@xrystal/core 3.46.0 → 3.47.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +35 -2
  2. package/package.json +5 -1
  3. package/x/bin/helpers/.generated/seed-from-tmp.mjs +8 -1
  4. package/x/bin/helpers/.generated/tmp-schema.mjs +10 -3
  5. package/x/bin/helpers/build-config.mjs +62 -9
  6. package/x/bin/helpers/project-artifacts.mjs +1 -0
  7. package/x/bin/scripts/clean-dist-tests.mjs +15 -5
  8. package/x/bin/scripts/fix-dist-imports.mjs +15 -5
  9. package/x/bin/scripts/minify-dist.mjs +15 -5
  10. package/x/dist/loader/configs/index.d.ts +2 -1
  11. package/x/dist/loader/configs/index.js +1 -1
  12. package/x/dist/loader/kafka/index.js +1 -1
  13. package/x/dist/loader/system/index.js +1 -1
  14. package/x/dist/project/index.js +1 -1
  15. package/x/dist/utils/constants/index.js +1 -1
  16. package/x/dist/utils/constants/package-root.js +1 -1
  17. package/x/dist/utils/helpers/context/index.js +1 -1
  18. package/x/dist/utils/helpers/core/handlebars-resolve.d.ts +2 -0
  19. package/x/dist/utils/helpers/core/handlebars-resolve.js +1 -0
  20. package/x/dist/utils/helpers/core/index.d.ts +1 -1
  21. package/x/dist/utils/helpers/core/index.js +1 -1
  22. package/x/dist/utils/helpers/core/tmp-layout.js +1 -1
  23. package/x/dist/utils/helpers/date/index.js +1 -1
  24. package/x/dist/utils/helpers/dispatch/index.js +1 -1
  25. package/x/dist/utils/helpers/framework/index.js +1 -1
  26. package/x/dist/utils/helpers/handlers/adapters.js +1 -1
  27. package/x/dist/utils/helpers/handlers/execute.js +1 -1
  28. package/x/dist/utils/helpers/handlers/index.js +1 -1
  29. package/x/dist/utils/helpers/middleware/index.js +1 -1
  30. package/x/dist/utils/helpers/path/index.d.ts +1 -0
  31. package/x/dist/utils/helpers/path/index.js +1 -1
  32. package/x/dist/utils/helpers/path/resolve-alias-path.d.ts +24 -0
  33. package/x/dist/utils/helpers/path/resolve-alias-path.js +1 -0
  34. package/x/dist/utils/helpers/protocol/index.js +1 -1
  35. package/x/dist/utils/helpers/runtime/shutdown.js +1 -1
  36. package/x/dist/utils/helpers/state/index.js +1 -1
  37. package/x/dist/utils/helpers/state/props-from-tmp.js +1 -1
  38. package/x/dist/utils/helpers/state/request-key-guard.js +1 -1
  39. package/x/dist/utils/helpers/state/scopes.js +1 -1
  40. package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -1
  41. package/x/dist/utils/helpers/tmp/runtime-tmp.js +1 -1
  42. package/x/dist/utils/helpers/tmp/seed-from-tmp.js +1 -1
  43. package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -1
  44. package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +1 -1
  45. package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -1
  46. package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -1
  47. package/x/dist/utils/helpers/tmp/toolchain-heal.js +2 -2
  48. package/x/dist/utils/models/classes/class.clients.js +1 -1
  49. package/x/dist/utils/models/classes/class.service-locator.js +1 -1
  50. package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -1
  51. package/x/dist/utils/models/classes/class.x.js +1 -1
  52. package/x/tmp.yml +1 -1
package/README.md CHANGED
@@ -142,13 +142,46 @@ configs:
142
142
  source: ./source
143
143
  protocols: [http]
144
144
  build:
145
- bundler: auto # auto | bun | tsc | esbuild
145
+ bundler: auto # auto → tsc (recommended) | bun | tsc | esbuild
146
+ typecheck: false # optional tsc --noEmit before emit
146
147
  loaders:
147
148
  dto: { withDefaultHeaders: true }
148
149
  loggers: { logLevel: info }
149
150
  controller: {}
150
151
  ```
151
152
 
153
+ ### Service build / Servis build
154
+
155
+ **EN:** `bundler: auto` → **`tsc`** (full `source/` tree → `x/dist`). Post-steps: `tsc-alias` → `fix-dist-imports` → `clean-dist-tests` (same as core). This keeps `loader/kafka`, relative imports, and `import.meta.url` paths valid in the container.
156
+
157
+ **TR:** `bundler: auto` → **`tsc`** (tüm `source/` ağacı `x/dist`'e). Sonrasında `tsc-alias` + import düzeltme — pod'da kafka/loader modülleri kaybolmaz.
158
+
159
+ | `build.bundler` | Behavior / Davranış |
160
+ |-----------------|---------------------|
161
+ | `auto` / `tsc` | Full tree emit via tsconfig `include` (recommended) |
162
+ | `bun` | Single entry `source/index.ts`, `--packages external` (not multi-entry) |
163
+ | `esbuild` | Single entry bundle; `@/` aliases need tsc or pre-alias |
164
+
165
+ **EN:** `@xrystal/core` itself uses a separate **core** build (package exports entries). Your service only builds **your** `source/` — `@xrystal/core` comes from `node_modules`.
166
+
167
+ **TR:** `@xrystal/core` paketi kendi core build'ini kullanır. Servis build'i sadece **senin** `source/` klasörünü derler; core `node_modules`'dan gelir.
168
+
169
+ ### Path alias `@/` / `@/` path alias
170
+
171
+ **EN:** `@/*` maps to your **source folder** (`source/*`), not project root — same as NestJS `@/` → `src/*`, not repo root.
172
+
173
+ **TR:** `@/*` proje root'u değil **source klasörünü** gösterir (`source/*`) — NestJS'teki `@/` → `src/*` gibi.
174
+
175
+ | Write / Yaz | Means / Anlam |
176
+ |-------------|---------------|
177
+ | `@/utils/foo` | `source/utils/foo` ✅ |
178
+ | `@/source/utils/foo` | legacy — treated as `@/utils/foo` |
179
+ | `logs` in tmp `loadPath` | relative to `paths.root` (`x/logs`) |
180
+
181
+ **EN:** `loadPath: '@/utils/helpers/configs/index'` resolves to `source/…` in dev and `x/dist/…` in prod when `source/` is absent.
182
+
183
+ **TR:** tmp.yml `loadPath` prod'da `source/` yoksa otomatik `x/dist/` fallback kullanır.
184
+
152
185
  ### First endpoint / İlk endpoint (~5 min)
153
186
 
154
187
  ```typescript
@@ -189,7 +222,7 @@ bun run dev
189
222
  | `xry tmp` | Create `tmp.yml` from seed if missing | `tmp.yml` yoksa seed'den oluştur |
190
223
  | `xry sync` | Force-sync `tsconfig` from `tmp.yml` (auto-heals otherwise) | Force sync (normalde otomatik) |
191
224
  | `xry dev` | Watch `source/index.ts` + dev env | `source/index.ts` watch + dev env |
192
- | `xry build` | Output → `x/dist` | Çıktı → `x/dist` |
225
+ | `xry build` | `tsc` full tree → dist (auto default) + alias/fix post-steps | `tsc` ile tüm `source/` → dist |
193
226
  | `xry start` | Run `x/dist` + prod env | `x/dist` + prod env |
194
227
  | `xry test` | Run `x/tests` | `x/tests` çalıştır |
195
228
  | `xry doctor` | CLI, runtime, package health | CLI, runtime, paket uyumu |
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Yusuf Yasir KAYGUSUZ",
3
3
  "name": "@xrystal/core",
4
- "version": "3.46.0",
4
+ "version": "3.47.6",
5
5
  "description": "microservice runtime library",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -35,6 +35,10 @@
35
35
  "types": "./x/dist/loader/index.d.ts",
36
36
  "default": "./x/dist/loader/index.js"
37
37
  },
38
+ "./loader/configs": {
39
+ "types": "./x/dist/loader/configs/index.d.ts",
40
+ "default": "./x/dist/loader/configs/index.js"
41
+ },
38
42
  "./loader/controller": {
39
43
  "types": "./x/dist/loader/controller/index.d.ts",
40
44
  "default": "./x/dist/loader/controller/index.js"
@@ -102,6 +102,13 @@ function readLayoutFromSpecial(special) {
102
102
  dist: requireString(block.dist, "configs.service.paths.special.dist")
103
103
  };
104
104
  }
105
+ function safeProcessCwd() {
106
+ try {
107
+ return process.cwd();
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
105
112
  function findBundledTmpFile(explicit) {
106
113
  if (explicit) {
107
114
  if (!fs.existsSync(explicit)) {
@@ -109,7 +116,7 @@ function findBundledTmpFile(explicit) {
109
116
  }
110
117
  return explicit;
111
118
  }
112
- const starts = [here, process.cwd()];
119
+ const starts = [here, safeProcessCwd()].filter((value) => Boolean(value));
113
120
  for (const start of starts) {
114
121
  let dir = path.resolve(start);
115
122
  for (;; ) {
@@ -129,6 +129,13 @@ function readLayoutFromSpecial(special) {
129
129
  dist: requireString(block.dist, "configs.service.paths.special.dist")
130
130
  };
131
131
  }
132
+ function safeProcessCwd() {
133
+ try {
134
+ return process.cwd();
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
132
139
  function findBundledTmpFile(explicit) {
133
140
  if (explicit) {
134
141
  if (!fs.existsSync(explicit)) {
@@ -136,7 +143,7 @@ function findBundledTmpFile(explicit) {
136
143
  }
137
144
  return explicit;
138
145
  }
139
- const starts = [here, process.cwd()];
146
+ const starts = [here, safeProcessCwd()].filter((value) => Boolean(value));
140
147
  for (const start of starts) {
141
148
  let dir = path.resolve(start);
142
149
  for (;; ) {
@@ -225,10 +232,10 @@ function normalizeBundler(value) {
225
232
  return "auto" /* AUTO */;
226
233
  throw new Error(`${defaults_default.packageName}: unknown build.bundler "${String(value)}" (expected ${Object.values(BundlerEnum).join("|")})`);
227
234
  }
228
- function resolveEffectiveBundler(bundler, runtime) {
235
+ function resolveEffectiveBundler(bundler, _runtime) {
229
236
  if (bundler !== "auto" /* AUTO */)
230
237
  return bundler;
231
- return runtime === "node" /* NODE */ ? "tsc" /* TSC */ : "bun" /* BUN */;
238
+ return "tsc" /* TSC */;
232
239
  }
233
240
  function normalizeRootFolder2(value) {
234
241
  return normalizeRootFolder(value, defaults_default.packageRootFolder);
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
3
4
  import yaml from 'yaml'
4
5
 
5
6
  import { packageDefaults } from '../paths.mjs'
@@ -15,6 +16,11 @@ import {
15
16
 
16
17
  import { CLI_BIN_NAMES, CLI_PRIMARY_NAME } from './cli-identity.mjs'
17
18
 
19
+ function resolveCoreScriptsBase() {
20
+ const here = path.dirname(fileURLToPath(import.meta.url))
21
+ return path.join(here, '..', 'scripts')
22
+ }
23
+
18
24
  function escapeRegExp(value) {
19
25
  return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
20
26
  }
@@ -134,6 +140,15 @@ export function declarationsFromTsconfig(compilerOptions = {}) {
134
140
  return undefined
135
141
  }
136
142
 
143
+ export function resolveServiceMainEntry(mainFolderPath, buildConfig = {}) {
144
+ if (Array.isArray(buildConfig.entries) && buildConfig.entries.length > 0) {
145
+ return buildConfig.entries.map(String)
146
+ }
147
+
148
+ const main = normalizeMainFolder(mainFolderPath)
149
+ return [`${main}/index.ts`]
150
+ }
151
+
137
152
  export function resolveBuildEntryGlobs(mainFolderPath, buildConfig = {}, tsconfig = null) {
138
153
  if (Array.isArray(buildConfig.entries) && buildConfig.entries.length > 0) {
139
154
  return buildConfig.entries.map(String)
@@ -268,14 +283,25 @@ export function resolveTscCommand(root, distRel, buildConfig = {}, runtime = det
268
283
  }
269
284
 
270
285
  export function resolveBunBuildCommand(entryGlobs, distRel, buildConfig = {}, tsconfig = null) {
286
+ const entries = (Array.isArray(entryGlobs) ? entryGlobs : [entryGlobs]).filter(Boolean)
271
287
  const sourcemapFlag = resolveSourcemapFlag(buildConfig, tsconfig)
272
288
  const minifyFlags = resolveMinifyFlags(buildConfig)
273
- const flags = [...minifyFlags, ...(sourcemapFlag ? [sourcemapFlag] : []), '--outdir', distRel, '--target', 'node', "--external", "'*'"]
274
- return `${getRuntimeTooling(RuntimeEnum.BUN).binRunner} build ${entryGlobs.join(' ')} ${flags.join(' ')}`.replace(/\s+/g, ' ').trim()
289
+ const flags = [
290
+ ...minifyFlags,
291
+ ...(sourcemapFlag ? [sourcemapFlag] : []),
292
+ '--outdir',
293
+ distRel,
294
+ '--target',
295
+ 'node',
296
+ '--packages',
297
+ 'external',
298
+ ]
299
+ return `${getRuntimeTooling(RuntimeEnum.BUN).binRunner} build ${entries.join(' ')} ${flags.join(' ')}`.replace(/\s+/g, ' ').trim()
275
300
  }
276
301
 
277
302
  export function resolveTscBuildCommand(root, distRel, buildConfig = {}, runtime = detectCliHostRuntime()) {
278
- return withTscProject(root, buildConfig, `--outDir ${distRel}`, runtime)
303
+ const cmd = withTscProject(root, buildConfig, `--outDir ${distRel}`, runtime)
304
+ return buildConfig.tscLenient ? `${cmd} || true` : cmd
279
305
  }
280
306
 
281
307
  export function resolveEsbuildBuildCommand(entryGlobs, distRel, buildConfig = {}, tsconfig = null, runtime = detectCliHostRuntime()) {
@@ -287,14 +313,37 @@ export function resolveEsbuildBuildCommand(entryGlobs, distRel, buildConfig = {}
287
313
  return `${bin} ${entries} --bundle --platform=node --packages=external --outdir=${distRel}${minify}${sourcemap}`.replace(/\s+/g, ' ').trim()
288
314
  }
289
315
 
290
- export function resolveServiceBundleCommand(root, plan, buildConfig = {}, runtime = detectCliHostRuntime(), bundler = normalizeBundler('bun')) {
316
+ export function resolveServiceBundleCommand(root, layout, plan, buildConfig = {}, runtime = detectCliHostRuntime(), bundler = normalizeBundler('bun')) {
317
+ const mainEntries = resolveServiceMainEntry(layout.mainFolderPath, buildConfig)
318
+
291
319
  if (bundler === BundlerEnum.TSC) {
292
320
  return resolveTscBuildCommand(root, plan.distRel, buildConfig, runtime)
293
321
  }
294
322
  if (bundler === BundlerEnum.ESBUILD) {
295
- return resolveEsbuildBuildCommand(plan.entryGlobs, plan.distRel, buildConfig, plan.tsconfig, runtime)
323
+ return resolveEsbuildBuildCommand(mainEntries, plan.distRel, buildConfig, plan.tsconfig, runtime)
296
324
  }
297
- return resolveBunBuildCommand(plan.entryGlobs, plan.distRel, buildConfig, plan.tsconfig)
325
+ return resolveBunBuildCommand(mainEntries, plan.distRel, buildConfig, plan.tsconfig)
326
+ }
327
+
328
+ export function resolveServicePostProcessSteps(root, distRel, buildConfig = {}, runtime = detectCliHostRuntime()) {
329
+ const tsconfigRel = resolveTsconfigRel(root, buildConfig)
330
+ if (!tsconfigRel) {
331
+ throw new Error('Service tsc build requires tsconfig.json (set build.tsconfig or add tsconfig.json).')
332
+ }
333
+
334
+ const host = getRuntimeTooling(runtime)
335
+ const aliasRunner = host.tscBin.trim().split(/\s+/)[0]
336
+ const scriptsBase = `node ${resolveCoreScriptsBase()}`
337
+ const distArg = distRel.includes(' ') ? `"${distRel}"` : distRel
338
+ const steps = [`${aliasRunner} tsc-alias -p ${tsconfigRel}`]
339
+
340
+ if (resolveMinifyEnabled(buildConfig)) {
341
+ steps.push(`${scriptsBase}/minify-dist.mjs ${distArg}`)
342
+ }
343
+
344
+ steps.push(`${scriptsBase}/fix-dist-imports.mjs ${distArg}`)
345
+ steps.push(`${scriptsBase}/clean-dist-tests.mjs ${distArg}`)
346
+ return steps
298
347
  }
299
348
 
300
349
  export function resolveEffectiveBuildOptions(root, layout, buildConfig = {}, runtime = detectCliHostRuntime()) {
@@ -339,7 +388,7 @@ export function resolveCoreBuildSteps(root, distRel, buildConfig = {}) {
339
388
  }
340
389
  const host = getRuntimeTooling(detectCliHostRuntime())
341
390
  const xBin = host.tscBin.trim().split(/\s+/)[0] // bunx | npx
342
- const scriptsBase = `node ${packageDefaults.packageRootFolder}/bin/scripts`
391
+ const scriptsBase = `node ${resolveCoreScriptsBase()}`
343
392
  const steps = [
344
393
  `${scriptsBase}/sync-cli-defaults.mjs`,
345
394
  `rm -rf ${distRel}`,
@@ -366,10 +415,14 @@ export function resolveServiceBuildSteps(root, layout, buildConfig = {}, runtime
366
415
 
367
416
  steps.push(
368
417
  `rm -rf ${plan.distRel}`,
369
- resolveServiceBundleCommand(root, plan, buildConfig, runtime, plan.bundler),
418
+ resolveServiceBundleCommand(root, layout, plan, buildConfig, runtime, plan.bundler),
370
419
  )
371
420
 
372
- if (plan.declarations && plan.bundler !== 'tsc') {
421
+ if (plan.bundler === BundlerEnum.TSC) {
422
+ steps.push(...resolveServicePostProcessSteps(root, plan.distRel, buildConfig, runtime))
423
+ }
424
+
425
+ if (plan.declarations && plan.bundler !== BundlerEnum.TSC) {
373
426
  steps.push(resolveTscCommand(root, plan.distRel, buildConfig, runtime))
374
427
  }
375
428
 
@@ -29,6 +29,7 @@ function cliGeneratedModules() {
29
29
  const CORE_EXPORT_SUBPATHS = [
30
30
  'utils',
31
31
  'loader',
32
+ 'loader/configs',
32
33
  'loader/controller',
33
34
  'loader/dto',
34
35
  'project',
@@ -3,11 +3,21 @@ import path from 'node:path'
3
3
 
4
4
  import { packageDefaults } from '../helpers/package-defaults.mjs'
5
5
 
6
- const distRoot = path.join(
7
- process.cwd(),
8
- packageDefaults.packageRootFolder,
9
- packageDefaults.layoutPaths.dist,
10
- )
6
+ const distRoot = resolveDistRootFromArgv()
7
+
8
+ function resolveDistRootFromArgv() {
9
+ const arg = process.argv[2]
10
+ if (arg && String(arg).trim()) {
11
+ const trimmed = String(arg).trim()
12
+ return path.isAbsolute(trimmed) ? trimmed : path.join(process.cwd(), trimmed)
13
+ }
14
+
15
+ return path.join(
16
+ process.cwd(),
17
+ packageDefaults.packageRootFolder,
18
+ packageDefaults.layoutPaths.dist,
19
+ )
20
+ }
11
21
  const TEST_FILE_RE = /\.test\.(js|d\.ts)$/
12
22
 
13
23
  export function cleanDistTests(distDir = distRoot) {
@@ -2,11 +2,21 @@ import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { packageDefaults } from '../helpers/package-defaults.mjs'
4
4
 
5
- const distRoot = path.join(
6
- process.cwd(),
7
- packageDefaults.packageRootFolder,
8
- packageDefaults.layoutPaths.dist,
9
- )
5
+ const distRoot = resolveDistRootFromArgv()
6
+
7
+ function resolveDistRootFromArgv() {
8
+ const arg = process.argv[2]
9
+ if (arg && String(arg).trim()) {
10
+ const trimmed = String(arg).trim()
11
+ return path.isAbsolute(trimmed) ? trimmed : path.join(process.cwd(), trimmed)
12
+ }
13
+
14
+ return path.join(
15
+ process.cwd(),
16
+ packageDefaults.packageRootFolder,
17
+ packageDefaults.layoutPaths.dist,
18
+ )
19
+ }
10
20
 
11
21
  const HAS_EXT = /\.(js|mjs|cjs|json|node|wasm)(\?.*)?$/i
12
22
 
@@ -5,11 +5,21 @@ import path from 'node:path'
5
5
  import { packageDefaults } from '../helpers/package-defaults.mjs'
6
6
  import { RuntimeEnum, getRuntimeTooling } from '../helpers/cli-runtime.mjs'
7
7
 
8
- const distRoot = path.join(
9
- process.cwd(),
10
- packageDefaults.packageRootFolder,
11
- packageDefaults.layoutPaths.dist,
12
- )
8
+ const distRoot = resolveDistRootFromArgv()
9
+
10
+ function resolveDistRootFromArgv() {
11
+ const arg = process.argv[2]
12
+ if (arg && String(arg).trim()) {
13
+ const trimmed = String(arg).trim()
14
+ return path.isAbsolute(trimmed) ? trimmed : path.join(process.cwd(), trimmed)
15
+ }
16
+
17
+ return path.join(
18
+ process.cwd(),
19
+ packageDefaults.packageRootFolder,
20
+ packageDefaults.layoutPaths.dist,
21
+ )
22
+ }
13
23
 
14
24
  function walkJsFiles(dir, out = []) {
15
25
  for (const name of fs.readdirSync(dir)) {
@@ -1,5 +1,6 @@
1
1
  import System from '../../loader/system';
2
- import { IProvide, ModeEnum } from '../../utils';
2
+ import { IProvide } from '../../utils/models/classes/class.interfaces';
3
+ import { ModeEnum } from '../../utils/models/enums';
3
4
  export interface IConfig {
4
5
  worker: boolean;
5
6
  mode: ModeEnum;
@@ -1 +1 @@
1
- import c from"node:path";import i from"lodash";import{pathToFileURL as l}from"node:url";import{bindLoaderTmpSync as v}from"../../utils";import{Constants as a}from"../../utils";export default class Configs{publicFolderName=a.publicFolderName;kafkaLogsTopic=a.kafkaLogsTopic;#s;#e;constructor({system:s}){this.#s=s;return new Proxy(this,{get:(o,r)=>{return o[r]||o.config?.[r]}})}onInit=async()=>{await this.syncFromTmp();v(this)};syncFromTmp=async()=>{const s=process.cwd(),e=this.#s.tmp,o=e.configs.service.loaders.configs.loadPath,r=o.startsWith("@/")?c.join(process.cwd(),o.slice(2)):c.resolve(e.configs.rootFolderPath,o),p=import(l(r).href);this.#e={worker:process.env.WORKER==="true"?!0:!1,mode:process.env.MODE,nodeEnv:"development",debug:process.env.SYSTEM_LOGGER_LAYER??"",https:process.env.HTTPS??"false",httpsfileEncoding:process.env.ENCODING||"utf8",httpsCertfile:process.env.HTTPS_CERT_FILE??"",httpsKeyfile:process.env.HTTPS_KEY_FILE??"",rootFolderPath:e.configs.rootFolderPath||"x",projectName:e.project.name,serviceName:e.configs.service.name??"",projectNamePrefixEnv:process.env.PROJECT_NAME_PREFIX||"",projectNameEnv:process.env.PROJECT_NAME||"",projectNameSuffixEnv:process.env.PROJECT_NAME_SUFFIX||"",systemStaticFolderPath:c.resolve(e.configs.rootFolderPath,this.publicFolderName),systemLoggerLayer:process.env.SYSTEM_LOGGER_LAYER??"info",isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaClientId:e.configs.service.name??"",kafkaBrokers:process.env.KAFKA_BROKERS??"",kafkaUsername:process.env.KAFKA_USERNAME??"",kafkaPassword:process.env.KAFKA_PASSWORD??"",kafkaTopics:[],kafkaLogsTopic:this.kafkaLogsTopic,baseApiUri:process.env.HTTPS==="true"?process.env.SYSTEM_HTTPS_BASE_API_URI??"":process.env.SYSTEM_BASE_API_URI??"",port:Number(process.env.PORT),internalSecret:process.env.INTERNAL_SECRET??"",secret:process.env.SECRET??"",cwd:s,env:"development"};try{const t=await p,f=t?.default||t?.configs||t||{},m=i.mergeWith({},this.#e,f,(n,E)=>{if(i.isArray(n))return n.concat(E)});this.#e=Object.freeze(m)}catch{this.#e=Object.freeze(this.#e)}};setConfig(s){const e=Object.assign(this.#e,s);this.#e=Object.freeze(e)}_(s){return this.#e[s]}get all(){return this.#e}}
1
+ import E from"node:path";import c from"lodash";import{pathToFileURL as l}from"node:url";import{Constants as i}from"../../utils/constants";import{resolveTmpLoadPath as v}from"../../utils/helpers/path/resolve-alias-path";import{bindLoaderTmpSync as h}from"../../utils/helpers/tmp/loader-tmp-sync";export default class Configs{publicFolderName=i.publicFolderName;kafkaLogsTopic=i.kafkaLogsTopic;#s;#e;constructor({system:s}){this.#s=s;return new Proxy(this,{get:(o,r)=>{return o[r]||o.config?.[r]}})}onInit=async()=>{await this.syncFromTmp();h(this)};syncFromTmp=async()=>{const s=process.cwd(),e=this.#s.tmp,o=e.configs.service.loaders.configs.loadPath,r=v(o,e,s),a=import(l(r).href);this.#e={worker:process.env.WORKER==="true"?!0:!1,mode:process.env.MODE,nodeEnv:"development",debug:process.env.SYSTEM_LOGGER_LAYER??"",https:process.env.HTTPS??"false",httpsfileEncoding:process.env.ENCODING||"utf8",httpsCertfile:process.env.HTTPS_CERT_FILE??"",httpsKeyfile:process.env.HTTPS_KEY_FILE??"",rootFolderPath:e.configs.rootFolderPath||"x",projectName:e.project.name,serviceName:e.configs.service.name??"",projectNamePrefixEnv:process.env.PROJECT_NAME_PREFIX||"",projectNameEnv:process.env.PROJECT_NAME||"",projectNameSuffixEnv:process.env.PROJECT_NAME_SUFFIX||"",systemStaticFolderPath:E.resolve(e.configs.rootFolderPath,this.publicFolderName),systemLoggerLayer:process.env.SYSTEM_LOGGER_LAYER??"info",isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaClientId:e.configs.service.name??"",kafkaBrokers:process.env.KAFKA_BROKERS??"",kafkaUsername:process.env.KAFKA_USERNAME??"",kafkaPassword:process.env.KAFKA_PASSWORD??"",kafkaTopics:[],kafkaLogsTopic:this.kafkaLogsTopic,baseApiUri:process.env.HTTPS==="true"?process.env.SYSTEM_HTTPS_BASE_API_URI??"":process.env.SYSTEM_BASE_API_URI??"",port:Number(process.env.PORT),internalSecret:process.env.INTERNAL_SECRET??"",secret:process.env.SECRET??"",cwd:s,env:"development"};try{const t=await a,p=t?.default||t?.configs||t||{},f=c.mergeWith({},this.#e,p,(n,m)=>{if(c.isArray(n))return n.concat(m)});this.#e=Object.freeze(f)}catch{this.#e=Object.freeze(this.#e)}};setConfig(s){const e=Object.assign(this.#e,s);this.#e=Object.freeze(e)}_(s){return this.#e[s]}get all(){return this.#e}}
@@ -1 +1 @@
1
- import{Kafka as M,logLevel as N}from"kafkajs";import{bindLoaderTmpSync as O}from"../../utils";export default class KafkaForCore{_instance;_producer;clientId="";brokers="";username=null;password=null;#q;#h;constructor({system:h,configs:q}){this.#q=h;this.#h=q}onDispose=async()=>{await this.teardownKafka()};onInit=async()=>{await this.syncFromTmp();O(this)};syncFromTmp=async()=>{await this.teardownKafka();this.clientId=this.#h.all?.kafkaClientId;this.brokers=this.#h.all?.kafkaBrokers;this.username=this.#h.all?.kafkaUsername;this.password=this.#h.all?.kafkaPassword;if(this.#h.all.isKafkaPassive)return;const h=(Array.isArray(this.brokers)?this.brokers:this.brokers?.split(",")??[]).map((q)=>q?.trim()).filter(Boolean);if(h.length===0)throw Error("Broker list error");await this.kafkaLoader({clientId:this.clientId,brokers:h,username:this.username,password:this.password});await this.initializeKafkaInfrastructure()};teardownKafka=async()=>{if(this._producer){try{await this._producer.disconnect()}catch{}this._producer=void 0}};kafkaLoader=async({clientId:h,brokers:q,username:F,password:E})=>{const D={clientId:h,brokers:q,sasl:F&&E?{mechanism:"plain",username:F,password:E}:void 0,ssl:!1,logLevel:N.ERROR,logCreator:()=>{return({level:z,log:G})=>{console.error(`Kafka ${G.message}`)}},retry:{initialRetryTime:100,retries:8}};try{const z=new M(D);this._instance=z;this._producer=z.producer();await this.producer.connect();return z}catch(z){console.error(`Kafka ${z}`)}};initializeKafkaInfrastructure=async()=>{const{kafkaBrokers:h,kafkaTopics:q,isKafkaPassive:F}={isKafkaPassive:process.env.IS_KAFKA_PASSIVE==="true"?!0:!1,kafkaBrokers:process.env?.KAFKA_BROKERS,kafkaTopics:[...new Set([...this.#h.all.kafkaTopics])]};if(F===!0||!h)return;const E=Array.isArray(q)?q:[];if(E.length===0)return;const D=this._instance.admin();try{await D.connect();const z=await D.listTopics(),G=E.filter((J)=>!z.includes(J)).map((J)=>({topic:J,numPartitions:1,replicationFactor:1}));if(G.length>0)await D.createTopics({waitForLeaders:!0,topics:G})}catch(z){}finally{await D.disconnect()}};sendMessage=async(h,q)=>{if(!this.producer)throw Error("Producer not ready");await this.producer.send({topic:h,messages:[{value:JSON.stringify(q)}],acks:0})};get producer(){return this._producer}get instance(){return this._instance}}
1
+ import{Kafka as c,logLevel as l}from"kafkajs";import{bindLoaderTmpSync as k}from"../../utils";export default class KafkaForCore{_instance;_producer;clientId="";brokers="";username=null;password=null;#r;#a;constructor({system:a,configs:r}){this.#r=a;this.#a=r}onDispose=async()=>{await this.teardownKafka()};onInit=async()=>{await this.syncFromTmp();k(this)};syncFromTmp=async()=>{await this.teardownKafka();this.clientId=this.#a.all?.kafkaClientId;this.brokers=this.#a.all?.kafkaBrokers;this.username=this.#a.all?.kafkaUsername;this.password=this.#a.all?.kafkaPassword;if(this.#a.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:!1,logLevel:l.ERROR,logCreator:()=>{return({level:s,log:n})=>{console.error(`Kafka ${n.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.#a.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(),n=t.filter((o)=>!s.includes(o)).map((o)=>({topic:o,numPartitions:1,replicationFactor:1}));if(n.length>0)await e.createTopics({waitForLeaders:!0,topics:n})}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{G as k,notifyRuntimeTmpChange as q,onTmpReload as v,setRuntimeTmpConfigs as w}from"../../utils";import{normalizeTmpDocument as x}from"../../utils/helpers/tmp/tmp-schema";export default class System{_core={};_tmp={};cwd=process.cwd();g=k;onInit=async({core:j})=>{this._core=j;await this.applyTmp(this._core._);v((b)=>void this.applyTmp(b))};async applyTmp(j){this._tmp=x(j);const b=this._tmp.configs;w(b);this.g.configureFromTmp(this._tmp);await q(b)}get core(){return this._core}get tmp(){return this._tmp}}
1
+ import{G as m,notifyRuntimeTmpChange as o,onTmpReload as p,setRuntimeTmpConfigs as s}from"../../utils";import{normalizeTmpDocument as e}from"../../utils/helpers/tmp/tmp-schema";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}}
@@ -1 +1 @@
1
- import A from"path";import{fileURLToPath as O}from"node:url";import{System as Q,Configs as V,Logger as W,Events as X,Localizations as Y,DtoRuntime as Z,Clients as _,Controller as $,KafkaForCore as v}from"../loader";import{Constants as z,getCore as F,x as K}from"../utils";import{ensureCoreTmpEntry as U,isCorePackageRoot as b}from"../utils/helpers/core/tmp-layout";import{getTmpSnapshot as j}from"../utils/helpers/tmp/tmp-loader";export{ensureCoreTmpEntry,isCorePackageRoot}from"../utils/helpers/core/tmp-layout";export{getTmpSnapshot}from"../utils/helpers/tmp/tmp-loader";export const core=F(),coreInit=async(B)=>{const{locales:q}=B;if(q)globalThis.__LOCAL_MESSAGES__=q};let I=!1;const J=A.dirname(O(import.meta.url)),k=A.join(J,"..","loader","**/*.{ts,js}"),x=A.join(J,"..","utils","**/class.x.{ts,js}"),G=async(B={})=>{if(I)return core;const q=process.cwd();if(b(q))U(q);j();try{await(await K.load([k],{exclude:[x]})).initialize([{service:Q,props:{core}},{service:V,props:{}},{service:v,props:{}},{service:W,props:{}},{service:X,props:{}},{service:Y,props:{}},{service:Z,props:{}},{service:$,props:{}},{service:_,props:{}}]);I=!0;return core}catch(w){const N=w instanceof Error?w.message:String(w);console.error(`[${z.packageName} core failure]: ${N}`);throw w}};export default G;
1
+ import e from"path";import{fileURLToPath as p}from"node:url";import{System as c,Configs as n,Logger as l,Events as m,Localizations as f,DtoRuntime as u,Clients as g,Controller as d,KafkaForCore as C}from"../loader";import{Constants as v,getCore as x,x as h}from"../utils";import{ensureCoreTmpEntry as E,isCorePackageRoot as S}from"../utils/helpers/core/tmp-layout";import{getTmpSnapshot as y}from"../utils/helpers/tmp/tmp-loader";export{ensureCoreTmpEntry,isCorePackageRoot}from"../utils/helpers/core/tmp-layout";export{getTmpSnapshot}from"../utils/helpers/tmp/tmp-loader";export const core=x(),coreInit=async(s)=>{const{locales:o}=s;if(o)globalThis.__LOCAL_MESSAGES__=o};let t=!1;const a=e.dirname(p(import.meta.url)),L=e.join(a,"..","loader","**/*.{ts,js}"),T=e.join(a,"..","utils","**/class.x.{ts,js}"),_=async(s={})=>{if(t)return core;const o=process.cwd();if(S(o))E(o);y();try{await(await h.load([L],{exclude:[T]})).initialize([{service:c,props:{core}},{service:n,props:{}},{service:C,props:{}},{service:l,props:{}},{service:m,props:{}},{service:f,props:{}},{service:u,props:{}},{service:d,props:{}},{service:g,props:{}}]);t=!0;return core}catch(r){const i=r instanceof Error?r.message:String(r);console.error(`[${v.packageName} core failure]: ${i}`);throw r}};export default _;
@@ -1 +1 @@
1
- import w from"node:path";import{packageRootDir as x}from"../../utils/constants/package-root";import b from"./defaults.json" with { type: 'json' };import{seedFromTmp as j}from"../../utils/helpers/tmp/seed-from-tmp";export const packageDefaults=Object.freeze({...b,mainSourceFolder:j.sourceFolder,framework:j.framework,layoutPaths:Object.freeze({...j.layout}),brand:Object.freeze({...b.brand}),runtimes:Object.freeze(Object.fromEntries(Object.entries(b.runtimes).map(([n,q])=>[n,Object.freeze({...q})]))),bundlers:Object.freeze([...b.bundlers]),buildDefaults:Object.freeze({...b.buildDefaults}),tmpWatchDefaults:Object.freeze({...b.tmpWatchDefaults}),cliBinNames:Object.freeze([...b.cliBinNames??[b.cliName]])}),coreVersionPattern=/^\d{2}\.\d{2}\.\d{2}-v\d+$/,semverVersionPattern=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/;const z=`${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=w.join(x,packageDefaults.packageRootFolder,z)}export{seedFromTmp,loadSeedFromBundledTmp}from"../../utils/helpers/tmp/seed-from-tmp";
1
+ import r from"node:path";import{packageRootDir as i}from"../../utils/constants/package-root";import e from"./defaults.json" with { type: 'json' };import{seedFromTmp as t}from"../../utils/helpers/tmp/seed-from-tmp";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";
@@ -1 +1 @@
1
- import b from"node:path";import{fileURLToPath as w}from"node:url";const q=b.dirname(w(import.meta.url));export const sourceDir=b.resolve(q,"..",".."),packageRootDir=b.resolve(q,"..","..","..");
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 w}from"node:async_hooks";export const runContextStorage=new w;export function getRunContext(){return runContextStorage.getStore()}export function getRequestId(){return getRunContext()?.requestId}export function runWithContext(m,j){return runContextStorage.run(m,j)}export function runWithRequestId(m,j,v="http"){return runWithContext({requestId:m,kind:v},j)}export function runWithTrace(m,j,v){return runWithContext({requestId:m,kind:"job",label:v},j)}export function patchRunContext(m){const j=getRunContext();if(!j)return;Object.assign(j,m)}export{controllerContextStorage,getControllerCtx,runControllerStore,adapterBagFromRequest,isFetchRequest}from"../../../utils/helpers/context/controller-store";
1
+ import{AsyncLocalStorage as 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";
@@ -0,0 +1,2 @@
1
+ /** Interpolate tmp.yml strings/objects with Handlebars (no utils barrel — safe for TmpFileLoader). */
2
+ export declare function resolveObjWithHandlebars(obj: unknown, context: unknown): unknown;
@@ -0,0 +1 @@
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,6 +1,7 @@
1
1
  import { ProtocolEnum } from '../../../utils/index.js';
2
2
  export * from '../../../utils/helpers/core/paths';
3
3
  export * from '../../../utils/helpers/core/tmp-layout';
4
+ export { resolveObjWithHandlebars } from '../../../utils/helpers/core/handlebars-resolve';
4
5
  export declare const getCore: () => {
5
6
  _: Record<string, unknown>;
6
7
  };
@@ -9,7 +10,6 @@ export declare const getTmpConfig: ({ root, tmpFileName, ext, }?: {
9
10
  tmpFileName?: string;
10
11
  ext?: string;
11
12
  }) => Record<string, unknown>;
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>;
15
15
  export declare const argvsConverter: (argvs: string) => {
@@ -1 +1 @@
1
- import M from"handlebars";import{Constants as I,ProtocolEnum as J,TmpFileLoader as Q}from"../../../utils/index.js";import{controllerContextStorage as U}from"../../../utils/helpers/context/controller-store";import{getTmpSnapshot as V}from"../../../utils/helpers/tmp/tmp-loader";import{findFileRecursively as X}from"../../../utils/helpers/core/paths";import{parseProtocol as Y}from"../../../utils/helpers/protocol/index.js";export*from"../../../utils/helpers/core/paths";export*from"../../../utils/helpers/core/tmp-layout";export const getCore=()=>({_:V()}),getTmpConfig=({root:q=process.cwd(),tmpFileName:z=I.tmpBaseName,ext:B=I.tmpExtension}={})=>{const D=X(q,z,B);if(!D)throw Error(`${z}${B.startsWith(".")?B:`.${B}`} file not found`);return new Q({filePath:D}).getResolvedTmpFile()};export function resolveObjWithHandlebars(q,z){if(typeof q==="string")return M.compile(q)(z);else if(typeof q==="object"&&q!==null)for(const B in q)q[B]=resolveObjWithHandlebars(q[B],z);return q}export const withProtocol=async(q,z=J.HTTP)=>{const B=Y(z),D=U.getStore();if(D)D.protocol=B;return await q()},protocol=async(q,z=J.HTTP)=>withProtocol(q,z),argvsConverter=(q)=>{const z=q?.slice(2),B={};z.forEach((D)=>{if(D.startsWith("--")){console.log(D);const[G,K]=D.split("=");B[G.replace("--","")]=K||""}});return B},findExt=(q)=>{const z=q.split(".");return z[z.length-1]},changeExtensions=(q,z)=>{return q.replace(findExt(q),z)};
1
+ import{Constants as n,ProtocolEnum as c,TmpFileLoader as l}from"../../../utils/index.js";import{controllerContextStorage as i}from"../../../utils/helpers/context/controller-store";import{getTmpSnapshot as a}from"../../../utils/helpers/tmp/tmp-loader";import{findFileRecursively as m}from"../../../utils/helpers/core/paths";import{parseProtocol as f}from"../../../utils/helpers/protocol/index.js";export*from"../../../utils/helpers/core/paths";export*from"../../../utils/helpers/core/tmp-layout";export{resolveObjWithHandlebars}from"../../../utils/helpers/core/handlebars-resolve";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 U from"node:fs";import J from"node:path";import z from"yaml";import{Constants as I}from"../../../utils/constants";import{findAllFilesRecursively as L,findFileRecursively as A}from"../../../utils/helpers/core/paths";import{normalizeTmpDocument as D,readTmpServiceBlock as B,normalizeRootFolder as b,normalizeSourceFolder as x,resolveServiceLayoutPaths as k}from"../../../utils/helpers/tmp/tmp-schema";function M(E,q){return`${E}${q.startsWith(".")?q:`.${q}`}`}export function coreCanonicalTmpPath(E=process.cwd()){return J.join(J.resolve(E),I.packageRootFolder,M(I.tmpBaseName,I.tmpExtension))}export function assertCoreTmpGuard(E,q){if(!isCorePackageRoot(E))return;const H=coreCanonicalTmpPath(E);if(J.resolve(q)!==J.resolve(H))throw Error(`${I.packageName}: tmp.yml must stay at ${I.packageRootFolder}/tmp.yml (expected ${H}, got ${q})`)}function N(E,q){const H=J.resolve(E),K=J.resolve(q);return L(H,I.tmpBaseName,I.tmpExtension).filter((Q)=>J.resolve(Q)!==K)}export function ensureCoreTmpEntry(E=process.cwd(),q={}){const H=J.resolve(E);if(!isCorePackageRoot(H))throw Error(`ensureCoreTmpEntry is only for ${I.packageName} package root`);const K=coreCanonicalTmpPath(H),Q=N(H,K);if(Q.length>0){const X=Q.map((W)=>J.relative(H,W)).join(", ");throw Error(`${I.packageName}: tmp.yml must only exist under ${I.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=J.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=J.join(J.resolve(E),"package.json");if(!U.existsSync(q))return!1;try{return JSON.parse(U.readFileSync(q,"utf8")).name===I.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=J.relative(J.resolve(H),J.dirname(J.resolve(q)));if(W&&W!==".")return W;return I.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 I.mainSourceFolder}export function buildTmpLayout(E,q,H){const K=J.resolve(E),Q=q?D(q).configs:void 0,X=q&&H&&!isCorePackageRoot(K)?resolveRootFolderPath(q,H,K):I.packageRootFolder,W=J.join(K,X),Y=resolveLayoutPaths(Q),V=resolveMainFolderPath(Q),Z={tests:J.join(W,Y.tests),environments:J.join(W,Y.environments),dist:J.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??I.tmpBaseName,K=q.ext??I.tmpExtension,Q=S(E,H,K);if(!Q)throw Error(`${M(H,K)} not found under ${J.resolve(E)}`);if(isCorePackageRoot(J.resolve(E)))assertCoreTmpGuard(E,Q);return buildTmpLayout(E,_(Q),Q)}export function resolveTmpLayoutOrDefaults(E=process.cwd()){const q=S(E,I.tmpBaseName,I.tmpExtension);if(!q)return buildTmpLayout(E,null,null);return buildTmpLayout(E,_(q),q)}export function resolveBundledCoreTmpPath(E=process.cwd()){if(U.existsSync(I.bundledCoreTmpPath))return I.bundledCoreTmpPath;let q=J.resolve(E);while(q!==J.dirname(q)){const H=J.join(q,"node_modules","@xrystal","core",I.packageRootFolder,M(I.tmpBaseName,I.tmpExtension));if(U.existsSync(H))return H;const K=J.join(q,"package.json");if(U.existsSync(K)){if(JSON.parse(U.readFileSync(K,"utf8")).name===I.packageName){const X=J.join(q,I.packageRootFolder,M(I.tmpBaseName,I.tmpExtension));if(U.existsSync(X))return X}}q=J.dirname(q)}throw Error(`${I.packageName} bundled ${I.packageRootFolder}/tmp.yml not found`)}export function ownerTmpFilePath(E=process.cwd(),q){const H=q??resolveTmpLayoutOrDefaults(E);return J.join(H.rootFolderAbs,M(I.tmpBaseName,I.tmpExtension))}export function ensureTmpFile(E=process.cwd(),q={}){const H=J.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)=>J.relative(H,w)).join(", ");throw Error(`${I.packageName}: tmp.yml must only exist under ${I.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,I.tmpBaseName,I.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(`${I.packageName} bundled ${I.packageRootFolder}/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=J.join(H,"package.json");if(U.existsSync(V)){const Z=JSON.parse(U.readFileSync(V,"utf8")),$=typeof Z.name==="string"?Z.name.replace(/^@/,"").replace(/\//g,"-"):null;if($){const w=z.parse(Y),G=w.configs??{},O=G.service;if(typeof O==="object"&&O!==null&&!Array.isArray(O))O.name=$;else G.service={name:$};w.configs=G;Y=z.stringify(w)}}}catch{}U.writeFileSync(W,Y);return{tmpFilePath:W,created:!0,layout:buildTmpLayout(H,_(W),W)}}export function resolveTmpLayoutEnsured(E=process.cwd()){return ensureTmpFile(E).layout}
1
+ import c from"node:fs";import n from"node:path";import x from"yaml";import{Constants as r}from"../../../utils/constants";import{findAllFilesRecursively as P,findFileRecursively as k}from"../../../utils/helpers/core/paths";import{normalizeTmpDocument as S,readTmpServiceBlock as F,normalizeRootFolder as T,normalizeSourceFolder as E,resolveServiceLayoutPaths as R}from"../../../utils/helpers/tmp/tmp-schema";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 $}from"../../../utils/models";export function dateZoneConverter({polarity:e,date:o,zone:n,factor:r=1000}){let s=null;if(e===$.NEGATIVE)s=o.getTime()-r*n;else s=o.getTime()+r*n;return new Date(s).toISOString()}export function convertDate(e,o="/",n="-"){return e.split(o).map((s,t)=>t!==2?n:s)}export function convertTime(e,o=":",n="-"){return e.split(o).map((s,t)=>t!==2?n:s)}export function getDateAndTime({getDate:e=!0,getTime:o=!0,dateCharacter:n="-",timeCharacter:r=":",separatorCharacter:s="&"}){const t=new Date;let u="";if(!e&&!o)throw Error("Invalid options! Required one true value");if(e){const i=t.getDate().toString().padStart(2,"0"),a=(t.getMonth()+1).toString().padStart(2,"0");u=`${t.getFullYear()}${n}${a}${n}${i}`}if(o){const i=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0"),S=t.getSeconds().toString().padStart(2,"0");u=`${i}${r}${a}${r}${S}`}if(e&&o){const i=t.getDate().toString().padStart(2,"0"),a=(t.getMonth()+1).toString().padStart(2,"0"),S=t.getFullYear(),c=t.getHours().toString().padStart(2,"0"),g=t.getMinutes().toString().padStart(2,"0"),p=t.getSeconds().toString().padStart(2,"0");u=`${S}${n}${a}${n}${i}${s}${c}${r}${g}${r}${p}`}return u}
1
+ import{PolarityTypeEnum as d}from"../../../utils/models";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 J}from"@xrystal/dto/express";import{nodeSink as K}from"@xrystal/dto/node";import{fetchSink as L}from"@xrystal/dto/fetch";import{elysiaSink as M}from"@xrystal/dto/elysia";import{websocketSink as N}from"@xrystal/dto/websocket";import{socketIoSink as Q}from"@xrystal/dto/socketio";import{FrameworkEnum as z,ProtocolEnum as C}from"../../../utils/models";import{getFramework as T}from"../../../utils/helpers/framework";import{getDtoRuntime as U}from"../../../utils/helpers/runtime";export{expressSink}from"@xrystal/dto/express";export{nodeSink}from"@xrystal/dto/node";export{fetchSink}from"@xrystal/dto/fetch";export{elysiaSink}from"@xrystal/dto/elysia";export{websocketSink}from"@xrystal/dto/websocket";export{socketIoSink}from"@xrystal/dto/socketio";export{dispatchExpressResponse,dispatchNodeResponse,toFetchResponse,applyElysiaTransport,dispatchWebSocketMessage,dispatchSocketIoMessage}from"@xrystal/dto/response";const V=(j)=>!!j&&typeof j==="object"&&("body"in j)&&("statusCode"in j),W=(j)=>j instanceof Response||j instanceof Blob||j instanceof Uint8Array||j instanceof ArrayBuffer,G=(j)=>j.socket??j.ctx?.ws??j.ctx,X=()=>U().config.socket?.event??"response";export function dispatchResult(j,q,B){if(j===void 0||j===null)return;if(W(j))return j;if(!V(j))return j;if(q.protocol===C.SOCKETIO||q.framework===z.SOCKETIO){Q(G(q),X()).dispatch(j);return}if(q.protocol===C.WEBSOCKET||q.framework===z.WEBSOCKET){N(G(q)).dispatch(j);return}const H=q.framework??T(),A=B;switch(H){case z.EXPRESS:if(A&&!A.headersSent)J(B).dispatch(j);return;case z.NODE:if(A&&!A.headersSent)K(B).dispatch(j);return;case z.FETCH:return L.dispatch(j);case z.ELYSIA:default:return M(q.ctx?.set??{}).dispatch(j)}}
1
+ 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";import{getFramework as d}from"../../../utils/helpers/framework";import{getDtoRuntime as h}from"../../../utils/helpers/runtime";export{expressSink}from"@xrystal/dto/express";export{nodeSink}from"@xrystal/dto/node";export{fetchSink}from"@xrystal/dto/fetch";export{elysiaSink}from"@xrystal/dto/elysia";export{websocketSink}from"@xrystal/dto/websocket";export{socketIoSink}from"@xrystal/dto/socketio";export{dispatchExpressResponse,dispatchNodeResponse,toFetchResponse,applyElysiaTransport,dispatchWebSocketMessage,dispatchSocketIoMessage}from"@xrystal/dto/response";const 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 q}from"../../../utils/helpers/tmp/runtime-tmp";import{FrameworkEnum as j}from"../../../utils/models";const x=new Set(Object.values(j));export function parseFramework(b){const c=b?String(b).toLowerCase():void 0;return c&&x.has(c)?c:j.ELYSIA}export function getFramework(b){if(b)return b;try{return parseFramework(q()?.service?.framework)}catch{return j.ELYSIA}}
1
+ import{getRuntimeTmpConfigs as n}from"../../../utils/helpers/tmp/runtime-tmp";import{FrameworkEnum as t}from"../../../utils/models";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 G,ProtocolEnum as K}from"../../../utils/models";import{detectSocketProtocol as L}from"../../../utils/helpers/protocol";import{getFramework as M}from"../../../utils/helpers/framework";import{runAction as I}from"../../../utils/helpers/handlers/execute";import{Constants as N}from"../../../utils/constants";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(`[${N.packageName}] realtime: ctr({ ... }, { protocol: "ws" | "socketio" })`);default:return(j)=>I({framework:G.ELYSIA,ctx:j},z)}},toWebSocket=(z,D)=>toRealtimeHandler(D,K.WEBSOCKET)(z),toSocketIo=(z,D)=>toRealtimeHandler(D,K.SOCKETIO)(z);
1
+ import{FrameworkEnum as a,ProtocolEnum as s}from"../../../utils/models";import{detectSocketProtocol as l}from"../../../utils/helpers/protocol";import{getFramework as E}from"../../../utils/helpers/framework";import{runAction as m}from"../../../utils/helpers/handlers/execute";import{Constants as u}from"../../../utils/constants";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 Q}from"node:crypto";import{FrameworkEnum as V,ProtocolEnum as X}from"../../../utils/models";import{runControllerStore as Y}from"../../../utils/helpers/context";import{runWithRequestId as Z}from"../../../utils/helpers/context";import{dispatchResult as _}from"../../../utils/helpers/dispatch";import{getFramework as $}from"../../../utils/helpers/framework";import{attachSocketTransport as x,isRealtimeProtocol as H}from"../../../utils/helpers/protocol";import{getDtoRuntime as J}from"../../../utils/helpers/runtime";export const runController=Y;const B=(b)=>({framework:b.framework??(H(b.protocol)?void 0:$()),protocol:b.protocol??X.HTTP,...b,metadata:{locals:{},...b.metadata}}),M=(b,z)=>{if(!b)return;if(b instanceof Headers)return b.get(z)??b.get(z.toLowerCase());if(typeof b.get==="function"){const j=b.get;return j(z)??j(z.toLowerCase())}const A=b;return A[z]??A[z.toLowerCase()]},K=(b)=>{const z=b.ctx??{},A=b.req??{},j=A.headers??z.request?.headers;return b.requestId??z.requestId??A.ctx?.requestId??M(j,"x-request-id")??M(j,"x-correlation-id")??""},T=(b)=>{const z=String(K(b)||Q());b.requestId=z;b.ctx={...b.ctx,requestId:z};if(b.req)b.req.ctx={...b.req.ctx,requestId:z};return z},W=(b)=>{if(b.framework!==V.FETCH||b.ctx?.builder)return;const z=b.ctx?.request??b.req;if(!(z instanceof Request))return;b.ctx={...b.ctx,...J().forRequest(z)};if(b.ctx.requestId)b.requestId=String(b.ctx.requestId)},v=async(b,z,A)=>{const j=_(b,z,A),G=A;if(j instanceof Response&&G?.send){G.status?.(j.status);j.headers.forEach((N,O)=>G.setHeader?.(O,N));const L=j.headers.get("content-type")||"";if(L.includes("json")||L.includes("text/"))return G.send(await j.text());return G.send(Buffer.from(await j.arrayBuffer()))}return j},y=(b)=>H(b.protocol)?"ws":"http";export async function runAction(b,z,A){const j=B(b);if(H(j.protocol)&&j.socket&&!j.socket.builder)x(j.socket,j.protocol,J());W(j);const G=T(j);return Z(G,()=>runController(j,async()=>v(await z(),j,A)),y(j))}export function configureDto(b,z){return J().configure(b,z)}
1
+ import{randomUUID as a}from"node:crypto";import{FrameworkEnum as m,ProtocolEnum as q}from"../../../utils/models";import{runControllerStore as x}from"../../../utils/helpers/context";import{runWithRequestId as p}from"../../../utils/helpers/context";import{dispatchResult as l}from"../../../utils/helpers/dispatch";import{getFramework as I}from"../../../utils/helpers/framework";import{attachSocketTransport as g,isRealtimeProtocol as c}from"../../../utils/helpers/protocol";import{getDtoRuntime as s}from"../../../utils/helpers/runtime";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 A}from"../../../utils/models";import{createDtoMiddleware as q}from"../../../utils/helpers/middleware";import{attachSocketTransport as B,detectSocketProtocol as C,resolveRealtimeMiddlewareProtocol as D}from"../../../utils/helpers/protocol";import{getDtoRuntime as j}from"../../../utils/helpers/runtime";export{runAction,runController,configureDto}from"../../../utils/helpers/handlers/execute";export{toHandler,toRealtimeHandler,toWebSocket,toSocketIo}from"../../../utils/helpers/handlers/adapters";export{getFramework}from"../../../utils/helpers/framework";export{dispatchResult}from"../../../utils/helpers/dispatch";export{getRequestId,getRunContext,runWithContext,runWithRequestId,runWithTrace}from"../../../utils/helpers/context";export{G,propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey,GStoreScopeEnum}from"../../../utils/helpers/state";export{bindLoaderTmpSync,getRuntimeTmpConfigs,setRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,getTmpSnapshot,onTmpReload}from"../../../utils/helpers/tmp";export{normalizeFrameworkKind,createDtoMiddleware,resolveDtoAdapter}from"../../../utils/helpers/middleware";export{resolveCtrOptions}from"../../../utils/helpers/protocol/options";export{parseProtocol,getConfiguredProtocols,getConfiguredRealtimeProtocols,defaultRealtimeProtocolFromConfig,getDefaultRealtimeProtocol,resolveRealtimeMiddlewareProtocol,detectSocketProtocol,isRealtimeProtocol,isHttpProtocol,resolveProtocolsFromConfig,REALTIME_MIDDLEWARE_HINT}from"../../../utils/helpers/protocol";export{getDtoRuntime}from"../../../utils/helpers/runtime";export const dtoMiddleware=(b)=>q(j(),b);export function realtimeMiddleware(b){const z=D(b);return(u,y)=>{try{const h=C(u,z);B(u,h,j());y?.()}catch(h){y?.(h instanceof Error?h:Error(String(h)))}}}export const websocketMiddleware=(b)=>b?q(j(),b):realtimeMiddleware("ws"),socketIoMiddleware=(b)=>b?q(j(),b??A.SOCKETIO):realtimeMiddleware("socketio");
1
+ import{FrameworkEnum as l}from"../../../utils/models";import{createDtoMiddleware as r}from"../../../utils/helpers/middleware";import{attachSocketTransport as a,detectSocketProtocol as c,resolveRealtimeMiddlewareProtocol as p}from"../../../utils/helpers/protocol";import{getDtoRuntime as t}from"../../../utils/helpers/runtime";export{runAction,runController,configureDto}from"../../../utils/helpers/handlers/execute";export{toHandler,toRealtimeHandler,toWebSocket,toSocketIo}from"../../../utils/helpers/handlers/adapters";export{getFramework}from"../../../utils/helpers/framework";export{dispatchResult}from"../../../utils/helpers/dispatch";export{getRequestId,getRunContext,runWithContext,runWithRequestId,runWithTrace}from"../../../utils/helpers/context";export{G,propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey,GStoreScopeEnum}from"../../../utils/helpers/state";export{bindLoaderTmpSync,getRuntimeTmpConfigs,setRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,getTmpSnapshot,onTmpReload}from"../../../utils/helpers/tmp";export{normalizeFrameworkKind,createDtoMiddleware,resolveDtoAdapter}from"../../../utils/helpers/middleware";export{resolveCtrOptions}from"../../../utils/helpers/protocol/options";export{parseProtocol,getConfiguredProtocols,getConfiguredRealtimeProtocols,defaultRealtimeProtocolFromConfig,getDefaultRealtimeProtocol,resolveRealtimeMiddlewareProtocol,detectSocketProtocol,isRealtimeProtocol,isHttpProtocol,resolveProtocolsFromConfig,REALTIME_MIDDLEWARE_HINT}from"../../../utils/helpers/protocol";export{getDtoRuntime}from"../../../utils/helpers/runtime";export const dtoMiddleware=(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
- import{FrameworkEnum as j}from"../../../utils/models";import{getFramework as x,parseFramework as C}from"../../../utils/helpers/framework";const G={express:j.EXPRESS,elysia:j.ELYSIA,node:j.NODE,fetch:j.FETCH,websocket:j.WEBSOCKET,ws:j.WEBSOCKET,socketio:j.SOCKETIO};export function normalizeFrameworkKind(b){if(b===void 0)return x();const q=typeof b==="object"&&b!==null&&"framework"in b?b.framework:b;if(!q)return x();const B=String(q).toLowerCase().replace(/[-_\s]/g,"");return G[B]??C(q)}export function resolveDtoAdapter(b,q){switch(q){case j.ELYSIA:return b.elysia();case j.NODE:return b.node();case j.SOCKETIO:return b.socketIo();case j.WEBSOCKET:return b.websocket();case j.FETCH:return null;case j.EXPRESS:return b.express();default:return b.elysia()}}export function createDtoMiddleware(b,q){return resolveDtoAdapter(b,normalizeFrameworkKind(q))}
1
+ import{FrameworkEnum as r}from"../../../utils/models";import{getFramework as o,parseFramework as a}from"../../../utils/helpers/framework";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))}
@@ -1,2 +1,3 @@
1
+ export * from '../../../utils/helpers/path/resolve-alias-path';
1
2
  export declare const __filename: (metaUrl: string) => string;
2
3
  export declare const __dirname: (metaUrl: string) => string;
@@ -1 +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
+ import t from"path";import{fileURLToPath as r}from"url";export*from"../../../utils/helpers/path/resolve-alias-path";export const __filename=(o)=>r(o),__dirname=(o)=>t.dirname(r(o));
@@ -0,0 +1,24 @@
1
+ export type ResolveAliasModulePathOptions = {
2
+ cwd?: string;
3
+ aliasPrefix?: string;
4
+ sourceFolder?: string;
5
+ rootFolder?: string;
6
+ distSegment?: string;
7
+ };
8
+ /** Resolve `@/…` the same way as tsconfig paths (`@/*` → `{sourceFolder}/*`), with dist fallback for prod. */
9
+ export declare function resolveAliasModulePath(spec: string, options?: ResolveAliasModulePathOptions): string;
10
+ export type TmpLoadPathContext = {
11
+ configs?: {
12
+ rootFolderPath?: string;
13
+ service?: {
14
+ paths?: {
15
+ source?: string;
16
+ special?: {
17
+ dist?: string;
18
+ };
19
+ };
20
+ };
21
+ };
22
+ };
23
+ /** Resolve tmp.yml loader `loadPath` — `@/` modules or paths relative to `paths.root`. */
24
+ export declare function resolveTmpLoadPath(spec: string, tmp: TmpLoadPathContext, cwd?: string): string;
@@ -0,0 +1 @@
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 J}from"../../../utils/constants";import{ProtocolEnum as h}from"../../../utils/models/enums";import{getRuntimeTmpConfigs as K}from"../../../utils/helpers/tmp/runtime-tmp";const G={http:h.HTTP,https:h.HTTPS,ws:h.WEBSOCKET,websocket:h.WEBSOCKET,socketio:h.SOCKETIO,socket:h.SOCKETIO},REALTIME_MIDDLEWARE_HINT=`[${J.packageName}] 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 K()?.service}export function resolveProtocolsFromConfig(b){const j=b?.protocols;if(!j)return[h.HTTP];return(Array.isArray(j)?j:[j]).map(parseProtocol)}export function getConfiguredProtocols(){try{return resolveProtocolsFromConfig(B())}catch{return[h.HTTP,h.WEBSOCKET]}}export function getConfiguredRealtimeProtocols(b){return resolveProtocolsFromConfig(b).filter(isRealtimeProtocol)}export function defaultRealtimeProtocolFromConfig(b){const j=getConfiguredRealtimeProtocols(b);if(j.length===1)return j[0];if(j.length>1)return;return h.WEBSOCKET}export function getDefaultRealtimeProtocol(){try{return defaultRealtimeProtocolFromConfig(B())}catch{return h.WEBSOCKET}}export function resolveRealtimeMiddlewareProtocol(b,j){if(b!==void 0&&b!==null&&b!=="")return parseProtocol(b);let q=j;if(!q)try{q=B()}catch{return h.WEBSOCKET}const z=getConfiguredRealtimeProtocols(q);if(z.length===1)return z[0];if(z.length>1)throw Error(REALTIME_MIDDLEWARE_HINT);return h.WEBSOCKET}export function detectSocketProtocol(b,j){if(j)return j;const q=b;if(q?.__xrystalProtocol)return q.__xrystalProtocol;return h.WEBSOCKET}export function attachSocketTransport(b,j,q){const z=b;if(j===h.SOCKETIO)q.attachSocketIo(b);else q.attachWebSocket(b);z.__xrystalProtocol=j}export{REALTIME_MIDDLEWARE_HINT};
1
+ import{Constants as s}from"../../../utils/constants";import{ProtocolEnum as r}from"../../../utils/models/enums";import{getRuntimeTmpConfigs as u}from"../../../utils/helpers/tmp/runtime-tmp";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 +1 @@
1
- import{stopTmpLoader as y}from"../../../utils/helpers/tmp/tmp-loader";import{clearRuntimeTmpConfigs as z}from"../../../utils/helpers/tmp/runtime-tmp";import A from"../../../utils/models/classes/class.x";let k=!1,q=!1;export function isShuttingDown(){return k}export async function gracefulShutdown(b=0){if(k){process.exit(b);return}k=!0;try{await A.shutdown()}catch{}y();z();await new Promise((j)=>setImmediate(j));process.exit(b)}export function registerGracefulShutdown(){if(q)return;q=!0;const b=(j)=>{gracefulShutdown(j==="SIGINT"?130:j==="SIGTERM"?143:0)};process.on("SIGINT",b);process.on("SIGTERM",b)}
1
+ import{stopTmpLoader as n}from"../../../utils/helpers/tmp/tmp-loader";import{clearRuntimeTmpConfigs as s}from"../../../utils/helpers/tmp/runtime-tmp";import i from"../../../utils/models/classes/class.x";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 w}from"zustand/vanilla";import{subscribeWithSelector as I}from"zustand/middleware";import{GStoreScopeEnum as Z}from"../../../utils/models/enums";import{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED}from"../../../utils/helpers/state/props-from-tmp";import{warnIfRequestScopedKey as Q,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey}from"../../../utils/helpers/state/request-key-guard";import{buildStoresSnapshot as U,patchControllerScope as Y,patchRunScope as q}from"../../../utils/helpers/state/scopes";export{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey};export{GStoreScopeEnum}from"../../../utils/models/enums";export{buildStoresSnapshot,summarizeController,runContextValues,patchControllerScope,patchRunScope}from"../../../utils/helpers/state/scopes";const V=(j)=>JSON.parse(JSON.stringify(j));function $(j,z){const H=new Set([...Object.keys(j),...Object.keys(z)]),M=[];for(const J of H)if(j[J]!==z[J])M.push({key:J,value:z[J],prev:j[J]});return M}class GStoreFacade{store;baseline={};allowedKeys=new Set;allowAutoCreateProps=!0;warnOnRequestKeys=!0;constructor(){this.store=w(I(()=>({})))}configureFromTmp(j={}){const z=resolveGStoreBoot(j);this.allowAutoCreateProps=z.allowAutoCreateProps;this.warnOnRequestKeys=z.warnOnRequestKeys;this.allowedKeys=new Set(Object.keys(z.vars));const H=V(z.bootstrap?z.vars:{});this.store.setState(H,!0);this.baseline=V(H);return this}allowsAutoCreateProps(){return this.allowAutoCreateProps}declaredKeys(){return[...this.allowedKeys]}guardRequestKey(j){Q(j,this.warnOnRequestKeys)}assertPropAllowed(j){if(this.allowAutoCreateProps)return;if(!this.allowedKeys.has(j))throw Error(`${G_PROP_NOT_ALLOWED}: ${j}`)}registerAllowedKeys(j){for(const z of j)this.allowedKeys.add(z)}getState(){return this.store.getState()}select(j){return j(this.getState())}get(j,z){const H=this.getState();if(!(j in H))return z;return H[j]}set(j,z){this.guardRequestKey(j);this.assertPropAllowed(j);const H=this.getState();if(H[j]===z)return this;this.store.setState({...H,[j]:z});return this}merge(j){for(const M of Object.keys(j)){this.guardRequestKey(M);this.assertPropAllowed(M)}const z=this.getState();if(!$(z,{...z,...j}).length)return this;this.store.setState({...z,...j});return this}has(j){return j in this.getState()}remove(...j){const H={...this.getState()};let M=!1;for(const J of j)if(J in H){delete H[J];M=!0}if(M)this.store.setState(H,!0);return this}keys(){return Object.keys(this.getState())}entries(){return Object.entries(this.getState())}snapshot(){return{...this.getState()}}subscribe(j){return this.store.subscribe((z,H)=>j(z,H,$(H,z)))}subscribeKey(j,z){return this.store.subscribe((H)=>H[j],(H,M)=>z(H,M,{key:j,value:H,prev:M}))}bootstrap(j){if(!this.allowAutoCreateProps)for(const z of Object.keys(j))this.assertPropAllowed(z);else this.registerAllowedKeys(Object.keys(j));this.merge(j);this.baseline=V(this.getState());return this}reset(){this.store.setState(V(this.baseline),!0)}stores(){return U(this.snapshot())}list(){return Object.values(this.stores())}scope(j){const H=this.stores()[j],M={name:j,active:H.active,keys:()=>H.keys,get(J,X){if(!H.values||!(J in H.values))return X;return H.values[J]}};if(j===Z.GLOBAL)return{...M,set:(J,X)=>{this.set(J,X);return!0},merge:(J)=>{this.merge(J);return!0}};if(j===Z.RUN)return{...M,patch:(J)=>q(J)};return{...M,patch:(J)=>Y(J)}}}export{GStoreFacade};export const G=new GStoreFacade;
1
+ import{createStore as h}from"zustand/vanilla";import{subscribeWithSelector as l}from"zustand/middleware";import{GStoreScopeEnum as a}from"../../../utils/models/enums";import{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED}from"../../../utils/helpers/state/props-from-tmp";import{warnIfRequestScopedKey as c,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey}from"../../../utils/helpers/state/request-key-guard";import{buildStoresSnapshot as p,patchControllerScope as S,patchRunScope as f}from"../../../utils/helpers/state/scopes";export{propsFromTmp,resolveGStoreBoot,G_PROP_NOT_ALLOWED,G_REQUEST_KEY_WARN,looksLikeRequestScopedKey};export{GStoreScopeEnum}from"../../../utils/models/enums";export{buildStoresSnapshot,summarizeController,runContextValues,patchControllerScope,patchRunScope}from"../../../utils/helpers/state/scopes";const 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 I}from"../../../utils/constants";import{readTmpServiceBlock as J}from"../../../utils/helpers/tmp/tmp-schema";export const G_PROP_NOT_ALLOWED=`[${I.packageName}] G prop not declared in tmp.yml vars — set autoCreateProps: true to allow runtime keys`;const F=()=>({});function L(j){return J(j).loaders?.system?.gStore}function M(j){if(typeof j.bootstrap==="boolean")return j.bootstrap;return!0}function Q(j){if(typeof j.autoCreateProps==="boolean")return j.autoCreateProps;return!0}function U(j){if(typeof j.warnOnRequestKeys==="boolean")return j.warnOnRequestKeys;return!0}export function resolveGStoreBoot(j={}){const x=j.configs??j,z=L(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:M(E),allowAutoCreateProps:Q(E),warnOnRequestKeys:U(E),vars:H}}export function propsFromTmp(j={}){const x=resolveGStoreBoot(j);return x.bootstrap?x.vars:F()}
1
+ import{Constants as u}from"../../../utils/constants";import{readTmpServiceBlock as p}from"../../../utils/helpers/tmp/tmp-schema";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 B}from"../../../utils/constants";import{getRunContext as D}from"../../../utils/helpers/context";import{getControllerCtx as F}from"../../../utils/helpers/context/controller-store";export const G_REQUEST_KEY_WARN=`[${B.packageName}] G: key looks request-scoped — use run/controller context, not global G`;const H=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(H.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=D()?"run":F()?"controller":"outside-request";console.warn(`${G_REQUEST_KEY_WARN} (key: ${j}, scope: ${f})`)}
1
+ import{Constants as t}from"../../../utils/constants";import{getRunContext as s}from"../../../utils/helpers/context";import{getControllerCtx as n}from"../../../utils/helpers/context/controller-store";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 j}from"../../../utils/models/enums";import{getRunContext as q,patchRunContext as w}from"../../../utils/helpers/context";import{getControllerCtx as v}from"../../../utils/helpers/context/controller-store";export function summarizeController(d){if(!d)return null;return{protocol:d.protocol,framework:d.framework,requestId:d.requestId,metadata:d.metadata,hasReq:!!d.req,hasRes:!!d.res,hasSocket:!!d.socket}}export function runContextValues(d){if(!d)return null;return{...d}}export function buildStoresSnapshot(d){const f=q(),k=summarizeController(v());return{[j.GLOBAL]:{name:j.GLOBAL,active:!0,keys:Object.keys(d),values:{...d}},[j.RUN]:{name:j.RUN,active:!!f,keys:f?Object.keys(f):[],values:runContextValues(f)},[j.CONTROLLER]:{name:j.CONTROLLER,active:!!k,keys:k?Object.keys(k):[],values:k}}}export function patchControllerScope(d){const f=v();if(!f)return!1;if(d.requestId!==void 0)f.requestId=d.requestId;if(d.metadata)f.metadata={...f.metadata,...d.metadata,locals:{...f.metadata?.locals??{},...d.metadata.locals??{}}};return!0}export function patchRunScope(d){if(!q())return!1;w(d);return!0}
1
+ import{GStoreScopeEnum as r}from"../../../utils/models/enums";import{getRunContext as a,patchRunContext as u}from"../../../utils/helpers/context";import{getControllerCtx as n}from"../../../utils/helpers/context/controller-store";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 w}from"../../../utils/constants";import{onRuntimeTmpChange as x}from"../../../utils/helpers/tmp/runtime-tmp";export function bindLoaderTmpSync(j){const q=j.constructor.name;x(async()=>{try{await j.syncFromTmp()}catch(b){const v=b instanceof Error?b.message:String(b);console.warn(`[${w.packageName}] ${q} tmp reload failed: ${v}`)}})}
1
+ import{packageDefaults as e}from"../../../utils/constants";import{onRuntimeTmpChange as t}from"../../../utils/helpers/tmp/runtime-tmp";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 A}from"../../../utils/constants";import{healToolchainIfLayoutNeedsSync as B,resetToolchainHealState as E}from"../../../utils/helpers/tmp/toolchain-heal";let v;const w=[];export function setRuntimeTmpConfigs(j){v=j}export function getRuntimeTmpConfigs(){return v}export function onRuntimeTmpChange(j){w.push(j);return()=>{const b=w.indexOf(j);if(b>=0)w.splice(b,1)}}export async function notifyRuntimeTmpChange(j){if(j)v=j;const b=v;if(!b)return;if(b.rootFolderPath&&b.service?.paths)try{B(process.cwd(),b)}catch(q){const z=q instanceof Error?q.message:String(q);console.warn(`[${A.packageName}] toolchain auto-sync skipped: ${z}`)}for(const q of w)await q(b)}export function clearRuntimeTmpConfigs(){v=void 0;w.length=0;E()}
1
+ import{packageDefaults as s}from"../../../utils/constants";import{healToolchainIfLayoutNeedsSync as a,resetToolchainHealState as c}from"../../../utils/helpers/tmp/toolchain-heal";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 J from"node:fs";import I from"node:path";import{fileURLToPath as Q}from"node:url";import V from"yaml";import defaults from"../../../utils/constants/defaults.json" with { type: 'json' };import{normalizeRootFolder as W,normalizeSourceFolder as X}from"../../../utils/helpers/tmp/path-normalize";export{defaults as packageIdentityDefaults};const M=I.dirname(Q(import.meta.url)),O=`${defaults.tmpBaseName}${defaults.tmpExtension}`;function H(j,A){if(typeof j!=="string"||!j.trim())throw Error(`${defaults.packageName}: bundled tmp.yml missing ${A}`);return j.trim()}function Y(j){const A=j&&typeof j==="object"&&!Array.isArray(j)?j:{};return{tests:H(A.tests,"configs.service.paths.special.tests"),environments:H(A.environments,"configs.service.paths.special.environments"),dist:H(A.dist,"configs.service.paths.special.dist")}}function Z(j){if(j){if(!J.existsSync(j))throw Error(`${defaults.packageName}: bundled tmp.yml missing at ${j}`);return j}const A=[M,process.cwd()];for(const G of A){let C=I.resolve(G);for(;;){const D=I.join(C,defaults.packageRootFolder,O);if(J.existsSync(D))return D;const E=I.dirname(C);if(E===C)break;C=E}}throw Error(`${defaults.packageName}: bundled ${defaults.packageRootFolder}/${O} not found from ${M}`)}export function loadSeedFromBundledTmp(j){const A=Z(j),G=V.parse(J.readFileSync(A,"utf8")),C=G?.configs&&typeof G.configs==="object"?G.configs:{},D=C.service&&typeof C.service==="object"?C.service:{},E=D.paths&&typeof D.paths==="object"?D.paths:{},K=H(E.source,"configs.service.paths.source");return{rootFolder:W(E.root,defaults.packageRootFolder),sourceFolder:X(K,K),framework:H(D.framework,"configs.service.framework"),layout:Y(E.special)}}export const seedFromTmp=loadSeedFromBundledTmp();
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";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 J from"node:fs";import K from"node:path";import{Constants as z}from"../../../utils/constants";import{assertCoreTmpGuard as M,coreCanonicalTmpPath as O,isCorePackageRoot as Q}from"../../../utils/helpers/core/tmp-layout";import{findFileRecursively as U}from"../../../utils/helpers/core/paths";import{TmpFileLoader as V}from"../../../utils/models/classes/class.tmp-file-loader";import{registerGracefulShutdown as W}from"../../../utils/helpers/runtime/shutdown";let q=null,B=null;function X(D=process.cwd(),j=z.tmpBaseName,b=z.tmpExtension){const A=K.resolve(D);if(Q(A)){const E=O(A);if(!J.existsSync(E))throw Error(`${z.packageRootFolder}/tmp.yml not found. Run ${z.cliName} tmp or ensureCoreTmpEntry() before starting ${z.packageName}`);M(A,E);return E}const H=U(A,j,b);if(!H)throw Error(`${j}${b.startsWith(".")?b:`.${b}`} file not found`);return H}export function getTmpLoaderPath(){if(!B)B=X();return B}export function getTmpLoader(){if(!q){q=new V({filePath:getTmpLoaderPath()});W()}return q}export function getTmpSnapshot(){return getTmpLoader().getResolvedTmpFile()}export function onTmpReload(D){const j=getTmpLoader(),b=()=>D(j.getResolvedTmpFile());j.on("reload",b);return()=>j.off("reload",b)}export function stopTmpLoader(){if(q){q.stop();q=null;B=null}}export function resetTmpLoaderForTests(){stopTmpLoader()}
1
+ import s from"node:fs";import m from"node:path";import{Constants as t}from"../../../utils/constants";import{assertCoreTmpGuard as f,coreCanonicalTmpPath as c,isCorePackageRoot as u}from"../../../utils/helpers/core/tmp-layout";import{findFileRecursively as d}from"../../../utils/helpers/core/paths";import{TmpFileLoader as T}from"../../../utils/models/classes/class.tmp-file-loader";import{registerGracefulShutdown as h}from"../../../utils/helpers/runtime/shutdown";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()}
@@ -43,7 +43,7 @@ export type TmpRuntimeConfigs = {
43
43
  };
44
44
  export declare function normalizeRuntime(value: unknown): RuntimeEnum;
45
45
  export declare function normalizeBundler(value: unknown): BundlerEnum;
46
- export declare function resolveEffectiveBundler(bundler: BundlerEnum, runtime: RuntimeEnum): Exclude<BundlerEnum, BundlerEnum.AUTO>;
46
+ export declare function resolveEffectiveBundler(bundler: BundlerEnum, _runtime: RuntimeEnum): Exclude<BundlerEnum, BundlerEnum.AUTO>;
47
47
  export declare function normalizeRootFolder(value?: string): string;
48
48
  export declare function normalizeSourceFolder(value?: string): string;
49
49
  export declare function readTmpGlobalBlock(configs?: Record<string, unknown>): TmpGlobalBlock;
@@ -1 +1 @@
1
- import Q from"../../../utils/constants/defaults.json" with { type: 'json' };import{BundlerEnum as D,RuntimeEnum as M}from"../../../utils/models/enums";import{seedFromTmp as U}from"../../../utils/helpers/tmp/seed-from-tmp";import{interpolateWithContext as Z}from"../../../utils/helpers/tmp/tmp-interpolate";import{normalizeLayoutPaths as _,normalizeRootFolder as $,normalizeSourceFolder as I}from"../../../utils/helpers/tmp/path-normalize";function H(j){return typeof j==="object"&&j!==null&&!Array.isArray(j)}function x(j){if(typeof j==="number"||typeof j==="string")return j;return}export function normalizeRuntime(j){const q=typeof j==="string"?j.trim().toLowerCase():"";if(q===M.NODE)return M.NODE;if(q===M.BUN)return M.BUN;if(!q)throw Error(`${Q.packageName}: configs.global.runtime is required (${Object.values(M).join("|")})`);throw Error(`${Q.packageName}: unknown configs.global.runtime "${String(j)}" (expected ${Object.values(M).join("|")})`)}export function normalizeBundler(j){const q=typeof j==="string"?j.trim().toLowerCase():"";if(!q)return D.AUTO;if(q===D.TSC)return D.TSC;if(q===D.ESBUILD)return D.ESBUILD;if(q===D.BUN)return D.BUN;if(q===D.AUTO)return D.AUTO;throw Error(`${Q.packageName}: unknown build.bundler "${String(j)}" (expected ${Object.values(D).join("|")})`)}export function resolveEffectiveBundler(j,q){if(j!==D.AUTO)return j;return q===M.NODE?D.TSC:D.BUN}export function normalizeRootFolder(j){return $(j,Q.packageRootFolder)}export function normalizeSourceFolder(j){return I(j,U.sourceFolder)}export function readTmpGlobalBlock(j){const q=H(j?.global)?j.global:{},A=H(q.vars)?q.vars:{};return{runtime:normalizeRuntime(q.runtime),vars:{...A}}}export function readTmpCoreBlock(j){const q=H(j?.core)?j.core:{},A=H(q.tmp)?q.tmp:{};return{tmp:{fileWatchIntervalMs:x(A.fileWatchIntervalMs)}}}export function readTmpServiceBlock(j){const q=H(j?.service)?j.service:{},A=H(q.paths)?q.paths:{},J=H(A.special)?A.special:{};let K=H(q.loaders)?{...q.loaders}:void 0,O=H(q.build)?q.build:void 0;if(K&&H(K.build)){const{build:X,...Y}=K;K=Y;if(!O&&H(X))O=X}return{name:typeof q.name==="string"?q.name:void 0,framework:typeof q.framework==="string"?q.framework:void 0,paths:{root:typeof A.root==="string"?A.root:void 0,source:typeof A.source==="string"?A.source:void 0,special:{tests:typeof J.tests==="string"?J.tests:void 0,environments:typeof J.environments==="string"?J.environments:void 0,dist:typeof J.dist==="string"?J.dist:void 0}},protocols:q.protocols,loaders:K,build:O}}export function resolveServiceLayoutPaths(j){return _(j.paths?.special,U.layout)}function L(j){const q=resolveServiceLayoutPaths(j);return{name:j.name,framework:j.framework??U.framework,paths:{root:j.paths?.root??Q.packageRootFolder,source:j.paths?.source??U.sourceFolder,special:q},protocols:j.protocols,loaders:j.loaders,build:j.build}}function N(j){return{tmp:{fileWatchIntervalMs:j.tmp?.fileWatchIntervalMs}}}export function buildTmpVarContext(j){return{...j.vars,runtime:j.runtime,global:j}}export function applyTmpGlobalVars(j){const q=H(j.configs)?j.configs:{},A=readTmpGlobalBlock(q);return Z(j,buildTmpVarContext(A))}export function resolveTmpRuntimeConfigs(j){const q=H(j?.configs)?j.configs:{},A=readTmpGlobalBlock(q),J=readTmpServiceBlock(q),K=readTmpCoreBlock(q),O=L(J);return{global:A,service:O,core:N(K),rootFolderPath:normalizeRootFolder(O.paths.root)}}export function normalizeTmpDocument(j){const q=applyTmpGlobalVars(j);return{...q,configs:resolveTmpRuntimeConfigs(q)}}
1
+ import l from"../../../utils/constants/defaults.json" with { type: 'json' };import{BundlerEnum as n,RuntimeEnum as u}from"../../../utils/models/enums";import{seedFromTmp as c}from"../../../utils/helpers/tmp/seed-from-tmp";import{interpolateWithContext as d}from"../../../utils/helpers/tmp/tmp-interpolate";import{normalizeLayoutPaths as m,normalizeRootFolder as g,normalizeSourceFolder as b}from"../../../utils/helpers/tmp/path-normalize";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 J}from"../../../utils/constants";import{readTmpCoreBlock as P}from"../../../utils/helpers/tmp/tmp-schema";const Q=J.tmpWatchDefaults;function z(y){const j=Q?.[y];if(typeof j!=="number"||!Number.isFinite(j))throw Error(`${J.packageName}: tmpWatchDefaults.${y} missing in defaults.json`);return j}export function resolveTmpWatchIntervalMs(y){const j=y?.configs,K=P(j),G=z("intervalMs"),M=K.tmp?.fileWatchIntervalMs??G,I=Number(M);if(!Number.isFinite(I))return G;const N=z("minIntervalMs"),O=z("maxIntervalMs");return Math.min(O,Math.max(N,Math.round(I)))}
1
+ import{packageDefaults as o}from"../../../utils/constants";import{readTmpCoreBlock as u}from"../../../utils/helpers/tmp/tmp-schema";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 Q from"node:fs";import Y from"node:path";import{packageDefaults as M}from"../../../utils/constants";import{normalizeSourceFolder as C}from"../../../utils/helpers/tmp/path-normalize";function Z(j){return String(j).replace(/^\.\//,"")}function _(){const j=M.buildDefaults?.tsconfig;if(!j||!String(j).trim())throw Error(`${M.packageName}: buildDefaults.tsconfig missing in defaults.json`);return String(j)}export function layoutOptionsFromRuntimeConfigs(j){const B=j.service?.paths,G=B?.special;return{rootFolderPath:j.rootFolderPath||M.packageRootFolder,mainFolderPath:C(B?.source,M.mainSourceFolder),pathsDist:G?.dist||M.layoutPaths.dist,pathsTests:G?.tests||M.layoutPaths.tests}}export function layoutFingerprint(j){return[j.rootFolderPath,Z(j.mainFolderPath),j.pathsDist,j.pathsTests].join("\x00")}export function resolveRecommendedTsconfig(j){const B=Z(j.mainFolderPath),G=j.rootFolderPath,I=M.pathAliasKey;return{include:[B],exclude:[`${G}/${j.pathsTests}`],compilerOptions:{baseUrl:".",paths:{[I]:[`${B}/*`]},rootDir:`./${B}`,outDir:`./${G}/${j.pathsDist}`}}}function E(j){const B=Y.join(j,"package.json");if(!Q.existsSync(B))return`${M.packageName}/tsconfig.base.json`;try{if(JSON.parse(Q.readFileSync(B,"utf8")).name===M.packageName)return"./tsconfig.base.json"}catch{}return`${M.packageName}/tsconfig.base.json`}function W(j,B,G){const I=B.compilerOptions??{};return{...B,extends:B.extends??G,include:j.include,exclude:j.exclude,compilerOptions:{...I,baseUrl:j.compilerOptions.baseUrl,paths:j.compilerOptions.paths,rootDir:j.compilerOptions.rootDir,outDir:j.compilerOptions.outDir}}}export function auditTsconfigAgainstLayout(j,B,G=_()){const I=Y.join(j,G);if(!Q.existsSync(I))return{ok:!1,missing:!0,notes:[`${G} missing`]};let J;try{J=JSON.parse(Q.readFileSync(I,"utf8"))}catch{return{ok:!1,missing:!1,notes:[`${G} unreadable`]}}const H=resolveRecommendedTsconfig(B),N=[],V=J.compilerOptions??{},X=M.pathAliasKey;if(V.outDir!==H.compilerOptions.outDir)N.push("outDir drift");if(!(Array.isArray(J.include)?J.include.map(String):[]).some((A)=>Z(A)===H.include[0]))N.push("include drift");const $=V.paths?.[X];if(JSON.stringify($)!==JSON.stringify(H.compilerOptions.paths[X]))N.push(`paths ${X} drift`);return{ok:N.length===0,missing:!1,notes:N}}export function writeTsconfigFromLayout(j,B,G=_()){const I=Y.join(j,G),J=!Q.existsSync(I);let H={};if(!J)try{H=JSON.parse(Q.readFileSync(I,"utf8"))}catch{H={}}const N=resolveRecommendedTsconfig(B),V=W(N,H,E(j));Q.writeFileSync(I,`${JSON.stringify(V,null,2)}
2
- `,"utf8");return{wrote:!0,created:J,abs:I}}let U=null;export function resetToolchainHealState(){U=null}export function healToolchainIfLayoutNeedsSync(j,B,G={}){const I=layoutOptionsFromRuntimeConfigs(B),J=layoutFingerprint(I),H=_(),N=auditTsconfigAgainstLayout(j,I,H);if(U===null){U=J;if(N.ok)return{healed:!1,tsconfigRel:H,fingerprint:J};writeTsconfigFromLayout(j,I,H);if(!G.quiet)console.info(`[${M.packageName}] toolchain auto-synced (${H}) — bootstrap layout drift`);return{healed:!0,reason:"bootstrap",tsconfigRel:H,fingerprint:J}}if(J===U)return{healed:!1,tsconfigRel:H,fingerprint:J};U=J;writeTsconfigFromLayout(j,I,H);if(!G.quiet)console.info(`[${M.packageName}] toolchain auto-synced (${H}) — tmp layout paths changed`);return{healed:!0,reason:"layout-changed",tsconfigRel:H,fingerprint:J}}
1
+ import c from"node:fs";import f from"node:path";import{packageDefaults as r}from"../../../utils/constants";import{normalizeSourceFolder as y}from"../../../utils/helpers/tmp/path-normalize";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";import{LoggerLayerEnum as x,x as b}from"../../../utils";import{getRequestId as D}from"../../../utils/helpers/context";export class ClientStore{static _store={};static get(t){return this._store[t]||{}}static set(t,e){this._store[t]={...this._store[t],...e}}}export class Client{logger=b.get(N);configs=b.get(y);clientName;baseURL;version=null;timeout=15000;debug;authConfigs;breaker={failures:0,lastFailure:0,state:"CLOSED",threshold:5,cooldown:30000};constructor({clientName:t,baseURL:e,version:r,timeout:i,auth:s,debug:n}){this.clientName=t;this.baseURL=e;this.version=r||null;this.authConfigs=s;this.timeout=i||15000;const c=Number(this.configs.all.debug)>=x.DEBUG;this.debug=n??c;if(s?.token)ClientStore.set(t,{accessToken:s.token})}resolvePath(t,e){return e.split(".").reduce((r,i)=>r?r[i]:void 0,t)}static cryptoHashGenerate=({algorithm:t,input:e,digest:r="hex"})=>{return k(t).update(e).digest(r)}}export class BaseApiClient extends Client{constructor(t){super(t)}async request(t,e={}){if(this.breaker.state==="OPEN")if(Date.now()-this.breaker.lastFailure>this.breaker.cooldown)this.breaker.state="HALF_OPEN";else throw Error(`[CircuitBreaker] ${this.clientName} is OPEN`);const r=e.retries??3;let i=0;while(i<r)try{const s=await this._execute(t,{...e});if(s.ok||s.status===401){this.breaker.failures=0;this.breaker.state="CLOSED";return s}if([502,503,504].includes(s.status))throw Error(`Server Error: ${s.status}`);return s}catch(s){i++;this.breaker.failures++;this.breaker.lastFailure=Date.now();if(this.breaker.failures>=this.breaker.threshold)this.breaker.state="OPEN";if(i>=r)throw s;const n=Math.pow(2,i)*500;await new Promise((c)=>setTimeout(c,n))}throw Error(`${this.clientName} failed after ${r} attempts`)}async _execute(t,e){const r=this.baseURL.replace(/\/$/,""),i=e.version!==void 0?e.version:this.version,s=i?`/${i.replace(/^\//,"")}`:"",n=`${r}${s}${t}`,c=D(),l=new Headers(e.headers||{}),u=e.body instanceof URLSearchParams,d=e.body instanceof FormData;if(!u&&!d)l.set("Content-Type","application/json");if(c)l.set("x-correlation-id",c);const f=this.configs.all.internalSecret||process.env.INTERNAL_SECRET;if(f){const a=Date.now().toString(),w=E("sha256",f).update(a+this.clientName).digest("hex");l.set("x-internal-signature",w);l.set("x-internal-timestamp",a);l.set("x-internal-client",this.clientName)}const p=e.debug??this.debug,{version:L,retries:$,debug:v,...h}=e;let o=h.body;if(o&&typeof o==="object"&&!u&&!d)o=JSON.stringify(o);if(p){const a={method:h.method||"GET",url:n,body:o&&typeof o==="string"?JSON.parse(o):o};console.log(`[DEBUG] ${this.clientName}`,a);this.logger.winston.info(`${this.clientName} Request`,a)}const m=new AbortController,g=setTimeout(()=>m.abort(),this.timeout);try{const a=await fetch(n,{...h,body:o,headers:l,signal:m.signal});clearTimeout(g);return a}catch(a){clearTimeout(g);throw a}}}
1
+ import{createHash as k,createHmac as E}from"node:crypto";import{Configs as y,Logger as N}from"../../../loader";import{LoggerLayerEnum as x,x as b}from"../../../utils";import{getRequestId as D}from"../../../utils/helpers/context";export class ClientStore{static _store={};static get(t){return this._store[t]||{}}static set(t,e){this._store[t]={...this._store[t],...e}}}export class Client{logger=b.get(N);configs=b.get(y);clientName;baseURL;version=null;timeout=15000;debug;authConfigs;breaker={failures:0,lastFailure:0,state:"CLOSED",threshold:5,cooldown:30000};constructor({clientName:t,baseURL:e,version:r,timeout:i,auth:s,debug:n}){this.clientName=t;this.baseURL=e;this.version=r||null;this.authConfigs=s;this.timeout=i||15000;const c=Number(this.configs.all.debug)>=x.DEBUG;this.debug=n??c;if(s?.token)ClientStore.set(t,{accessToken:s.token})}resolvePath(t,e){return e.split(".").reduce((r,i)=>r?r[i]:void 0,t)}static cryptoHashGenerate=({algorithm:t,input:e,digest:r="hex"})=>{return k(t).update(e).digest(r)}}export class BaseApiClient extends Client{constructor(t){super(t)}async request(t,e={}){if(this.breaker.state==="OPEN")if(Date.now()-this.breaker.lastFailure>this.breaker.cooldown)this.breaker.state="HALF_OPEN";else throw Error(`[CircuitBreaker] ${this.clientName} is OPEN`);const r=e.retries??3;let i=0;while(i<r)try{const s=await this._execute(t,{...e});if(s.ok||s.status===401){this.breaker.failures=0;this.breaker.state="CLOSED";return s}if([502,503,504].includes(s.status))throw Error(`Server Error: ${s.status}`);return s}catch(s){i++;this.breaker.failures++;this.breaker.lastFailure=Date.now();if(this.breaker.failures>=this.breaker.threshold)this.breaker.state="OPEN";if(i>=r)throw s;const n=Math.pow(2,i)*500;await new Promise((c)=>setTimeout(c,n))}throw Error(`${this.clientName} failed after ${r} attempts`)}async _execute(t,e){const r=this.baseURL.replace(/\/$/,""),i=e.version!==void 0?e.version:this.version,s=i?`/${i.replace(/^\//,"")}`:"",n=`${r}${s}${t}`,c=D(),l=new Headers(e.headers||{}),u=e.body instanceof URLSearchParams,d=e.body instanceof FormData;if(!u&&!d)l.set("Content-Type","application/json");if(c)l.set("x-correlation-id",c);const f=this.configs.all.internalSecret||process.env.INTERNAL_SECRET;if(f){const a=Date.now().toString(),w=E("sha256",f).update(a+this.clientName).digest("hex");l.set("x-internal-signature",w);l.set("x-internal-timestamp",a);l.set("x-internal-client",this.clientName)}const p=e.debug??this.debug,{version:L,retries: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: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
+ 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 L}from"node:events";import{readFileSync as N,unwatchFile as G,watchFile as Q}from"node:fs";import{resolve as R}from"node:path";import{parse as U}from"yaml";import{resolveObjWithHandlebars as V}from"../../../utils/helpers";import{normalizeTmpDocument as X}from"../../../utils/helpers/tmp/tmp-schema";import{resolveTmpWatchIntervalMs as A}from"../../../utils/helpers/tmp/tmp-watch";export class TmpFileLoader extends L{#k={};#q;#B=A(null);#A=!1;constructor({filePath:k}){super();this.#q=R(k);this.#G();this.#K()}#G(){try{const k=N(this.#q,"utf8"),q=U(k),B=A(q),K=this.#A&&B!==this.#B;this.#k=q;this.#B=B;this.emit("reload",this.#k);if(K)this.#K()}catch(k){console.error(`[TmpFileLoader] Error: ${k}`)}}#K(){if(this.#A)G(this.#q);this.#B=A(this.#k);Q(this.#q,{interval:this.#B},(k,q)=>{if(k.mtimeMs!==q.mtimeMs)this.#G()});this.#A=!0}stop(){if(this.#A){G(this.#q);this.#A=!1}this.removeAllListeners()}getResolvedTmpFile(){const k=Object.keys(this.#k).length>0?this.#k:(this.#G(),this.#k);return X(V(k,k))}}
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";import{normalizeTmpDocument as p}from"../../../utils/helpers/tmp/tmp-schema";import{resolveTmpWatchIntervalMs as s}from"../../../utils/helpers/tmp/tmp-watch";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="/home/runner/work/-xrystal-core/-xrystal-core/x/dist/utils/models/classes/class.x.js";import{createContainer as V,asClass as K,asValue as j,InjectionMode as N,listModules as X,Lifetime as Z}from"awilix";import R from"node:path";import{pathToFileURL as x}from"node:url";import C from"../../../utils/constants/defaults.json" with { type: 'json' };export const xSymbol=Symbol.for(`${C.packageName}/di-container`);class T{checkRegistration(q,A){return!!q.registrations[A]}}class U extends T{container;initializedNames=new Set;loadedPaths=new Set;registeredClasses=new Set;isInitializing=!1;constructor(){super();this.container=V({injectionMode:N.PROXY,strict:!0})}getName(q){if(typeof q==="string")return q.charAt(0).toLowerCase()+q.slice(1);if(typeof q==="function"&&q.name)return q.name.charAt(0).toLowerCase()+q.name.slice(1);return""}async load(q,A={}){const{verbose:H=!1,exclude:$=[],lifetime:E=Z.SINGLETON}=A,B=process.cwd(),G=(Array.isArray(q)?q:[q]).map((Q)=>{return(R.isAbsolute(Q)?Q:R.resolve(B,Q)).replace(/\\/g,"/").toLowerCase()});let O=[];try{O=X(G)}catch(Q){return this}for(const Q of O){const Y=Q.path.replace(/\\/g,"/").toLowerCase();if(this.loadedPaths.has(Y))continue;if(Y===__filename.replace(/\\/g,"/").toLowerCase()||Y.endsWith(".d.ts"))continue;try{const F=await import(x(Q.path).href);let J=F.default;if(!J)J=Object.values(F).find((W)=>typeof W==="function"&&!!W.prototype&&!!W.name);if(typeof J==="function"&&!!J.prototype&&!!J.name){if(this.registeredClasses.has(J))continue;const W=this.getName(J);if(W&&!this.checkRegistration(this.container,W)){this.container.register({[W]:K(J).setLifetime(E)});this.loadedPaths.add(Y);this.registeredClasses.add(J)}}}catch(w){if(H)console.error("[DI] Load Error:",w.message)}}return this}register(q,A=Z.SINGLETON){const H=this.getName(q);if(!H||this.registeredClasses.has(q))return this;if(this.checkRegistration(this.container,H))return this;this.container.register({[H]:K(q).setLifetime(A)});this.registeredClasses.add(q);return this}registerInstance(q,A){if(!q)return this;const H=this.getName(q);this.container.register({[H]:j(A)});return this}async initialize(q,A=!1){if(this.isInitializing)return this;this.isInitializing=!0;try{const H=q?Array.isArray(q)?q:[q]:[];for(const E of H){const B=this.getName(E.service);if(!B||this.initializedNames.has(B))continue;const G=this.container.registrations[B];if(!G||G.lifetime!==Z.SINGLETON)continue;try{const O=this.container.cradle[B];if(O&&typeof O.onInit==="function")await O.onInit(E.props||{});this.initializedNames.add(B)}catch(O){if(A)console.error(`[DI] Priority onInit Failed (${B}):`,O.message)}}const $=Object.keys(this.container.registrations);for(const E of $){if(this.initializedNames.has(E))continue;if(this.container.registrations[E].lifetime!==Z.SINGLETON)continue;try{const G=this.container.cradle[E];if(G&&typeof G.onInit==="function")await G.onInit({});this.initializedNames.add(E)}catch(G){if(A)console.error(`[DI] Auto onInit Failed (${E}):`,G.message)}}for(const E of this.initializedNames)try{const B=this.container.cradle[E];if(B&&typeof B.onAfterInit==="function")await B.onAfterInit()}catch(B){if(A)console.error(`[DI] onAfterInit Failed (${E}):`,B.message)}}finally{this.isInitializing=!1}return this}get(q){const A=this.getName(q);return this.container.resolve(A)}async shutdown(){for(const q of this.initializedNames)try{const A=this.container.cradle[q];if(A&&typeof A.onDispose==="function")await A.onDispose()}catch(A){console.error(`[DI] onDispose Failed (${q})`)}await this.container.dispose()}get cradle(){return this.container.cradle}}const _=globalThis;if(!_[xSymbol])_[xSymbol]=new U;export default _[xSymbol];
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];
package/x/tmp.yml CHANGED
@@ -25,7 +25,7 @@ configs:
25
25
 
26
26
  loaders:
27
27
  configs:
28
- loadPath: '@/source/utils/helpers/configs/index'
28
+ loadPath: '@/utils/helpers/configs/index'
29
29
 
30
30
  system:
31
31
  gStore: