@xrystal/core 3.38.1 → 3.38.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +251 -2146
  2. package/package.json +3 -3
  3. package/x/bin/helpers/.generated/tmp-schema.mjs +8 -1
  4. package/x/bin/helpers/build-config.mjs +2 -0
  5. package/x/bin/helpers/defaults.json +44 -0
  6. package/x/bin/helpers/package-defaults.mjs +21 -0
  7. package/x/bin/helpers/project-artifacts.mjs +14 -1
  8. package/x/bin/paths.mjs +1 -1
  9. package/x/bin/scripts/clean-dist-tests.mjs +50 -0
  10. package/x/bin/scripts/fix-dist-imports.mjs +11 -2
  11. package/x/bin/scripts/sync-cli-defaults.mjs +16 -0
  12. package/x/dist/loader/clients/index.js +1 -1
  13. package/x/dist/loader/configs/index.js +1 -1
  14. package/x/dist/loader/controller/index.js +1 -1
  15. package/x/dist/loader/dto/index.js +1 -1
  16. package/x/dist/loader/events/index.js +1 -1
  17. package/x/dist/loader/index.js +1 -1
  18. package/x/dist/loader/kafka/index.js +1 -1
  19. package/x/dist/loader/localizations/index.js +1 -1
  20. package/x/dist/loader/logger/index.js +1 -1
  21. package/x/dist/loader/system/index.js +1 -1
  22. package/x/dist/project/index.js +1 -1
  23. package/x/dist/utils/constants/index.js +1 -1
  24. package/x/dist/utils/helpers/context/index.js +1 -1
  25. package/x/dist/utils/helpers/core/index.js +1 -1
  26. package/x/dist/utils/helpers/core/tmp-layout.js +1 -1
  27. package/x/dist/utils/helpers/date/index.js +1 -1
  28. package/x/dist/utils/helpers/dispatch/index.js +1 -1
  29. package/x/dist/utils/helpers/framework/index.js +1 -1
  30. package/x/dist/utils/helpers/handlers/adapters.js +1 -1
  31. package/x/dist/utils/helpers/handlers/execute.js +1 -1
  32. package/x/dist/utils/helpers/handlers/index.js +1 -1
  33. package/x/dist/utils/helpers/index.js +1 -1
  34. package/x/dist/utils/helpers/middleware/index.js +1 -1
  35. package/x/dist/utils/helpers/protocol/index.js +1 -1
  36. package/x/dist/utils/helpers/protocol/options.js +1 -1
  37. package/x/dist/utils/helpers/runtime/dto-access.js +1 -1
  38. package/x/dist/utils/helpers/runtime/index.js +1 -1
  39. package/x/dist/utils/helpers/runtime/shutdown.js +1 -1
  40. package/x/dist/utils/helpers/state/index.js +1 -1
  41. package/x/dist/utils/helpers/state/props-from-tmp.js +1 -1
  42. package/x/dist/utils/helpers/state/request-key-guard.js +1 -1
  43. package/x/dist/utils/helpers/state/scopes.js +1 -1
  44. package/x/dist/utils/helpers/tmp/index.js +1 -1
  45. package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -1
  46. package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -1
  47. package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -1
  48. package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -1
  49. package/x/dist/utils/index.js +1 -1
  50. package/x/dist/utils/models/classes/class.clients.js +1 -1
  51. package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -1
  52. package/x/dist/utils/models/index.js +1 -1
  53. package/x/dist/utils/helpers/tests/tmp-schema.test.d.ts +0 -1
  54. package/x/dist/utils/helpers/tests/tmp-schema.test.js +0 -1
  55. package/x/dist/utils/helpers/tests/tmp-watch.test.d.ts +0 -1
  56. package/x/dist/utils/helpers/tests/tmp-watch.test.js +0 -1
package/README.md CHANGED
@@ -1,2356 +1,461 @@
1
- # xrystal-core
1
+ # @xrystal/core
2
2
 
3
- > **EN** — Multi-framework microservice runtime: HTTP + realtime, DI loaders, live `tmp.yml`, `@xrystal/dto` responses.
4
- > **TR** — Çok framework’lü microservice runtime: HTTP + realtime, DI loader’lar, canlı `tmp.yml`, `@xrystal/dto` cevapları.
3
+ > **EN** — Microservice runtime: Express or Elysia HTTP, DI loaders, live `tmp.yml`, standardized API responses.
4
+ > **TR** — Microservice runtime: Express veya Elysia HTTP, DI loader'lar, canlı `tmp.yml`, standart API cevapları.
5
5
 
6
- **Tests / Test:** `xcore test` · **CLI:** `xcore` · `xrystal` · `tmp` (same binary / aynı binary) · **Service / Servis:** `package.json` scripts
6
+ **CLI:** `xcore` · `xrystal` · `tmp` (same binary / aynı binary)
7
7
 
8
8
  ---
9
9
 
10
- ## npm publish / npm yayın
10
+ ## Quick start / Hızlı başlangıç
11
11
 
12
- | | **EN** | **TR** |
13
- |---|--------|--------|
14
- | **Ships** | `x/dist` (minified `.js` + `.d.ts`), `x/bin`, `x/tmp.yml`, `x/assets` | Aynı — yalnızca bunlar |
15
- | **Never** | `source/` `.ts` in npm | npm'e `source/` `.ts` **asla** gitmez |
16
- | **Runtime** | `main` / `exports` → `x/dist/` | `main` / `exports` → `x/dist/` |
12
+ ### Path A — `create` (recommended / önerilen)
17
13
 
18
- **EN — 3 publish checks (all must pass):**
19
- 1. `package.json` `files` — no `source/`, `main`/`exports` → `x/dist`
20
- 2. `npm pack --dry-run` — no `source/` paths
21
- 3. CI: `prepare-npm-publish` → `verify-npm-pack` (strict: disk + minify)
14
+ **EN:** Clone GitHub template — `x/tmp.yml` and folder layout ready.
22
15
 
23
- **TR — 3 publish kontrolü (hepsi geçmeli):**
24
- 1. `package.json` `files` — `source/` yok, `main`/`exports` → `x/dist`
25
- 2. `npm pack --dry-run` — `source/` yok
26
- 3. CI: `prepare-npm-publish` → `verify-npm-pack` (strict: disk + minify)
16
+ **TR:** GitHub template klonlanır — `x/tmp.yml` ve klasör yapısı hazır gelir.
27
17
 
28
18
  ```bash
29
- bun run release:prepare # lint → build → test
30
- node x/bin/scripts/verify-publish-config.mjs # local prepublish gate
19
+ mkdir my-api && cd my-api
20
+ bun init -y
21
+ bun add @xrystal/core
22
+ npx xcore create my-api .
31
23
  ```
32
24
 
33
- ---
34
-
35
- ## `tmp.yml` layout / tmp.yml düzeni
36
-
37
- **EN — structure:** `service` (app identity, paths, runtime, build) + `core` (library mechanisms like tmp watch).
38
-
39
- **TR — yapı:** `service` (uygulama kimliği, yollar, runtime, build) + `core` (tmp izleme gibi kütüphane mekanizmaları).
40
-
41
- ```yaml
42
- project:
43
- name: x
44
-
45
- configs:
46
- service:
47
- name: my-api
48
- framework: elysia
49
- protocols: [http, ws]
50
-
51
- paths:
52
- root: x # EN: CLI root (test/dev/build) · TR: test/dev/build kökü
53
- source: ./source # EN: source tree + dev entry · TR: kaynak + dev girişi
54
- special:
55
- tests: tests
56
- environments: environments
57
- dist: dist
58
-
59
- loaders:
60
- dto: { withDefaultHeaders: true }
61
- loggers: { logLevel: info }
62
- controller: {}
63
-
64
- build:
65
- typecheck: true # EN: build override · TR: build override
66
- minify: true # EN: @xrystal/core — minify x/dist JS · TR: x/dist JS küçültme
67
-
68
- core:
69
- tmp:
70
- fileWatchIntervalMs: 500
71
-
72
- end:
73
- version: 1
74
- ```
75
-
76
- | Block / Blok | Keys / Alanlar | Role / Rol |
77
- |--------------|----------------|------------|
78
- | `configs.service` | `name`, `framework`, `paths`, `protocols`, `loaders`, `build` | bu uygulama / servis |
79
- | `configs.service.paths` | `root`, `source`, `special.*` | **EN:** layout + CLI (`dev`/`build`/`test`) · **TR:** layout + CLI (`dev`/`build`/`test`) |
80
- | `configs.core.tmp` | `fileWatchIntervalMs` | tmp.yml dosya izleme (ms) |
81
-
82
- **EN:** Save `tmp.yml` → no restart; loaders reload automatically.
83
- **TR:** Kaydet → restart gerekmez; loader’lar otomatik yenilenir.
84
-
85
- ---
86
-
87
- ## How it works / Sistem nasıl çalışır
88
-
89
- ### EN — overview
90
-
91
- In one sentence: **`tmp.yml` is the project key** — `@xrystal/core` reads it, boots loaders, and sends responses via `@xrystal/dto`.
92
-
93
- | Layer | Module | Role |
94
- |--------|--------|------|
95
- | Defaults | `defaults.json` | `x`, `./source`, `tests`, template URI |
96
- | Constants | `Constants` | Shared TS + CLI values |
97
- | Layout | `tmp-layout.ts` | tmp path resolution — **CLI only** |
98
- | Live config | `{rootFolderPath}/tmp.yml` | framework, loaders, protocols |
99
- | Runtime | `getTmpSnapshot()` | Parse + watch + live reload |
100
-
101
- **Core repo:** `tmp.yml` must live at `x/tmp.yml` only (`ensureCoreTmpEntry`).
102
- **Service:** tmp under `configs.service.paths.root`; runtime uses `getTmpSnapshot()` — no layout module needed.
103
-
104
- **Boot:** `ensureCoreTmpEntry()` → `getTmpSnapshot()` → `coreLoader()` → loaders `syncFromTmp()`.
105
-
106
- See [npm publish / npm yayın](#npm-publish--npm-yayın) for what ships to npm.
107
-
108
- ---
109
-
110
- ### TR — genel bakış
111
-
112
- Tek cümle: **`tmp.yml` projenin anahtarı** — `@xrystal/core` onu okuyup loader’ları ayağa kaldırır; cevaplar `@xrystal/dto` ile gider.
113
-
114
- | Katman | Modül | Rol |
115
- |--------|--------|-----|
116
- | Varsayılanlar | `defaults.json` | `x`, `./source`, `tests`, template URI |
117
- | Sabitler | `Constants` | TS + CLI ortak değerler |
118
- | Layout | `tmp-layout.ts` | tmp yolu — **sadece CLI** |
119
- | Canlı config | `{rootFolderPath}/tmp.yml` | framework, loaders, protocols |
120
- | Runtime | `getTmpSnapshot()` | Parse + watch + canlı güncelleme |
121
-
122
- **Core repo:** `tmp.yml` yalnızca `x/tmp.yml` (`ensureCoreTmpEntry`).
123
- **Servis:** tmp `configs.service.paths.root` altında; runtime’da `getTmpSnapshot()` yeterli — layout modülü gerekmez.
124
-
125
- **Boot:** `ensureCoreTmpEntry()` → `getTmpSnapshot()` → `coreLoader()` → loader’lar `syncFromTmp()`.
126
-
127
- npm için → [npm publish / npm yayın](#npm-publish--npm-yayın).
128
-
129
- ---
130
-
131
- ## How it works — detail / Sistem nasıl çalışır — detay
132
-
133
- **EN:** Deep-dive below (mermaid + tables). Turkish prose in this section; key labels are bilingual where it matters.
134
-
135
- **TR:** Aşağıda detay (mermaid + tablolar). Türkçe anlatım; kritik etiketler iki dilli.
136
-
137
- ```mermaid
138
- flowchart TB
139
- subgraph config["Yapılandırma"]
140
- DEF["defaults.json\n(paket varsayılanları)"]
141
- CONST["Constants\n(TS sabitleri)"]
142
- TMP["x/tmp.yml\n(canlı proje ayarı)"]
143
- DEF --> CONST
144
- CONST --> TMP
145
- end
146
-
147
- subgraph boot["Boot"]
148
- ENTRY["dev: source/index.ts · prod: x/dist/index.js"]
149
- GUARD["ensureCoreTmpEntry\n(sadece @xrystal/core)"]
150
- SNAP["getTmpSnapshot()"]
151
- LOADER["coreLoader() → Awilix DI"]
152
- ENTRY --> GUARD
153
- GUARD --> SNAP
154
- SNAP --> LOADER
155
- end
156
-
157
- subgraph runtime["Runtime"]
158
- SYS["System.applyTmp()"]
159
- G["G store"]
160
- L["Logger · Dto · i18n · Controller …"]
161
- TMP --> SNAP
162
- LOADER --> L
163
- TMP -. watch .-> SYS
164
- SYS --> G
165
- SYS --> L
166
- end
25
+ ```bash
26
+ bun add elysia # EN: or express · TR: veya express
27
+ bun run dev
28
+ npx xcore doctor # EN: setup check · TR: kurulum kontrolü
167
29
  ```
168
30
 
169
- | Katman | Dosya / modül | Ne yapar |
170
- |--------|----------------|----------|
171
- | **Varsayılan değerler** | `source/utils/constants/defaults.json` | `x`, `./source`, `tests`, template URI — tek JSON kaynağı |
172
- | **TS sabitleri** | `Constants` (`@/utils/constants`) | CLI + runtime aynı değerleri okur |
173
- | **Layout çözümleme** | `tmp-layout.ts` | `tmp.yml` nerede, `tests/dist/env` yolları — CLI ve ensure için |
174
- | **Canlı config** | `{rootFolderPath}/tmp.yml` | framework, loaders, protocols — **runtime tek kaynak** |
175
- | **Runtime okuma** | `TmpFileLoader` / `getTmpSnapshot()` | Serviste dosyayı bir kez okur, watch ile canlı günceller |
176
-
177
- ### Core kütüphane vs servis
178
-
179
- | | **@xrystal/core repo** | **Microservice** |
180
- |---|------------------------|------------------|
181
- | `tmp.yml` konumu | **Zorunlu** `x/tmp.yml` — başka yerde kopya varsa hata | `configs.service.paths.root` altında (ör. `x/`, `infra/`) |
182
- | Koruma | `ensureCoreTmpEntry()` — stray tmp engeli | Yok; `tmp.yml` recursive bulunur |
183
- | Boot | `ensureCoreTmpEntry` → `getTmpSnapshot` → `coreLoader` | `coreLoader({})` + kendi HTTP sunucun |
184
- | Layout runtime’da | Gerekmez — değerler tmp snapshot’tan | Gerekmez — aynı |
185
-
186
- Servis runtime’ında `tmp-layout` çalıştırmana gerek yok: `getTmpSnapshot()` / `getRuntimeTmpConfigs()` yeterli.
31
+ ### Path B — Manual setup / Manuel kurulum
187
32
 
188
- **EN:** Layout module is for CLI only (`xcore dev`, `xcore tmp`, `xcore test`, `xcore build`).
33
+ **EN:** Install package, seed `tmp.yml`, add scripts.
189
34
 
190
- **TR:** Layout modülü yalnızca CLI içindir (`xcore dev`, `xcore tmp`, `xcore test`, `xcore build`).
35
+ **TR:** Paketi kur, `tmp.yml` seed'le, script'leri ekle.
191
36
 
192
- ### Proje layout’u (`x/`)
193
-
194
- ```
195
- {project-root}/ # EN: repo root · TR: proje kökü
196
- ├── package.json
197
- └── {rootFolderPath}/ # default: x — EN: CLI root (test/dev/build) · TR: CLI kökü
198
- ├── tmp.yml # EN: main config entry · TR: ana giriş
199
- ├── tests/
200
- ├── environments/ # EN: .env files (xcore dev) · TR: .env (xcore dev)
201
- └── dist/ # EN: build output (.js) · TR: build çıktısı (.js)
202
- ```
203
-
204
- Kaynak kodu `service.paths.source` ile ayrı tutulur (core’da `./source`, serviste `./src` olabilir):
205
-
206
- ```yaml
207
- configs:
208
- file:
209
- rootFolderPath: x
210
- configFileWatchIntervalMs: 500
211
-
212
- service:
213
- name: my-api
214
- framework: elysia
215
- folderPath: ./source # veya ./src
216
- protocols: [http]
217
- paths:
218
- tests: tests
219
- environments: environments
220
- dist: dist
221
- build:
222
- typecheck: true # tmp override — outDir/include tsconfig.json'dan
223
- loaders:
224
- dto: { withDefaultHeaders: true }
225
- controller: {}
37
+ ```bash
38
+ mkdir my-api && cd my-api
39
+ bun init -y
40
+ bun add @xrystal/core elysia
41
+ npx xcore tmp # EN: create x/tmp.yml from seed if missing · TR: yoksa seed'den oluşturur
226
42
  ```
227
43
 
228
- **Build ayarları — öncelik sırası**
229
-
230
- | Ayar | 1. tmp.yml `build.*` | 2. `tsconfig.json` | 3. fallback |
231
- |------|----------------------|--------------------|-------------|
232
- | Çıktı klasörü (`outDir`) | `build.outDir` | `compilerOptions.outDir` | `paths.dist` + `rootFolderPath` |
233
- | Giriş dosyaları (glob) | `build.entries` / `build.glob` | `include` / `rootDir` | `service.paths.source` |
234
- | Sourcemap | `build.sourcemap` | `sourceMap` / `inlineSourceMap` | kapalı |
235
- | `.d.ts` | `build.declarations` | `declaration` / full `tsc` | kapalı |
236
- | Minify (core) | `build.minify` | — | kapalı |
237
- | Tip kontrolü | `build.typecheck` | — | `false` |
238
-
239
- Servis örnek `tsconfig.json`:
44
+ `package.json`:
240
45
 
241
46
  ```json
242
47
  {
243
- "include": ["source"],
244
- "compilerOptions": {
245
- "rootDir": "./source",
246
- "outDir": "./x/dist",
247
- "sourceMap": false,
248
- "declaration": false,
249
- "paths": { "@/*": ["source/*"] },
250
- "strict": true
48
+ "dependencies": {
49
+ "@xrystal/core": "^3.38.2",
50
+ "elysia": "^1.4.19"
51
+ },
52
+ "scripts": {
53
+ "dev": "xcore dev",
54
+ "build": "xcore build",
55
+ "start": "xcore start",
56
+ "test": "xcore test",
57
+ "doctor": "xcore doctor"
251
58
  }
252
59
  }
253
60
  ```
254
61
 
255
- `x`, `dist`, kaynak klasörü — tek yerden `outDir` / `include` ile; tmp.yml'de tekrar yazmana gerek yok (override istemiyorsan).
256
-
257
- `tmp.yml` yoksa:
258
-
259
- **EN:** `xcore tmp` or `xcore dev` copies seed from `@xrystal/core/x/tmp.yml`.
260
-
261
- **TR:** `xcore tmp` veya `xcore dev` → seed `@xrystal/core/x/tmp.yml` kopyalanır.
262
-
263
- ### Boot sırası (lib)
264
-
265
- 1. Core repo ise `ensureCoreTmpEntry()` — `x/tmp.yml` var mı, tek mi?
266
- 2. `getTmpSnapshot()` — yaml parse, ilk snapshot
267
- 3. `coreLoader()` — Awilix: System → Configs → Kafka → Logger → … → Controller
268
- 4. Her loader `onInit`: `syncFromTmp()` + `bindLoaderTmpSync()` (dosya değişince otomatik)
269
-
270
- `tmp.yml` kaydedilince restart gerekmez — `TmpFileLoader` watch → `System.applyTmp()` → tüm loader’lar yeniden sync.
62
+ **EN:** No global `xcore` install — runs via `node_modules/.bin` after `bun add @xrystal/core`.
271
63
 
272
- ### CLI vs runtime / CLI ve runtime
64
+ **TR:** Global `xcore` gerekmez — `@xrystal/core` kurulunca `node_modules/.bin` üzerinden çalışır.
273
65
 
274
- | Tool / Araç | EN | TR |
275
- |---------------|----|----|
276
- | `xcore` / `xrystal` / `tmp` | Same binary — dev, test, build, doctor, tag, tmp ensure, create | Aynı binary — dev, test, build, doctor, tag, tmp ensure, create |
277
- | `getTmpSnapshot()` | In-app config | Uygulama içi config |
278
- | `dtoMiddleware()` + `ctr()` | HTTP handler pipeline | HTTP handler pipeline |
279
- | `realtimeMiddleware()` + `runAction()` | WebSocket / Socket.IO | WebSocket / Socket.IO |
280
-
281
- ---
282
-
283
- ## 5 dakikada çalışan microservice
284
-
285
- Tek repo, tek `tmp.yml`, tek boot — Elysia HTTP örneği:
66
+ ### Project layout / Proje düzeni
286
67
 
287
68
  ```
288
69
  my-api/
289
- ├── x/
290
- │ ├── tmp.yml
291
- │ ├── tests/ # EN: service tests (xcore test) · TR: servis testleri (xcore test)
292
- │ └── environments/
293
- ├── src/
294
- │ ├── boot.ts
295
- │ └── controllers/user.ts
296
- └── package.json
297
- ```
298
-
299
- **1) Kur**
300
-
301
- ```bash
302
- npm i @xrystal/core elysia
70
+ ├── package.json
71
+ ├── source/
72
+ │ ├── index.ts # EN: dev entry (xcore dev) · TR: dev girişi
73
+ │ └── controllers/
74
+ └── x/
75
+ ├── tmp.yml # EN: single config source · TR: tek config kaynağı
76
+ ├── environments/ # .dev.env, .prod.env
77
+ └── tests/
303
78
  ```
304
79
 
305
- **2) `x/tmp.yml`**
80
+ ### Minimal `x/tmp.yml`
306
81
 
307
82
  ```yaml
308
83
  configs:
309
- file:
310
- rootFolderPath: x
311
-
312
84
  service:
313
85
  name: my-api
314
- framework: elysia
315
- folderPath: ./src
86
+ framework: elysia # express | elysia | node | fetch
87
+ paths:
88
+ root: ./x
89
+ source: ./source
316
90
  protocols: [http]
317
91
  loaders:
318
- system:
319
- gStore:
320
- options: { bootstrap: true, autoCreateProps: false }
321
- vars: { maintenance: false }
322
92
  dto: { withDefaultHeaders: true }
323
93
  loggers: { logLevel: info }
324
94
  controller: {}
325
95
  ```
326
96
 
327
- **3) Controller**
97
+ ### First endpoint / İlk endpoint (~5 min)
328
98
 
329
99
  ```typescript
330
- // src/controllers/user.ts
100
+ // source/controllers/user.ts
331
101
  import Controller from '@xrystal/core/loader/controller'
332
102
 
333
103
  class UserController extends Controller {
334
104
  list = this.ctr({
335
- logic: async () => ({ data: [{ id: 1, name: 'Ada' }], message: '@successfully user' }),
105
+ logic: async () => ({ data: [{ id: 1 }], message: '@successfully user' }),
336
106
  })
337
107
  }
338
-
339
108
  export const userCtrl = new UserController()
340
109
  ```
341
110
 
342
- **4) Boot + route**
343
-
344
111
  ```typescript
345
- // src/boot.ts
112
+ // source/index.ts
346
113
  import { Elysia } from 'elysia'
347
- import coreLoader from '@xrystal/core/project'
114
+ import coreLoader from '@xrystal/core'
348
115
  import { dtoMiddleware } from '@xrystal/core/utils'
349
116
  import { userCtrl } from './controllers/user'
350
117
 
351
118
  await coreLoader({})
352
- new Elysia()
353
- .use(dtoMiddleware())
354
- .get('/users', userCtrl.list)
355
- .listen(3000)
119
+ new Elysia().use(dtoMiddleware()).get('/users', userCtrl.list).listen(3000)
356
120
  ```
357
121
 
358
- **5) Çalıştır**
359
-
360
122
  ```bash
361
- # package.json scripts ile (önerilen)
362
- bun run dev # "dev": "xcore dev"
363
-
364
- # veya doğrudan
365
- bun src/boot.ts
366
- xcore doctor # servis + @xrystal/core uyumu
123
+ bun run dev
367
124
  # GET http://localhost:3000/users
368
125
  ```
369
126
 
370
- Servis `package.json` örneği:
371
-
372
- ```json
373
- {
374
- "dependencies": { "@xrystal/core": "^3.32.2", "elysia": "^1.4.19" },
375
- "scripts": {
376
- "dev": "xcore dev",
377
- "build": "xcore build",
378
- "start:dist": "xcore start",
379
- "test": "xcore test",
380
- "lint": "eslint .",
381
- "sync-toolchain": "xcore sync-toolchain",
382
- "doctor": "xcore doctor",
383
- "version:check": "xcore version",
384
- "release:tag": "xcore tag",
385
- "hooks:install": "xcore hooks install"
386
- }
387
- }
388
- ```
389
-
390
- **İlk kurulum / klasör adı değişince (manuel, bir kez):**
391
-
392
- ```bash
393
- bun run sync-toolchain # tmp.yml → tsconfig paths; eslint tmp'den okur
394
- bun run doctor # drift kontrolü
395
- # sync çıktısındaki satırı bunfig.toml [resolve.alias]'a ekle
396
- ```
397
-
398
- Detay: [Servislerde `sync-toolchain`](#servislerde-sync-toolchain-manuel)
399
-
400
- Public API:
127
+ ---
401
128
 
402
- ```typescript
403
- import { dtoMiddleware, G, runWithTrace, getRuntimeTmpConfigs } from '@xrystal/core/utils'
404
- import { System, DtoRuntime, Controller } from '@xrystal/core/loader'
405
- import coreLoader from '@xrystal/core/project'
406
- ```
129
+ ## Daily commands / Günlük komutlar
407
130
 
408
- `tmp.yml` kaydedilince loader'lar otomatik `syncFromTmp()` — restart gerekmez.
131
+ | Command / Komut | EN | TR |
132
+ |-----------------|----|----|
133
+ | `xcore create [name] [path]` | Start project from template + `tmp.yml` | Template + `tmp.yml` ile proje başlat |
134
+ | `xcore tmp` | Create `tmp.yml` from seed if missing | `tmp.yml` yoksa seed'den oluştur |
135
+ | `xcore dev` | Watch `source/index.ts` + dev env | `source/index.ts` watch + dev env |
136
+ | `xcore build` | Output → `x/dist` | Çıktı → `x/dist` |
137
+ | `xcore start` | Run `x/dist` + prod env | `x/dist` + prod env |
138
+ | `xcore test` | Run `x/tests` | `x/tests` çalıştır |
139
+ | `xcore doctor` | CLI, runtime, package health | CLI, runtime, paket uyumu |
409
140
 
410
141
  ---
411
142
 
412
- ## Quick examples (copy-paste)
143
+ ## Reference / Referans
413
144
 
414
- ### 1) `x/tmp.yml` — single source of truth
415
-
416
- ```yaml
417
- configs:
418
- file:
419
- rootFolderPath: x
420
- configFileWatchIntervalMs: 500
145
+ | Topic / Konu | Section / Bölüm |
146
+ |--------------|-----------------|
147
+ | Controller, `ctr()` | [Controller](#controller) |
148
+ | Express / Elysia | [Framework](#express--elysia) |
149
+ | DI, boot, tmp watch | [DI](#di--tmpyml) |
150
+ | Locale / dil | [i18n](#i18n--locale) |
151
+ | Global state | [G store](#g-store) |
152
+ | WebSocket | [Realtime](#realtime) |
153
+ | API response shape | [DTO](#dto-responses--dto-cevapları) |
154
+ | End-to-end flow | [Usage guide](#usage-guide--kullanım-rehberi) |
421
155
 
422
- service:
423
- name: my-api
424
- framework: elysia # elysia | express | node | fetch
425
- folderPath: ./src
426
- protocols: [http, ws] # http, ws, socketio
427
- loaders:
428
- system:
429
- gStore:
430
- options:
431
- bootstrap: true
432
- autoCreateProps: false
433
- vars:
434
- maintenance: false
435
- dto: { withDefaultHeaders: true }
436
- localization: { fallbackLang: en, preloadLangs: [en, tr] }
437
- loggers: { logLevel: debug }
438
- controller: {}
439
- ```
156
+ ---
440
157
 
441
- Save the file → **live reload**: `System.applyTmp()` → `G.configureFromTmp()` → every loader `syncFromTmp()`.
158
+ ## Controller
442
159
 
443
- ---
160
+ **EN:** One endpoint = one class property + `this.ctr()`. Wire URL → property. No manual `res.json()`.
444
161
 
445
- ### 2) Controller + `ctr()` (HTTP)
162
+ **TR:** Bir endpoint = bir property + `this.ctr()`. URL → property bağla. `res.json()` yazmazsın.
446
163
 
447
164
  ```typescript
448
165
  import Controller from '@xrystal/core/loader/controller'
449
166
 
450
167
  class UserController extends Controller {
451
168
  list = this.ctr({
452
- logic: async ({ req }) => ({ data: [], message: '@successfully user' }),
453
- })
454
-
455
- create = this.ctr({
456
- logic: async ({ req }) => ({ data: req.body }),
169
+ logic: async ({ req }) => {
170
+ return { data: [], message: '@successfully user' }
171
+ },
457
172
  })
458
173
  }
459
-
460
174
  export const userCtrl = new UserController()
461
175
  ```
462
176
 
177
+ ```typescript
178
+ app.use(dtoMiddleware())
179
+ app.get('/users', userCtrl.list)
180
+ ```
181
+
182
+ | In `logic` / Logic içinde | EN | TR |
183
+ |---------------------------|----|----|
184
+ | `req.body`, `req.query`, `req.params` | Normalized input | Normalize girdi |
185
+ | `req.requestId` | Trace id | İzleme id |
186
+ | `req.t` | i18n function | Çeviri fonksiyonu |
187
+ | `this.logger` | Logger from DI | DI logger |
188
+
463
189
  ---
464
190
 
465
- ### 3) Elysia (default HTTP)
191
+ ## Express & Elysia
466
192
 
467
- ```typescript
468
- import { Elysia } from 'elysia'
469
- import { dtoMiddleware } from '@xrystal/core/utils'
470
- import { userCtrl } from './controllers/user'
193
+ **EN:** `tmp.yml` → `configs.service.framework` picks the HTTP stack.
471
194
 
472
- new Elysia()
473
- .use(dtoMiddleware())
474
- .get('/users', userCtrl.list)
475
- .post('/users', userCtrl.create)
476
- .listen(3000)
477
- ```
195
+ **TR:** `tmp.yml` → `configs.service.framework` HTTP stack'i seçer.
478
196
 
479
- ---
197
+ **Express**
480
198
 
481
- ### 4) Express
199
+ ```yaml
200
+ configs:
201
+ service:
202
+ framework: express
203
+ ```
482
204
 
483
205
  ```typescript
484
206
  import express from 'express'
207
+ import coreLoader from '@xrystal/core'
485
208
  import { dtoMiddleware } from '@xrystal/core/utils'
486
- import { userCtrl } from './controllers/user'
487
209
 
210
+ await coreLoader({})
488
211
  const app = express()
489
212
  app.use(dtoMiddleware('express'))
490
213
  app.get('/users', userCtrl.list)
491
- app.post('/users', userCtrl.create)
492
214
  app.listen(3000)
493
215
  ```
494
216
 
495
- ---
496
-
497
- ### 5) Fetch / Bun.serve
217
+ **Elysia**
498
218
 
499
- `tmp.yml` → `framework: fetch`
219
+ ```yaml
220
+ configs:
221
+ service:
222
+ framework: elysia
223
+ ```
500
224
 
501
225
  ```typescript
502
- import { userCtrl } from './controllers/user'
226
+ import { Elysia } from 'elysia'
227
+ import coreLoader from '@xrystal/core'
228
+ import { dtoMiddleware } from '@xrystal/core/utils'
503
229
 
504
- Bun.serve({
505
- port: 3000,
506
- fetch: (req) => userCtrl.list(req),
507
- })
230
+ await coreLoader({})
231
+ new Elysia().use(dtoMiddleware()).get('/users', userCtrl.list).listen(3000)
508
232
  ```
509
233
 
510
- ---
511
-
512
- ### 6) WebSocket — same controller, different protocol
513
-
514
- ```typescript
515
- import { WebSocketServer } from 'ws'
516
- import Controller from '@xrystal/core/loader/controller'
517
- import { realtimeMiddleware } from '@xrystal/core/utils'
518
-
519
- class ChatController extends Controller {
520
- onMessage = this.ctr({
521
- logic: async ({ req }) => ({ data: { text: req.body } }),
522
- }, { protocol: 'ws' })
523
- }
234
+ | Framework | Middleware | EN | TR |
235
+ |-----------|------------|----|----|
236
+ | express | `dtoMiddleware('express')` | Default Express stack | Express stack |
237
+ | elysia | `dtoMiddleware()` | Default Elysia stack | Elysia stack |
238
+ | node | `dtoMiddleware('node')` | Raw `createServer` | Ham HTTP |
239
+ | fetch | none | `ctr()` attaches builder per request | Request başına builder |
524
240
 
525
- const chatCtrl = new ChatController()
526
- const wss = new WebSocketServer({ port: 3001 })
241
+ **EN:** Realtime (ws / socket.io) is separate from HTTP framework — see [Realtime](#realtime).
527
242
 
528
- wss.on('connection', (socket) => {
529
- realtimeMiddleware('ws')(socket, () => {})
530
- socket.on('message', chatCtrl.onMessage.with(socket))
531
- })
532
- ```
243
+ **TR:** Realtime (ws / socket.io) HTTP framework'ten bağımsız — [Realtime](#realtime).
533
244
 
534
245
  ---
535
246
 
536
- ### 7) Socket.IO
537
-
538
- ```typescript
539
- import { Server } from 'socket.io'
540
- import { realtimeMiddleware } from '@xrystal/core/utils'
247
+ ## DI & tmp.yml
541
248
 
542
- io.use(realtimeMiddleware('socketio'))
543
- io.on('connection', (socket) => {
544
- socket.on('chat', chatCtrl.onChat.with(socket)) // protocol: 'socketio' on ctr
545
- })
546
- ```
249
+ **EN:** Single source of truth: **`x/tmp.yml`** at project root. Loaders read a live snapshot, not the file directly.
547
250
 
548
- ---
251
+ **TR:** Tek kaynak: proje kökündeki **`x/tmp.yml`**. Loader'lar dosyayı değil canlı snapshot'ı okur.
549
252
 
550
- ### 8) No controller — `runAction`
253
+ | Step / Adım | EN | TR |
254
+ |-------------|----|----|
255
+ | 1 | `await coreLoader({})` at boot — Awilix DI (System, Logger, Dto, Controller, …) | Boot'ta `coreLoader` — Awilix DI |
256
+ | 2 | Edit `tmp.yml` → loaders auto-sync (log level, i18n, dto, …) | `tmp.yml` değişince loader'lar sync |
257
+ | 3 | Read config at runtime: `getRuntimeTmpConfigs()` or DI `System` | Runtime config: `getRuntimeTmpConfigs()` veya `System` |
551
258
 
552
259
  ```typescript
553
- import { realtimeMiddleware, runAction } from '@xrystal/core/utils'
260
+ import coreLoader from '@xrystal/core'
261
+ import { getRuntimeTmpConfigs } from '@xrystal/core/utils'
554
262
 
555
- socket.on('message', async () => {
556
- await runAction({ protocol: 'ws', socket }, async () =>
557
- socket.builder.as.ok({ pong: true }).build(),
558
- )
559
- })
263
+ await coreLoader({})
264
+ const tmp = getRuntimeTmpConfigs()
560
265
  ```
561
266
 
562
- ---
563
-
564
- ### 9) G store (process-wide, Zustand)
267
+ **EN:** `loaders.*` in `tmp.yml` enables subsystems (logger, localization, dto, system/gStore, …).
565
268
 
566
- ```typescript
567
- import { G, GStoreScopeEnum, LoggerLayerEnum } from '@xrystal/core/utils'
269
+ **TR:** `tmp.yml` içindeki `loaders.*` hangi alt sistemlerin açılacağını belirler.
568
270
 
569
- G.get('maintenance', false)
570
- G.set('maintenance', true) // only keys declared in tmp vars (when autoCreateProps: false)
271
+ ---
571
272
 
572
- G.subscribeKey('maintenance', (value, prev) => {
573
- logger.log(LoggerLayerEnum.INFO, 'maintenance', { value, prev })
574
- })
273
+ ## i18n / locale
575
274
 
576
- G.scope(GStoreScopeEnum.GLOBAL).set?.('flag', 1)
577
- G.scope(GStoreScopeEnum.RUN).get('requestId') // inside request / job
578
- G.scope(GStoreScopeEnum.CONTROLLER).patch?.({ metadata: { locals: { userId: 1 } } })
579
- ```
275
+ **EN:** i18next via `loaders.localization` in `tmp.yml`. Use `@key` in responses or `req.t()`.
580
276
 
581
- Controller check example:
277
+ **TR:** `loaders.localization` ile i18next. Cevaplarda `@anahtar` veya `req.t()` kullan.
582
278
 
583
- ```typescript
584
- checks: () => G.get('maintenance', false) ? { message: '@unsuccessful maintenance' } : true
279
+ ```yaml
280
+ loaders:
281
+ localization:
282
+ fallbackLang: en
283
+ preloadLangs: [en, tr]
585
284
  ```
586
285
 
587
- ---
588
-
589
- ### 10) Trace / cron (no HTTP protocol)
590
-
591
286
  ```typescript
592
- import { runWithTrace, LoggerLayerEnum } from '@xrystal/core/utils'
593
-
594
- await runWithTrace('nightly-sync', async () => {
595
- logger.log(LoggerLayerEnum.INFO, 'started')
596
- }, 'sync-job')
287
+ return { message: '@successfully user' }
288
+ // or / veya req.t('responseMessage.successfully')
597
289
  ```
598
290
 
599
- ---
291
+ **EN:** Express — mount i18next middleware **before** `dtoMiddleware`.
600
292
 
601
- ### 11) DI boot + tmp reload (internal flow)
293
+ **TR:** Express — i18next middleware'i `dtoMiddleware`'den **önce** tak.
602
294
 
603
295
  ```typescript
604
- // source/project/index.ts — Awilix order matters
605
- await x.initialize([
606
- { service: System, props: { core } },
607
- { service: Configs },
608
- { service: KafkaForCore },
609
- { service: Logger },
610
- // Events, Localizations, Dto, Controller, Clients …
611
- ])
612
-
613
- // Each loader onInit:
614
- await this.syncFromTmp()
615
- bindLoaderTmpSync(this)
296
+ app.use(i18nextMiddleware.handle(i18n))
297
+ app.use(dtoMiddleware('express'))
616
298
  ```
617
299
 
618
- Public imports — always from utils barrel:
619
-
620
- ```typescript
621
- import {
622
- bindLoaderTmpSync,
623
- dtoMiddleware,
624
- G,
625
- GStoreScopeEnum,
626
- getRuntimeTmpConfigs,
627
- getConfiguredProtocols,
628
- realtimeMiddleware,
629
- runAction,
630
- runWithTrace,
631
- type ITmpSyncLoader,
632
- } from '@xrystal/core/utils'
633
- ```
300
+ **EN:** Client sends `Accept-Language: tr` → Turkish message.
634
301
 
635
- More walkthrough: [Kullanım örnekleri](#kullanım-örnekleri-sıralı--kopyala-yapıştır) · Realtime: [Realtime rehberi](#realtime-rehberi--ws-vs-socketio-kafanda-otursun) · Architecture: [DI + tmp.yml](#di--tmpyml--boot-ve-canlı-güncelleme)
302
+ **TR:** Client `Accept-Language: tr` gönderir → Türkçe mesaj döner.
636
303
 
637
304
  ---
638
305
 
639
- ### EN — mental model
640
-
641
- Two independent axes:
642
-
643
- | Axis | Values | Source | Used when |
644
- |------|--------|--------|-----------|
645
- | **framework** | elysia, express, node, fetch | `tmp.yml` → `dtoMiddleware()` | HTTP only |
646
- | **protocol** | http, ws, socketio | `ctr(..., { protocol })`, `runAction()`, `realtimeMiddleware()` | Every action |
647
-
648
- Three stores (do not mix):
649
-
650
- | Store | API | Lifetime |
651
- |-------|-----|----------|
652
- | Run context | `getRequestId`, `runWithTrace` | Per request / job |
653
- | Controller context | `this.req`, `builder` | Per request |
654
- | **G** | `G`, `system.g` | Process-wide — [Zustand](https://zustand.docs.pmnd.rs/) |
306
+ ## G store
655
307
 
656
- Quick wiring: `dtoMiddleware()` once → `userCtrl.list` on routes → `ctr()` returns handler → `dispatchResult()` sends via dto sink.
308
+ **EN:** App-wide shared state (Zustand). Bootstrapped from `tmp.yml` → `loaders.system.gStore.vars`.
657
309
 
658
- ### TR — zihinsel model
310
+ **TR:** Uygulama genelinde paylaşılan state (Zustand). Boot'ta `tmp.yml` → `gStore.vars`.
659
311
 
660
- İki bağımsız eksen:
312
+ ```yaml
313
+ loaders:
314
+ system:
315
+ gStore:
316
+ vars:
317
+ maintenance: false
318
+ ```
661
319
 
662
- | Eksen | Değerler | Kaynak | Ne zaman |
663
- |-------|----------|--------|----------|
664
- | **framework** | elysia, express, node, fetch | `tmp.yml` → `dtoMiddleware()` | Sadece HTTP |
665
- | **protocol** | http, ws, socketio | `ctr(..., { protocol })`, `runAction()`, `realtimeMiddleware()` | Her action |
320
+ ```typescript
321
+ import { G } from '@xrystal/core/utils'
666
322
 
667
- Üç depo (birbirinin yerine geçmez):
323
+ G.get('maintenance')
324
+ G.set('maintenance', true)
668
325
 
669
- | Depo | API | Ömür |
670
- |------|-----|------|
671
- | Run context | `getRequestId`, `runWithTrace` | İstek / job başına |
672
- | Controller context | `this.req`, `builder` | İstek başına |
673
- | **G** | `G`, `system.g` | Process geneli — [Zustand](https://zustand.docs.pmnd.rs/) |
326
+ checks: () => G.get('maintenance') ? { message: '@unsuccessful maintenance' } : true
327
+ ```
674
328
 
675
- Hızlı kalıp: bir kez `dtoMiddleware()` → route'a `userCtrl.list` → `ctr()` handler döner → `dispatchResult()` dto sink ile gönderir.
329
+ | Store | Lifetime / Ömür | EN | TR |
330
+ |-------|-----------------|----|----|
331
+ | **G** | App / Uygulama | Global flags, cache, maintenance | Global flag, cache, maintenance |
332
+ | **Controller context** | Request / İstek | `this.req`, `builder` | `this.req`, `builder` |
333
+ | **Run context** | Request or job / İstek veya job | `requestId`, log trace | `requestId`, log trace |
676
334
 
677
335
  ---
678
336
 
679
- ## Supported frameworks
680
-
681
- Set **one** HTTP default in `tmp.yml` — it drives `dtoMiddleware()` and `ctr()` for **HTTP only**.
682
-
683
- | `tmp.yml` value | Layer | Middleware | Notes |
684
- |---|---|---|---|
685
- | **`elysia`** | HTTP stack (default) | `runtime.elysia()` | `.use(dtoMiddleware())` |
686
- | **`express`** | HTTP stack | `runtime.express()` | `app.use(dtoMiddleware('express'))` |
687
- | **`node`** | HTTP stack | `runtime.node()` | Raw `createServer` |
688
- | **`fetch`** | HTTP stack | none (per-request) | `forRequest(req)` inside `ctr()` |
689
- | **`websocket`** | Realtime attach | `runtime.websocket()` | Use with `toWebSocket()` — **not** HTTP framework |
690
- | **`socketio`** | Realtime attach | `runtime.socketIo()` | Use with `toSocketIo()` — **not** HTTP framework |
691
-
692
- ### HTTP framework vs realtime protocol
337
+ ## Realtime
693
338
 
694
- | Eksen | Ne? | Nereden? | Dispatch |
695
- |-------|-----|----------|----------|
696
- | **framework** | HTTP mimarisi (elysia, express, node, fetch) | `tmp.yml` → `dtoMiddleware()` | Sadece `protocol: http` |
697
- | **protocol** | Transport (http, ws, socketio) | `ctr(..., { protocol })` veya `runAction()` | `dispatchResult` önce buna bakar |
339
+ **EN:** Not HTTP — use `protocol: 'ws'` or `'socketio'` on `ctr()`. Set `protocols` in `tmp.yml`.
698
340
 
699
- `tmp.yml` → `configs.protocols` = uygulamanın **desteklediği** protokoller (`getConfiguredProtocols()` / controller `onInit`):
700
-
701
- ```yaml
702
- configs:
703
- framework: elysia
704
- protocols:
705
- - http
706
- - ws
707
- loaders:
708
- dto: { withDefaultHeaders: true }
709
- localization: { fallbackLang: en, preloadLangs: [en, tr] }
710
- controller: {}
711
- ```
712
-
713
- Action başına protocol — controller bağımsızlığı:
341
+ **TR:** HTTP değil — `ctr()` üzerinde `protocol: 'ws'` veya `'socketio'`. `tmp.yml` → `protocols`.
714
342
 
715
343
  ```typescript
716
- list = this.ctr({ logic: async ({ req }) => ({ data: [] }) })
717
-
718
344
  onMessage = this.ctr({ logic: async () => ({ ok: true }) }, { protocol: 'ws' })
719
345
 
720
- onChat = this.ctr({ logic: async () => ({ ok: true }) }, { protocol: 'socketio' })
721
- ```
722
-
723
- **Realtime wiring (middleware + ctr):**
724
-
725
- ```typescript
726
346
  wss.on('connection', (socket) => {
727
347
  realtimeMiddleware()(socket, () => {})
728
348
  socket.on('message', chatCtrl.onMessage.with(socket))
729
349
  })
730
-
731
- io.use(realtimeMiddleware('socketio'))
732
- io.on('connection', (socket) => {
733
- socket.on('chat', chatCtrl.onChat.with(socket))
734
- })
735
350
  ```
736
351
 
737
- **Controller olmadan saf fonksiyon:**
738
-
739
- ```typescript
740
- await runAction({ protocol: 'ws', socket }, async () => {
741
- return socket.builder.as.ok({ ping: 1 }).build()
742
- })
352
+ ```yaml
353
+ protocols: [http, ws] # EN: or [http, socketio] · TR: veya [http, socketio]
743
354
  ```
744
355
 
745
- `withProtocol(() => { ... }, 'ws')` — zaten açık context varsa protocol tag'ler (iç içe logic).
356
+ ---
746
357
 
747
- Override per app without editing `tmp.yml`:
358
+ ## DTO responses / DTO cevapları
748
359
 
749
- ```typescript
750
- app.use(dtoMiddleware('elysia'))
751
- app.use(dtoMiddleware({ framework: 'socketio' }))
752
- ```
360
+ **EN:** Standard `{ success, message, data, … }` via `@xrystal/dto`. `dtoMiddleware()` attaches builder; `ctr()` dispatches the result.
361
+
362
+ **TR:** `@xrystal/dto` ile standart `{ success, message, data, … }`. `dtoMiddleware()` builder takar; `ctr()` sonucu dispatch eder.
753
363
 
754
- `@xrystal/dto` v26.6.28+ does **not** pick framework — core maps config → the correct adapter (`socketio` → `socketIo()`, not `websocket()`).
364
+ Details / detay: [`@xrystal/dto`](https://www.npmjs.com/package/@xrystal/dto)
755
365
 
756
366
  ---
757
367
 
758
- ## Realtime rehberi — WS vs Socket.IO (kafanda otursun)
368
+ ## Usage guide / Kullanım rehberi
759
369
 
760
- HTTP ile realtime **aynı şey değil**. Realtime'da `framework` (elysia/express) **devreye girmez**. Sadece **protocol** (`ws` veya `socketio`) önemli.
370
+ **EN:** Typical flow when building a service.
761
371
 
762
- ### Tek kalıp — her realtime event için 3 adım
372
+ **TR:** Servis yazarken tipik akış.
763
373
 
764
374
  ```
765
- 1. realtimeMiddleware() → socket.builder tak (tmp.yml veya explicit protocol)
766
- 2. logic çalış → ctr VEYA runAction
767
- 3. dispatch otomatik → send() veya emit()
375
+ 1. xcore create or bun add + xcore tmp
376
+ 2. tmp.yml → framework, loaders, paths
377
+ 3. coreLoader() → once at top of index.ts
378
+ 4. Controller → ctr() per endpoint
379
+ 5. Framework → dtoMiddleware + routes
380
+ 6. xcore dev → develop
381
+ 7. xcore build → start → production
768
382
  ```
769
383
 
770
- **Protocol nereden gelir?**
384
+ ### Express — end-to-end / uçtan uca
385
+
386
+ ```typescript
387
+ // source/index.ts
388
+ import express from 'express'
389
+ import coreLoader from '@xrystal/core'
390
+ import { dtoMiddleware } from '@xrystal/core/utils'
391
+ import { userCtrl } from './controllers/user'
771
392
 
772
- | tmp.yml `protocols` | `realtimeMiddleware()` |
773
- |---------------------|-------------------------|
774
- | `[http, ws]` | Otomatik **ws** (default) |
775
- | `[http, socketio]` | Otomatik **socketio** |
776
- | `[http, ws, socketio]` | **Arg zorunlu:** `realtimeMiddleware('ws')` veya `realtimeMiddleware('socketio')` |
777
- | Override | `realtimeMiddleware('socketio')` — açıkça belirt |
393
+ await coreLoader({})
778
394
 
779
- ```yaml
780
- configs:
781
- protocols:
782
- - http
783
- - ws
395
+ const app = express()
396
+ app.use(dtoMiddleware('express'))
397
+ app.get('/users', userCtrl.list)
398
+ app.listen(3000)
784
399
  ```
785
400
 
786
- ### WS mi Socket.IO mu?
787
-
788
- | | **Native WebSocket (`ws`)** | **Socket.IO (`socketio`)** |
789
- |--|--|--|
790
- | Client tarafı | `WebSocket`, `ws` kütüphanesi | `socket.io-client` |
791
- | Cevap gider | `socket.send(JSON string)` | `socket.emit('response', object)` |
792
- | Middleware | `realtimeMiddleware()` veya `'ws'` | `realtimeMiddleware('socketio')` |
793
- | ctr protocol | `{ protocol: 'ws' }` | `{ protocol: 'socketio' }` |
794
- | tmp.yml | `protocols: [http, ws]` | `protocols: [http, ws, socketio]` |
795
-
796
- Aynı `FinalResult` (.build()) — sadece **taşıma** farklı.
797
-
798
- ### Yol A — Controller + ctr (checks, i18n, schema)
799
-
800
- Logic karmaşıksa bunu kullan. HTTP'deki `ctr()` ile **aynı API**, sadece `{ protocol }` eklersin.
801
-
802
- ```typescript
803
- import { realtimeMiddleware } from '@xrystal/core/utils'
804
-
805
- class ChatController extends Controller {
806
- list = this.ctr({
807
- logic: async ({ req }) => ({ data: [] }),
808
- })
809
-
810
- onMessage = this.ctr({
811
- logic: async ({ req }) => ({ data: { text: req.body } }),
812
- }, { protocol: 'ws' })
813
-
814
- onChat = this.ctr({
815
- logic: async () => ({ data: { room: 'lobby' } }),
816
- }, { protocol: 'socketio' })
817
- }
818
-
819
- const chatCtrl = new ChatController()
820
- ```
821
-
822
- **Bağlama (Native WS — `ws` paketi):**
823
-
824
- ```typescript
825
- import { WebSocketServer } from 'ws'
826
- import { realtimeMiddleware } from '@xrystal/core/utils'
827
-
828
- const wss = new WebSocketServer({ port: 3001 })
829
-
830
- wss.on('connection', (socket) => {
831
- realtimeMiddleware()(socket as any, () => {})
832
-
833
- socket.on('message', chatCtrl.onMessage.with(socket))
834
- })
835
- ```
836
-
837
- **Bağlama (Socket.IO):**
838
-
839
- ```typescript
840
- import { Server } from 'socket.io'
841
- import { realtimeMiddleware } from '@xrystal/core/utils'
842
-
843
- const io = new Server(3002)
844
-
845
- io.use(realtimeMiddleware('socketio'))
846
-
847
- io.on('connection', (socket) => {
848
- socket.on('chat', chatCtrl.onChat.with(socket))
849
- })
850
- ```
851
-
852
- **`.with(socket)` neden?** Event handler (`socket.on('message', fn)`) her mesajda socket vermez — socket bağlantıda sabit. `.with(socket)` socket'i logic'e bağlar. Bağlantı anında tek seferlik: `chatCtrl.onMessage(socket)` de olur.
853
-
854
- ### Yol B — Controller yok (runAction)
855
-
856
- Basit ping/pong, tek satır logic — class açma.
857
-
858
- ```typescript
859
- import { realtimeMiddleware, runAction } from '@xrystal/core/utils'
860
-
861
- wss.on('connection', (socket) => {
862
- realtimeMiddleware()(socket, () => {})
863
-
864
- socket.on('message', async () => {
865
- await runAction({ protocol: 'ws', socket }, async () =>
866
- socket.builder.as.ok({ pong: true }, 'pong').build(),
867
- )
868
- })
869
- })
870
-
871
- io.on('connection', (socket) => {
872
- socket.on('ping', async () => {
873
- await runAction({ protocol: 'socketio', socket }, async () =>
874
- socket.builder.as.ok({ pong: true }).build(),
875
- )
876
- })
877
- })
878
- ```
879
-
880
- ### Ne zaman hangisi?
881
-
882
- | Durum | Kullan |
883
- |-------|--------|
884
- | checks, i18n, `@successfully`, logger | **ctr + protocol** |
885
- | Tek satır ping, cron benzeri basit cevap | **runAction** |
886
- | HTTP endpoint | **ctr** (protocol default http) |
887
-
888
- ### Genişletme (yeni protocol)
889
-
890
- Yeni transport eklemek için 3 nokta:
891
-
892
- 1. `ProtocolEnum` + `parseProtocol('yeni')`
893
- 2. `dispatchResult` → yeni sink
894
- 3. `realtimeMiddleware('yeni')` veya `runAction({ protocol: 'yeni' })`
895
-
896
- Controller/ctr API **değişmez** — sadece protocol enum genişler.
897
-
898
- ### Canlı testler
899
-
900
- README tarifleri test olarak koşulur:
901
-
902
- ```bash
903
- bun test x/tests/realtime.examples.test.ts
904
- ```
905
-
906
- Tarif 1–6: ws/socketio × ctr/runAction × gerçek Controller.
907
-
908
- ---
909
-
910
- ## Quick start — ne yapman yeterli?
911
-
912
- Her framework için aynı kalıp: **controller yaz → middleware tak → route/socket bağla**. Controller içinde `res.send()` yok; `ctr()` + `logic` yeter.
913
-
914
- ### Ortak (hepsi)
915
-
916
- 1. `tmp.yml` → `configs.framework: elysia` (default — express/node/fetch override edilebilir)
917
- 2. Controller:
918
-
919
- ```typescript
920
- class UserController extends Controller {
921
- list = this.ctr({
922
- logic: async ({ req }) => ({ data: [] }),
923
- })
924
- }
925
- const userCtrl = new UserController()
926
- ```
927
-
928
- 3. Mesaj (i18n): `return '@successfully user'` — `req.t` ile çevrilir
929
-
930
- ---
931
-
932
- ### Elysia (default)
933
-
934
- 1. `tmp.yml` → `framework: elysia` (veya hiç yazma — default elysia)
935
- 2. `new Elysia().use(dtoMiddleware()).get('/users', userCtrl.list)`
936
-
937
- ### Express
938
-
939
- 1. `app.use(dtoMiddleware('express'))`
940
- 2. `app.get('/users', userCtrl.list)`
941
-
942
- ### Fetch / Bun.serve
943
-
944
- 1. `tmp.yml` → `framework: fetch`
945
- 2. Middleware yok — direkt: `fetch: (req) => userCtrl.list(req)`
946
-
947
- ### Node http
948
-
949
- 1. `tmp.yml` → `framework: node`
950
- 2. `createServer((req, res) => userCtrl.list(req, res))`
951
-
952
- ### WebSocket & Socket.IO
953
-
954
- Realtime için ayrı bölüm: **[Realtime rehberi](#realtime-rehberi--ws-vs-socketio-kafanda-otursun)** (ctr'li / ctr'siz, ws vs socketio).
955
-
956
- Kısa özet:
957
-
958
- 1. `realtimeMiddleware()` — tmp.yml tek realtime ise otomatik (default **ws**); ws + socketio birlikte ise middleware'de explicit belirt
959
- 2. `ctr({ logic }, { protocol: 'ws' })` veya `runAction({ protocol, socket }, fn)`
960
- 3. `socket.on('event', handler.with(socket))`
961
-
962
- ### i18n (dil)
963
-
964
- 1. i18next middleware’i **dtoMiddleware’den önce** tak (Express örneği):
965
-
966
- ```typescript
967
- app.use(i18nextMiddleware.handle(i18n))
968
- app.use(dtoMiddleware())
969
- ```
970
-
971
- 2. Locale dosyaları: `locales/en/translation.json` → `responseMessage.successfully`
972
- 3. Controller’da: `'@successfully user'` veya logic içinde `req.t('responseMessage.successfully')`
973
- 4. Client `Accept-Language: tr` gönderir → Türkçe mesaj döner
974
-
975
- ---
976
-
977
- ## What is `userCtrl.list`?
978
-
979
- `list` is **not** a core keyword — it is **your action name** (you could call it `getUsers`, `index`, `findAll`, anything).
980
-
981
- ```typescript
982
- const userCtrl = new UserController()
983
-
984
- class UserController extends Controller {
985
- list = this.ctr({
986
- logic: async ({ req }) => ({ data: [] }),
987
- })
988
-
989
- create = this.ctr({
990
- logic: async ({ req }) => ({ data: req.body }),
991
- })
992
- }
993
- ```
994
-
995
- `this.ctr({ ... })` registers a **controller action** and returns a framework handler (Express or Elysia).
996
- So `userCtrl.list` is that function — pass it when wiring URLs:
997
-
998
- ```typescript
999
- app.use(dtoMiddleware())
1000
- app.get('/users', userCtrl.list)
1001
- app.post('/users', userCtrl.create)
1002
- ```
1003
-
1004
- ```
1005
- URL path Controller action What runs
1006
- ──────── ───────────────── ───────────
1007
- GET /users → userCtrl.list → ctr() → schema() → logic → dispatch
1008
- POST /users → userCtrl.create → ctr() → schema() → logic → dispatch
1009
- ```
1010
-
1011
- You never call `userCtrl.list()` yourself in app setup — Express/Elysia calls it when a request hits that path.
1012
-
1013
- ---
1014
-
1015
- ## Config
1016
-
1017
- `x/tmp.yml`:
1018
-
1019
- ```yaml
1020
- configs:
1021
- framework: elysia
1022
- service: my-api
1023
-
1024
- protocols:
1025
- - http
1026
- - ws
1027
-
1028
- loaders:
1029
- dto:
1030
- withDefaultHeaders: true
1031
- loggers:
1032
- loadPath: logs
1033
- logLevel: debug
1034
- localization:
1035
- loadPath: assets/langs
1036
- fallbackLang: en
1037
- preloadLangs: [en, tr]
1038
- controller: {}
1039
- ```
1040
-
1041
- | Alan | Ne işe yarar |
1042
- |------|----------------|
1043
- | `framework` | HTTP stack default (elysia) |
1044
- | `protocols` | App allowlist — hangi transport'lara izin var |
1045
- | `loaders.*` | dto, i18n, logger, configs bootstrap |
1046
-
1047
- `framework` is the single default for the whole app when you write `dtoMiddleware()` and `this.ctr({ ... })` without a second argument. You can omit it only if you pass framework explicitly everywhere (not recommended).
1048
-
1049
- ---
1050
-
1051
- ## Who does what
1052
-
1053
- | Responsibility | Package |
1054
- |---|---|
1055
- | Adapter middleware — attach `builder` + send sink | **`@xrystal/dto`** |
1056
- | `schema()`, i18n, business logic | **core / controller** |
1057
- | `dispatchResult()` — per-framework send | **core / dispatch** |
1058
- | `dtoMiddleware()`, `runController`, trace id | **core / handlers** |
1059
-
1060
- Core never calls `res.json()` directly. Controller returns `FinalResult` via `.build()`; core dispatches through dto send sinks.
1061
-
1062
- ```
1063
- dtoMiddleware() → expressSink(res) attached to res.builder
1064
- ctr() / toHandler → runController + trace id
1065
- schema() → builder.as.ok(...).build() ← schema only
1066
- dispatchResult() → expressSink(res).dispatch() ← send HERE
1067
- ```
1068
-
1069
- ---
1070
-
1071
- ## Controller
1072
-
1073
- Extend `Controller`, define **one property per endpoint** with `ctr()`:
1074
-
1075
- ```typescript
1076
- import Controller from '@xrystal/core/loader/controller'
1077
- import { LoggerLayerEnum } from '@xrystal/core/utils'
1078
-
1079
- class UserController extends Controller {
1080
- list = this.ctr({
1081
- logic: async ({ req }) => {
1082
- this.logger.log(LoggerLayerEnum.INFO, 'listing users')
1083
- return { data: [] }
1084
- },
1085
- })
1086
- }
1087
-
1088
- const userCtrl = new UserController()
1089
- ```
1090
-
1091
- Wire URLs to those properties:
1092
-
1093
- ```typescript
1094
- app.use(dtoMiddleware())
1095
- app.get('/users', userCtrl.list)
1096
- ```
1097
-
1098
- `ctr()` = `schema()` + trace context + framework handler + dispatch. You do not write `toHandler` yourself.
1099
-
1100
- ### `schema()` pipeline (internal — called by `ctr()`)
1101
-
1102
- 1. **checks** — return `true` or a failure object
1103
- 2. **logic** — main work
1104
- 3. **response** — optional transform
1105
-
1106
- Responses go through `builder.as.ok()` / `.fail()` then `.build()`. Messages support i18n:
1107
-
1108
- ```typescript
1109
- return '@successfully user'
1110
- return '@unsuccessful auth'
1111
- ```
1112
-
1113
- ### Why not embed everything in `schema()` alone?
1114
-
1115
- `schema()` needs `req`, `res`, `builder` from the current HTTP request. Those only exist after the framework calls your route handler. Flow:
1116
-
1117
- ```
1118
- Express calls userCtrl.list(req, res)
1119
- → runController stores req/res in context
1120
- → schema() reads context, returns builder.as.ok(...).build()
1121
- → dispatchResult() → expressSink(res).dispatch()
1122
- ```
1123
-
1124
- `schema()` cannot run before Express gives you `req`/`res`. `ctr()` is the thin glue — one line per action.
1125
-
1126
- ### Where does the HTTP response go? (Express)
1127
-
1128
- You never call `res.send()` in controller code. Chain:
1129
-
1130
- ```
1131
- schema()
1132
- → builder.as.ok(data, message).build()
1133
- dispatchResult()
1134
- → expressSink(res).dispatch(result)
1135
- → res.status(code).json(result.body)
1136
- ```
1137
-
1138
- Middleware attaches sink to builder at request start. Sink runs only when core calls `dispatchResult()` — not on `.build()`.
1139
-
1140
- ### What you get in `logic`
1141
-
1142
- | Field | Description |
1143
- |---|---|
1144
- | `req.body`, `req.query`, `req.params` | Normalized input |
1145
- | `req.requestId` | Trace id (header or generated) |
1146
- | `req.t` | i18n function |
1147
- | `builder` | `@xrystal/dto` response builder |
1148
-
1149
- ---
1150
-
1151
- ## Setup (2 steps)
1152
-
1153
- ### 1. Middleware once — prepares every request
1154
-
1155
- ```typescript
1156
- import { dtoMiddleware } from '@xrystal/core/utils'
1157
-
1158
- app.use(dtoMiddleware())
1159
- app.use(dtoMiddleware('elysia'))
1160
- app.use(dtoMiddleware({ framework: 'express' }))
1161
- ```
1162
-
1163
- `dtoMiddleware(config)` maps config → `runtime.express()` / `.elysia()` / `.socketIo()` / `.websocket()` / `.node()`. Fetch has no global middleware — `ctr()` uses `forRequest(req)` per request.
1164
-
1165
- ### 2. Register routes — tell framework which URL → which action
1166
-
1167
- ```typescript
1168
- app.get('/users', userCtrl.list)
1169
- app.post('/users', userCtrl.create)
1170
- ```
1171
-
1172
- Express requires a handler per route. Middleware cannot replace `app.get` — it runs for all paths but does not know `/users` → `list`.
1173
-
1174
- `toHandler()` still exists for edge cases; prefer `this.ctr()`.
1175
-
1176
- ---
1177
-
1178
- ## Framework examples
1179
-
1180
- ### Express (default)
1181
-
1182
- ```typescript
1183
- import express from 'express'
1184
- import { dtoMiddleware } from '@xrystal/core/utils'
1185
-
1186
- const app = express()
1187
- app.use(dtoMiddleware())
1188
-
1189
- app.get('/health', healthCtrl.check)
1190
- ```
1191
-
1192
- ### Elysia
1193
-
1194
- ```yaml
1195
- configs:
1196
- framework: elysia
1197
- ```
1198
-
1199
- ```typescript
1200
- import { Elysia } from 'elysia'
1201
- import { dtoMiddleware } from '@xrystal/core/utils'
1202
-
1203
- const app = new Elysia()
1204
- .use(dtoMiddleware())
1205
- .get('/health', healthCtrl.check)
1206
- ```
1207
-
1208
- ### Fetch / Bun.serve
1209
-
1210
- ```yaml
1211
- configs:
1212
- framework: fetch
1213
- ```
1214
-
1215
- ```typescript
1216
- class HealthController extends Controller {
1217
- check = this.ctr({
1218
- logic: async () => ({ status: 'ok' }),
1219
- })
1220
- }
1221
-
1222
- Bun.serve({
1223
- fetch: (req) => healthCtrl.check(req),
1224
- })
1225
- ```
1226
-
1227
- No global middleware — `ctr()` calls `forRequest(req)` to attach builder + fetch sink per request.
1228
-
1229
- ### Node (raw http)
1230
-
1231
- ```yaml
1232
- configs:
1233
- framework: node
1234
- ```
1235
-
1236
- ```typescript
1237
- import http from 'node:http'
1238
-
1239
- http.createServer((req, res) => healthCtrl.check(req, res)).listen(3000)
1240
- ```
1241
-
1242
- ### Realtime (özet — detay için üstteki rehber)
1243
-
1244
- Native WS ve Socket.IO aynı 3 adım. `framework` tmp.yml'den gelmez.
1245
-
1246
- ```typescript
1247
- onMessage = this.ctr({ logic: async () => ({ data: {} }) }, { protocol: 'ws' })
1248
- socket.on('message', onMessage.with(socket))
1249
-
1250
- await runAction({ protocol: 'socketio', socket }, async () =>
1251
- socket.builder.as.ok({ ok: true }).build(),
1252
- )
1253
- ```
1254
-
1255
- ---
1256
-
1257
- ## Mimari özeti (basit şema)
1258
-
1259
- Tek cümle: **framework = HTTP taşıyıcı**, **protocol = action tipi**, **3 store = farklı ömür**.
1260
-
1261
- ```mermaid
1262
- flowchart TB
1263
- subgraph process["Process (servis örneği)"]
1264
- G["G — global\nmaintenance, cache, flags\ntmp.yml vars"]
1265
- end
1266
-
1267
- subgraph request["Her istek / job"]
1268
- RUN["Run context (ALS)\nrequestId, kind, trace"]
1269
- CTRL["Controller context (ALS)\nreq, cookies, builder, socket"]
1270
- RUN --> CTRL
1271
- end
1272
-
1273
- MW["dtoMiddleware()"] --> RUN
1274
- CTRL --> LOGIC["ctr() logic"]
1275
- LOGIC --> DISPATCH["dispatchResult() → dto sink"]
1276
- G -.->|"sadece oku/yaz flag"| LOGIC
1277
- ```
1278
-
1279
- | Veri | Nereye? | Örnek |
1280
- |------|---------|--------|
1281
- | `requestId`, correlation | **Run context** | `getRequestId()`, log, outbound header |
1282
- | `cookies`, `body`, `headers`, `builder` | **Controller context** | `this.req.cookies`, `this.res.builder` |
1283
- | Bakım modu, warmed cache, feature flag | **G** | `G.get('test')`, `G.set('maintenance', true)` |
1284
- | Servisler arası state | **Hiçbiri (G değil!)** | DB, Redis, message bus |
1285
-
1286
- **Patlamadan korunma — 4 kural:**
1287
-
1288
- 1. İstek verisini `G`'ye yazma — handler bitince kaybolması gereken her şey ALS'te kalır. `G.set('requestId'| 'cookies'| ...)` → runtime **warn** ( `warnOnRequestKeys: false` ile kapatılır).
1289
- 2. Handler dışında `this.req` / `getControllerCtx()` bekleme — `undefined` döner, bug değil.
1290
- 3. Realtime'da `protocol` açık ver — `ctr({ ... }, { protocol: 'ws' })`.
1291
- 4. Microservice'te her pod kendi `G`'sine sahip — cross-service state için Redis/DB kullan.
1292
-
1293
- `G.scope(GStoreScopeEnum.*)` → debug/observability; günlük iş mantığında zorunlu değil.
1294
-
1295
- **tmp.yml değişince:** `TmpFileLoader` izler → `System.applyTmp()` → runtime snapshot + `G` + loader'lar sırayla `syncFromTmp()` (`bindLoaderTmpSync(this)`).
1296
-
1297
- ---
1298
-
1299
- ## DI + tmp.yml — boot ve canlı güncelleme
1300
-
1301
- Tek kaynak: proje kökündeki **`x/tmp.yml`**. Loader'lar dosyayı doğrudan okumaz; **System** okur, snapshot'ı dağıtır.
1302
-
1303
- ```mermaid
1304
- sequenceDiagram
1305
- participant YML as x/tmp.yml
1306
- participant TFL as TmpFileLoader
1307
- participant SYS as System (DI)
1308
- participant RT as runtime snapshot
1309
- participant G as G store
1310
- participant L as Loaders
1311
-
1312
- YML->>TFL: watchFile (configs.core.tmp.fileWatchIntervalMs)
1313
- TFL->>SYS: reload event
1314
- SYS->>SYS: applyTmp(parsed)
1315
- SYS->>RT: setRuntimeTmpConfigs
1316
- SYS->>G: configureFromTmp
1317
- SYS->>L: notifyRuntimeTmpChange (sırayla)
1318
- Note over L: Configs → Kafka → Logger → …
1319
- L->>L: syncFromTmp()
1320
- ```
1321
-
1322
- ### Boot (Awilix DI)
1323
-
1324
- `source/project/index.ts`:
1325
-
1326
- ```typescript
1327
- const core = getCore() // tmp.yml oku (ilk snapshot)
1328
-
1329
- await x.initialize([
1330
- { service: System, props: { core } },
1331
- { service: Configs, props: { system } },
1332
- { service: KafkaForCore, props: { system, configs } },
1333
- { service: Logger, props: { system, configs, kafkaForCore } },
1334
- // … Events, Localizations, Dto, Controller, Clients
1335
- ])
1336
- ```
1337
-
1338
- **Sıra önemli:** `Configs` önce init olur → `Kafka`/`Logger` onun `configs.all`'ını kullanır.
1339
-
1340
- Her loader `onInit`:
1341
-
1342
- ```typescript
1343
- await this.syncFromTmp()
1344
- bindLoaderTmpSync(this)
1345
- ```
1346
-
1347
- ### tmp değişince ne olur?
1348
-
1349
- | Adım | Ne |
1350
- |------|-----|
1351
- | 1 | `tmp.yml` kaydedilir |
1352
- | 2 | `TmpFileLoader` değişikliği algılar |
1353
- | 3 | `System.applyTmp(yeniTmp)` |
1354
- | 4 | `getRuntimeTmpConfigs()` güncellenir — `getFramework()`, `getConfiguredProtocols()` bunu okur |
1355
- | 5 | `G.configureFromTmp` — `loaders.system.gStore.vars` |
1356
- | 6 | Her loader `syncFromTmp()` — winston, dto, i18n, kafka, … yeniden kurulur |
1357
-
1358
- **Eski tmp affedilmez** — her reload tam sync.
1359
-
1360
- ### Nereden import?
1361
-
1362
- Hepsi `@xrystal/core/utils` (veya loader içinden `../../utils`):
1363
-
1364
- ```typescript
1365
- import {
1366
- bindLoaderTmpSync,
1367
- getRuntimeTmpConfigs,
1368
- getConfiguredProtocols,
1369
- G,
1370
- GStoreScopeEnum,
1371
- type ITmpSyncLoader,
1372
- } from '@xrystal/core/utils'
1373
- ```
1374
-
1375
- Runtime helper'lar (`getFramework`, `getConfiguredProtocols`) **System'in yazdığı snapshot**'ı okur — dosyadan tekrar parse etmez.
1376
-
1377
- Uygulama kodunda tmp okumak için: `x.get<System>(System).tmp` veya `getRuntimeTmpConfigs()`.
1378
-
1379
- ---
1380
-
1381
- ## Three stores (by design)
1382
-
1383
- Üç ayrı depo — birbirinin yerine geçmez:
1384
-
1385
- | Store | Import | Lifetime | Ne için? |
1386
- |---|---|---|---|
1387
- | **Run context** | `getRequestId`, `runWithTrace` | İstek / job (ALS) | `requestId`, log correlation, outbound headers |
1388
- | **Controller context** | `this.req`, `this.store`, `builder` | İstek (ALS) | HTTP/socket handler anı — req, res, builder |
1389
- | **G** | `G`, `system.g` | Uygulama (store) | Düz prop'lar — System `onInit` tmp.yml'den bootstrap |
1390
-
1391
- ```
1392
- HTTP isteği gelir
1393
- → run context açılır (requestId)
1394
- → controller context açılır (req, res, builder)
1395
- → logic biter → ikisi kapanır
1396
-
1397
- G → process boyunca kalır (maintenance, warmed cache, …)
1398
- ```
1399
-
1400
- ### Run context (scoped trace)
1401
-
1402
- ```typescript
1403
- import { getRequestId, runWithTrace } from '@xrystal/core/utils'
1404
- ```
1405
-
1406
- - `ctr()` / `runAction()` / realtime handler otomatik açar
1407
- - Handler bitince kapanır — **global değil**
1408
- - Cron/queue: `runWithTrace('job-id', fn)`
1409
-
1410
- ```typescript
1411
- list = this.ctr({
1412
- logic: async () => {
1413
- this.logger.log(LoggerLayerEnum.INFO, 'listing')
1414
- return { data: [] }
1415
- },
1416
- })
1417
-
1418
- await runWithTrace('nightly-sync', async () => {
1419
- logger.log(LoggerLayerEnum.INFO, 'started')
1420
- }, 'sync-users')
1421
- ```
1422
-
1423
- ### Controller context (scoped handler)
1424
-
1425
- `runController()` `ControllerContext` yazar — controller içinde `this.req`, `this.store`, `builder`. Run context ile aynı istek; farklı veri.
1426
-
1427
- ### G — global store (Zustand)
1428
-
1429
- Düz property bag. **Tek kaynak:** proje kökündeki `x/tmp.yml`. System boot: `G.configureFromTmp(tmp)`.
1430
-
1431
- ```typescript
1432
- import { G } from '@xrystal/core/utils'
1433
-
1434
- G.set('maintenance', false)
1435
- G.get('test')
1436
- this.system.g.get('region')
1437
- ```
1438
-
1439
- | API | EN | TR |
1440
- |-----|----|----|
1441
- | `G.configureFromTmp(tmp)` | Boot from `system.gStore` (System loader) | tmp.yml → vars |
1442
- | `G.set(key, value)` | Set prop (runtime) | Prop yaz |
1443
- | `G.merge({ ... })` | Set many | Çoklu prop |
1444
- | `G.get(key, fallback?)` | Read prop | Oku |
1445
- | `G.subscribe(fn)` | `(state, prev, changes[])` | Değişen key'ler |
1446
- | `G.subscribeKey(key, fn)` | Single prop | Tek prop dinle |
1447
-
1448
- **tmp.yml:**
1449
-
1450
- ```yaml
1451
- configs:
1452
- loaders:
1453
- system:
1454
- gStore:
1455
- options:
1456
- bootstrap: true
1457
- autoCreateProps: false
1458
- vars:
1459
- test: false
1460
- ```
1461
-
1462
- → `G.get('test')` — sadece `vars` içindeki key'ler
1463
-
1464
- **Runtime — `autoCreateProps: false`:**
1465
-
1466
- ```typescript
1467
- G.set('test', true) // ok — tmp vars'da tanımlı
1468
- G.set('runtimeOnly', 1) // throws — tmp'de yok
1469
- ```
1470
-
1471
- **Runtime — `autoCreateProps: true`:**
1472
-
1473
- ```typescript
1474
- G.set('sessionCache', true) // ok — runtime key
1475
- ```
1476
-
1477
- **Scope enum — string karışmasın:**
1478
-
1479
- ```typescript
1480
- import { G, GStoreScopeEnum } from '@xrystal/core/utils'
1481
-
1482
- G.scope(GStoreScopeEnum.GLOBAL)
1483
- G.scope(GStoreScopeEnum.RUN)
1484
- G.scope(GStoreScopeEnum.CONTROLLER)
1485
- ```
1486
-
1487
- **Controller:**
1488
-
1489
- ```typescript
1490
- checks: () => G.get('test', false) ? { message: '@unsuccessful maintenance' } : true
1491
- ```
1492
-
1493
- **Subscribe:**
1494
-
1495
- ```typescript
1496
- G.subscribe((_state, _prev, changes) => {
1497
- for (const { key, value, prev } of changes) {
1498
- logger.log(LoggerLayerEnum.INFO, `G.${key}`, { value, prev })
1499
- }
1500
- })
1501
-
1502
- G.subscribeKey('test', (value, prev) => {
1503
- logger.log(LoggerLayerEnum.INFO, 'test', { value, prev })
1504
- })
1505
- ```
1506
-
1507
- **Üç store'u tek yerden gör:**
1508
-
1509
- ```typescript
1510
- G.list()
1511
-
1512
- G.scope('global').set?.('flag', 1)
1513
- G.scope('run').get('requestId')
1514
- G.scope('run').patch?.({ meta: { source: 'cron' } })
1515
- G.scope('controller').patch?.({ metadata: { locals: { userId: 1 } } } })
1516
- ```
1517
-
1518
- | Store | Aktif ne zaman | Manipülasyon |
1519
- |-------|----------------|--------------|
1520
- | `global` | Her zaman | `set`, `merge` |
1521
- | `run` | İstek / job içinde | `patch` (meta, label) |
1522
- | `controller` | Handler içinde | `patch` (metadata.locals) |
1523
-
1524
- ### App responsibility (keep it simple)
1525
-
1526
- 1. **`tmp.yml`** — `framework: elysia` (veya express, fetch, …)
1527
- 2. **`app.use(dtoMiddleware())`** bir kez
1528
- 3. Process-wide bag gerekiyorsa **`G`** — per-request trace için değil
1529
-
1530
- ---
1531
-
1532
- ## Request ID (trace)
1533
-
1534
- One id per request — from **run context** (not `G`).
1535
-
1536
- ```
1537
- Incoming header (x-request-id / x-correlation-id)
1538
- ↓
1539
- dto adapter middleware → req.ctx.requestId
1540
- ↓
1541
- ensureRequestId() → run context requestId
1542
- ↓
1543
- runWithRequestId(id, fn)
1544
- ↓
1545
- req.requestId → controller context
1546
- logger.log() → LogDTO.id
1547
- Clients outbound → x-correlation-id
1548
- ```
1549
-
1550
- | Case | Behaviour |
1551
- |---|---|
1552
- | Header present | That value is used |
1553
- | No header | UUID generated automatically |
1554
- | Cron / queue / script | `runWithTrace('job-42', () => { ... })` |
1555
-
1556
- ```typescript
1557
- import { runWithTrace } from '@xrystal/core/utils'
1558
-
1559
- await runWithTrace('nightly-sync', async () => {
1560
- logger.log(LoggerLayerEnum.INFO, 'job started')
1561
- })
1562
- ```
1563
-
1564
- ---
1565
-
1566
- ## @xrystal/dto migration (v26.6.28+)
1567
-
1568
- Removed from dto — use core instead:
1569
-
1570
- | Removed (dto) | Replacement (core) |
1571
- |---|---|
1572
- | `runtime.middleware()` | `dtoMiddleware()` |
1573
- | `runtime.middleware('express')` | `dtoMiddleware('express')` |
1574
- | `normalizeRuntimeKind()` | `normalizeFrameworkKind()` |
1575
-
1576
- ```typescript
1577
- app.use(runtime.express())
1578
-
1579
- import { dtoMiddleware } from '@xrystal/core/utils'
1580
- app.use(dtoMiddleware())
1581
- app.use(dtoMiddleware('socketio'))
1582
- ```
1583
-
1584
- Mapping lives in `utils/helpers/middleware/` — `socketio` → `socketIo()`, `websocket` → `websocket()`.
1585
-
1586
- ---
1587
-
1588
- ## CLI (`xcore` · `xrystal` · `tmp`)
1589
-
1590
- **EN:** Installing `@xrystal/core` exposes **three bin names** for the same CLI (`x/bin/main-cli.js`) — same commands, same project-root resolution.
1591
-
1592
- **TR:** `@xrystal/core` kurulunca **üç bin adı** aynı CLI’yı açar — aynı komutlar, aynı proje kökü çözümlemesi.
1593
-
1594
- | Bin | EN | TR | Example |
1595
- |-----|----|----|---------|
1596
- | **`xcore`** | Primary name (recommended) | Ana isim (önerilen) | `xcore doctor`, `npx xcore dev` |
1597
- | **`xrystal`** | Transition alias | Geçiş alias | `xrystal version` = `xcore version` |
1598
- | **`tmp`** | Legacy alias | Eski alışkanlık alias | `tmp tag` = `xcore tag` |
1599
-
1600
- **EN:** Any bin name resolves project root, git, version/tag, and `dev`/`build`/`test` through the **same code path**. Banner shows the bin you invoked.
1601
-
1602
- **TR:** Hangi bin adını yazarsan yaz: proje kökü, git, version/tag, dev/build/test **aynı kod yolu**. Banner çağırdığın bin adını gösterir.
1603
-
1604
- **EN:** Works in every service repo with `@xrystal/core` — no global install. From a subfolder (`src/`, `x/`, …) the CLI walks up to the `package.json` that depends on `@xrystal/core`; git / version / tag stay on **that service root**.
1605
-
1606
- **TR:** `@xrystal/core` dependency’si olan her serviste doğrudan kullanılır — global kurulum gerekmez. Alt klasörden çalıştırsan bile CLI yukarı çıkar; git / version / tag **o servisin** kökünde kalır.
1607
-
1608
- ```bash
1609
- cd api-gateway-svc/src
1610
-
1611
- npx xcore doctor # → api-gateway-svc/package.json
1612
- npx xrystal version # aynı
1613
- npx tmp tag # aynı — servis tag + push
1614
- ```
1615
-
1616
- **EN:** Any bin alias in service `package.json` scripts — same behavior.
1617
-
1618
- **TR:** Servis `package.json` script’lerinde herhangi bir alias kullanılabilir; davranış değişmez.
1619
-
1620
- ```json
1621
- {
1622
- "scripts": {
1623
- "dev": "xcore dev",
1624
- "doctor": "xrystal doctor",
1625
- "release:tag": "tmp tag"
1626
- }
1627
- }
1628
- ```
1629
-
1630
- ---
1631
-
1632
- ### Three script layers / Üç script katmanı
1633
-
1634
- | Layer / Katman | Defined in / Tanım | When / Ne zaman | Example / Örnek |
1635
- |----------------|-------------------|-----------------|-----------------|
1636
- | **CLI (shared)** | `@xrystal/core` bin (`xcore` / `xrystal` / `tmp`) | Same in all services / Tüm servislerde aynı | `xcore dev`, `tmp version`, `xrystal tag` |
1637
- | **Project (service)** | Service `package.json` → `scripts` | Service-specific; `xcore build` delegates if custom / Servise özel; özel build varsa delegate | `"build": "bun build src/boot.ts"` |
1638
- | **Lib (core repo)** | `@xrystal/core` own `package.json` | Core dev / publish only / Sadece core geliştirme | `"release:prepare"`, `"tag"` |
1639
-
1640
- **EN — shared CLI commands** (`<bin>` = `xcore` | `xrystal` | `tmp`; cwd = project root):
1641
-
1642
- | Command | What it does |
1643
- |---------|----------------|
1644
- | `<bin> version` | CLI version + project `package.json` ↔ git HEAD |
1645
- | `<bin> tag` | `v{version}` tag + push from **project** version |
1646
- | `<bin> doctor` | Runtimes, git, installed `@xrystal/core` vs CLI |
1647
- | `<bin> test` | `bun test ./{rootFolderPath}/{paths.tests}` |
1648
- | `<bin> dev` | Watch `{service.folderPath}/index.ts` + dev env |
1649
- | `<bin> build` | Output → `{rootFolderPath}/{paths.dist}/` |
1650
- | `<bin> start` | Run `{rootFolderPath}/{paths.dist}/index.js` + prod env |
1651
- | `<bin> tmp` | Ensure `tmp.yml` from seed if missing |
1652
- | `<bin> create [name] [path]` | GitHub template clone + `tmp.yml` ensure |
1653
-
1654
- **TR — ortak CLI komutlar** (`<bin>` = `xcore` | `xrystal` | `tmp`; cwd = proje kökü):
1655
-
1656
- | Komut | Ne yapar |
1657
- |-------|----------|
1658
- | `<bin> version` | CLI sürümü + **proje** `package.json` ↔ git HEAD |
1659
- | `<bin> tag` | **Proje** versiyonundan `v{version}` tag + push |
1660
- | `<bin> doctor` | runtime, git, kurulu `@xrystal/core` vs CLI |
1661
- | `<bin> test` | `bun test ./{rootFolderPath}/{paths.tests}` |
1662
- | `<bin> dev` | `{service.folderPath}/index.ts` watch + dev env |
1663
- | `<bin> build` | Çıktı → `{rootFolderPath}/{paths.dist}/` |
1664
- | `<bin> start` | `{rootFolderPath}/{paths.dist}/index.js` + prod env |
1665
- | `<bin> tmp` | `tmp.yml` yoksa seed’den oluşturur |
1666
- | `<bin> create [name] [path]` | GitHub template + `tmp.yml` ensure |
1667
-
1668
- **EN:** If `tmp.yml` is missing, `xcore tmp` / `dev` / `test` / `build` copy seed from `@xrystal/core/x/tmp.yml` into `{rootFolderPath}/tmp.yml`.
1669
-
1670
- **TR:** `tmp.yml` silinmişse `xcore tmp` / `dev` / `test` / `build`, seed `@xrystal/core/x/tmp.yml` dosyasından `{rootFolderPath}/tmp.yml` oluşturur.
1671
-
1672
- **EN — core repo guard:** In `@xrystal/core` repo, `tmp.yml` must be only `x/tmp.yml`; stray copies fail boot/CLI. Services have no such rule.
1673
-
1674
- **TR — core koruması:** `@xrystal/core` repo’sunda `tmp.yml` yalnızca `x/tmp.yml`; başka kopya hata verir. Servislerde bu kural yok.
1675
-
1676
- ```bash
1677
- xcore tmp # ensure tmp.yml
1678
- xcore create example ./ # GitHub template + tmp ensure
1679
- tmp dev # bin alias = xcore dev
1680
- ```
1681
-
1682
- **EN:** `configs` in `tmp.yml`: `service.*` + `core.*` — single source per service. Core package default: `service.paths.root: x`.
1683
-
1684
- **TR:** `tmp.yml` içinde `configs`: `service.*` + `core.*` — servis tek kaynak. Core pakette default `service.paths.root: x`.
1685
-
1686
- **EN — recommended service `package.json` wiring** (bind shared CLI commands; keep service-specific scripts separate):
1687
-
1688
- **TR — önerilen servis `package.json` wiring** (ortak komutları script’e bağla; servise özel olanları ayrı tut):
1689
-
1690
- ```json
1691
- {
1692
- "name": "api-gateway-svc",
1693
- "version": "26.06.27-v1",
1694
- "dependencies": {
1695
- "@xrystal/core": "^3.34.0"
1696
- },
1697
- "scripts": {
1698
- "dev": "xcore dev",
1699
- "build": "xcore build",
1700
- "start:dist": "xcore start",
1701
- "test": "xcore test",
1702
- "lint": "eslint .",
1703
- "sync-toolchain": "xcore sync-toolchain",
1704
- "doctor": "xcore doctor",
1705
- "version:check": "xcore version",
1706
- "release:tag": "xcore tag",
1707
- "start": "bun --env-file=./x/environments/.prod.env x/dist/index.js"
1708
- }
1709
- }
1710
- ```
1711
-
1712
- **EN — toolchain files (service)**
1713
-
1714
- **TR — toolchain dosyaları (servis)**
1715
-
1716
- | File / Dosya | Required? / Zorunlu? | Note / Not |
1717
- |--------------|----------------------|------------|
1718
- | `{rootFolderPath}/tmp.yml` | Yes / Evet | Folder names here / Klasör adları burada |
1719
- | `tsconfig.json` | Yes / Evet | Updated by `sync-toolchain` |
1720
- | `eslint.config.js` | Recommended / Önerilir | Reads tmp — [example](#toolchain--klasör-adları-tmpyml-kurallar-tsconfigbasejson) |
1721
- | `bunfig.toml` | Bun test/dev | `@/*` alias from sync output |
1722
-
1723
- **EN — from service root:**
1724
-
1725
- **TR — servis kökünden:**
1726
-
1727
- ```bash
1728
- bun run dev # = xcore dev
1729
- bun run version:check # = xcore version → api-gateway-svc version, git HEAD
1730
- bun run release:tag # = xcore tag → servis tag’i, core değil
1731
- bun run doctor # CLI vs node_modules @xrystal/core uyumu
1732
- bun run sync-toolchain # sadece layout değişince (aşağıya bak)
1733
- ```
1734
-
1735
- **EN — dev vs prod entry**
1736
-
1737
- | Command | Runs | Path |
1738
- |---------|------|------|
1739
- | `xcore dev` | TypeScript source | `{service.folderPath}/index.ts` |
1740
- | `xcore build` | Compiles to dist | `{rootFolderPath}/{paths.dist}/` |
1741
- | `xcore start` | Production JS | `{rootFolderPath}/{paths.dist}/index.js` |
1742
-
1743
- **TR — dev vs prod giriş**
1744
-
1745
- | Komut | Çalıştırır | Yol |
1746
- |-------|------------|-----|
1747
- | `xcore dev` | TypeScript kaynak | `{service.folderPath}/index.ts` |
1748
- | `xcore build` | Derler | `{rootFolderPath}/{paths.dist}/` |
1749
- | `xcore start` | Prod JS | `{rootFolderPath}/{paths.dist}/index.js` |
1750
-
1751
- **EN — service build:** `tsconfig.json` is primary (`include`, `outDir`, `rootDir`, `sourceMap`, `paths`, `strict`). `tmp.yml` `build.*` = explicit overrides only. `tmp.yml` runtime = loaders, protocols, `rootFolderPath`.
1752
-
1753
- **TR — servis build:** `tsconfig.json` birincil. `tmp.yml` `build.*` = yalnızca override. `tmp.yml` runtime = loaders, protocols, `rootFolderPath`.
1754
-
1755
- | File / Dosya | EN | TR |
1756
- |--------------|----|----|
1757
- | `tsconfig.json` | `include`→glob, `outDir`→dist, `sourceMap`, `paths`, `strict`, `typecheck` via `--noEmit` | `include`→glob, `outDir`→dist, `sourceMap`, `paths`, `strict`, `typecheck` için `--noEmit` |
1758
- | `tmp.yml` `build.*` | Override: `typecheck`, `glob`, `entries`, `outDir`, `sourcemap`, `declarations`, `minify` | Override: `typecheck`, `glob`, `entries`, `outDir`, `sourcemap`, `declarations`, `minify` |
1759
- | `tmp.yml` `paths.*` | Runtime (test, env); dist fallback if no `outDir` | Runtime (test, env); `outDir` yoksa dist fallback |
1760
-
1761
- | `configs.build` (override) | tsconfig karşılığı | Ne yapar |
1762
- |-----------------------------|-------------------|----------|
1763
- | `outDir` | `compilerOptions.outDir` | Çıktı klasörü — **tsconfig'te `./x/dist` yaz, tmp'de tekrarlama** |
1764
- | `glob` / `entries` | `include` / `rootDir` | Hangi `.ts` derlenecek |
1765
- | `sourcemap` | `sourceMap` / `inlineSourceMap` | Harita (default kapalı) |
1766
- | `declarations` | `declaration` / `emitDeclarationOnly` | `.d.ts` üret |
1767
- | `minify` | — (core build) | `tsc` sonrası `minify-dist.mjs` (tmp `build.minify: true`) |
1768
- | `typecheck` | — (tsconfig kuralları okunur) | `tsc --noEmit` build öncesi |
1769
- | `tsconfig` | dosya yolu | `tsconfig.build.json` vb. |
1770
- | `tscLenient` | — | Sadece `declarations: true` + tsc hatalarını yoksay |
1771
-
1772
- **EN — priority:** tmp.yml explicit > tsconfig.json > tmp layout fallback
1773
-
1774
- **TR — öncelik:** tmp.yml explicit > tsconfig.json > tmp layout fallback
1775
-
1776
- ```yaml
1777
- configs:
1778
- file:
1779
- rootFolderPath: x
1780
-
1781
- service:
1782
- folderPath: ./source
1783
- build:
1784
- typecheck: true # tek satır yeter — outDir/include tsconfig'te
1785
- ```
1786
-
1787
- ```json
1788
- // tsconfig.json — servis/lib ortak model
1789
- {
1790
- "include": ["source"],
1791
- "compilerOptions": {
1792
- "rootDir": "./source",
1793
- "outDir": "./x/dist",
1794
- "sourceMap": false,
1795
- "declaration": false,
1796
- "strict": true,
1797
- "paths": { "@/*": ["source/*"] }
1798
- }
1799
- }
1800
- ```
1801
-
1802
- **EN — build order (service):** `typecheck?` → `rm dist` → `bun build .ts` → `declarations?`
1803
-
1804
- **TR — build sırası (servis):** `typecheck?` → `rm dist` → `bun build .ts` → `declarations?`
1805
-
1806
- **EN — build order (@xrystal/core lib):** `rm x/dist` → `tsc` (JS + `.d.ts`) → `tsc-alias` → `fix-dist-imports` → `minify-dist?` (`build.minify`)
1807
-
1808
- **TR — build sırası (@xrystal/core lib):** `rm x/dist` → `tsc` → `tsc-alias` → `fix-dist-imports` → `minify-dist?` (`build.minify`)
1809
-
1810
- **EN:** `prepublishOnly` = `release:prepare` + `verify-publish-config`. See [npm publish](#npm-publish--npm-yayın).
1811
-
1812
- **TR:** `prepublishOnly` = `release:prepare` + `verify-publish-config`. Bkz. [npm publish](#npm-publish--npm-yayın).
1813
-
1814
- ```bash
1815
- xcore build
1816
- xcore start # bun x/dist/index.js (+ .global.env / .prod.env if present)
1817
- ```
1818
-
1819
- **Build output / derleme çıktısı**
1820
-
1821
- | Layer | Path | Role |
1822
- |-------|------|------|
1823
- | Source (dev) | `{service.folderPath}/**/*.ts` | `xcore dev` runs TS directly |
1824
- | Prod runtime | `tsconfig outDir` → `.js` | `xcore start`, Docker |
1825
- | Source map | `{outDir}/**/*.js.map` | tsconfig `sourceMap` veya tmp `build.sourcemap` |
1826
- | Declarations | `{outDir}/**/*.d.ts` | tsconfig `emitDeclarationOnly` veya tmp `build.declarations` |
1827
-
1828
- **EN:** Put `include`, `outDir`, `sourceMap`, `paths`, `strict` in `tsconfig.json`. tmp.yml `build.*` only when you need an override (e.g. `typecheck: true`).
1829
-
1830
- **TR:** `include`, `outDir`, `sourceMap`, `paths`, `strict` → `tsconfig.json`. tmp.yml `build.*` sadece override için (ör. `typecheck: true`).
1831
-
1832
- **Loop fix / döngü fix:** `"build": "xcore build"` no longer delegates to itself — default build runs.
1833
-
1834
- **`xcore build` priority / öncelik:**
1835
-
1836
- 1. **EN:** Custom `scripts.build` (not `xcore build`) → `bun run build`
1837
- **TR:** Özel `scripts.build` (xcore build değilse) → delegate
1838
- 2. **EN:** Else: read `tsconfig.json` (include/outDir/sourceMap) + tmp.yml overrides
1839
- **TR:** Aksi halde tsconfig okunur + tmp.yml override
1840
-
1841
- **Lib scripts / Lib script’leri** (`@xrystal/core` repo — developer / geliştirici):
1842
-
1843
- | Script | EN | TR |
1844
- |--------|----|----|
1845
- | `npm run dev` | Core source watch | Core kaynak watch |
1846
- | `npm run build` | `tsc` → alias → fix-dist-imports (+ minify) | `tsc` tam emit → Node ESM import düzeltme |
1847
- | `npm run release:prepare` | lint → build → test (no git write) | lint → build → test (git’e yazmaz) |
1848
- | `xcore hooks install` | Install pre-commit into `.git/hooks` (core + services) | `.git/hooks` pre-commit (core + servis) |
1849
- | `npm run tag` / `xcore tag` | prepare + git tag + push | prepare + tag + push |
1850
- | `npm publish` | GitHub Actions on tag (`--ignore-scripts`) | Tag’de CI publish eder |
1851
-
1852
- **`xcore tag` flow / akışı (@xrystal/core):**
1853
-
1854
- 1. **EN:** Commit `package.json` version bump first.
1855
- **TR:** Önce `package.json` version commit edilmeli.
1856
- 2. **EN:** `lint` → `build` → `test` (TypeScript stays in git; runtime in `x/dist`).
1857
- **TR:** `lint` → `build` → `test` (git’te `.ts` kalır; runtime `x/dist`’te).
1858
- 3. **EN:** `git tag vX.Y.Z` + push → GitHub Actions publishes to npm.
1859
- **TR:** Tag + push → CI npm’e publish eder.
1860
-
1861
- **EN:** Never commit `.js` under `source/`. Publish uses minified `x/dist` only — [npm publish](#npm-publish--npm-yayın).
1862
-
1863
- **TR:** `source/` altına `.js` commit etme. Publish yalnızca minify `x/dist` — [npm publish](#npm-publish--npm-yayın).
1864
-
1865
- **EN:** Service `npm run tag` does not publish `@xrystal/core` — use `xcore tag` or `"release:tag": "xcore tag"` on the **service** repo.
1866
-
1867
- **TR:** Serviste `npm run tag` **@xrystal/core** publish etmez — servis repo’sunda `xcore tag` veya `"release:tag": "xcore tag"` kullan.
1868
-
1869
- ---
1870
-
1871
- ### Version bump + `hooks:install` — when / ne zaman?
1872
-
1873
- **EN — what does it do?**
1874
- `xcore hooks install` writes `pre-commit` into `.git/hooks/pre-commit` (local git dir, not committed to the repo). After that, every **`git commit`** runs a **pre-commit** check: if you staged a **`package.json` version change**, the new version must be **strictly greater** than the old one (`3.35.0` → `3.35.1` ✅ · `3.35.0` → `3.35.0` ❌). Commits that do not change `version` are not blocked.
1875
-
1876
- **TR — ne yapar?**
1877
- `xcore hooks install` `.git/hooks/pre-commit` dosyasını yazar (repo'ya commit edilmez, sadece senin makinede). Sonrasında **`git commit`** atarken: **`package.json` içindeki `version` değiştiyse**, yeni sürüm eskisinden **büyük** olmalı. Sadece kod değişikliği commit'lerinde version aynı kalabilir.
1878
-
1879
- **EN — when do I run it?**
1880
-
1881
- | Situation | Run `hooks:install`? |
1882
- |-----------|----------------------|
1883
- | First clone of **`-xrystal-core`** on this machine | **Yes — once** |
1884
- | Commits never block same/lower version bumps | **Yes — once** |
1885
- | After `bun install` in core repo | Run once after clone |
1886
- | Before every commit or tag | **No** |
1887
- | **Service repo** (only uses `@xrystal/core`) | **Yes — once** |
1888
- | **`xcore create`** scaffolded a new service | **Auto** — hook + `hooks:install` script |
1889
-
1890
- **TR — ne zaman çalıştırırım?**
1891
-
1892
- | Durum | `hooks:install`? |
1893
- |-------|------------------|
1894
- | **`-xrystal-core`** reposunu bu makinede ilk kez clone'ladım | **Evet — bir kez** |
1895
- | Commit atınca version kontrolü hiç çalışmıyor | **Evet — bir kez** |
1896
- | Core repo'da `bun install` sonrası | Clone sonrası bir kez |
1897
- | Her commit / tag öncesi | **Hayır** |
1898
- | Sadece servis reposu | **Evet — bir kez** |
1899
- | **`xcore create`** ile yeni servis oluşturdum | **Otomatik** — hook + `hooks:install` script |
1900
-
1901
- ```bash
1902
- # @xrystal/core repo — first time on this machine / bu makinede ilk kez
1903
- cd -xrystal-core
1904
- xcore hooks install # core repo or service repo
1905
- # core repo only: bun run hooks:install
1906
- ```
1907
-
1908
- **EN — two layers of protection**
1909
-
1910
- | Layer | When | Rule |
1911
- |-------|------|------|
1912
- | **pre-commit hook** | `git commit` (if hook installed) | Staged `version` > HEAD `version` |
1913
- | **`xcore tag`** | Before tag + push | Committed `version` > latest git tag |
1914
-
1915
- **TR — iki katman**
1916
-
1917
- | Katman | Ne zaman | Kural |
1918
- |--------|----------|-------|
1919
- | **pre-commit hook** | `git commit` (hook kuruluysa) | Stage'deki `version` > HEAD'teki `version` |
1920
- | **`xcore tag`** | Tag + push öncesi | Commit'teki `version` > son git tag |
1921
-
1922
- **EN — typical release (core maintainer)**
1923
-
1924
- ```bash
1925
- # 1. Bump package.json version (e.g. 3.35.0 → 3.35.1)
1926
- git add package.json
1927
- git commit -m "chore: release 3.35.1" # hook blocks same/lower version
1928
-
1929
- xcore tag # lint + test + build + version check again
1930
- ```
1931
-
1932
- **TR — tipik release**
1933
-
1934
- ```bash
1935
- # 1. package.json version artır (ör. 3.35.0 → 3.35.1)
1936
- git add package.json
1937
- git commit -m "chore: release 3.35.1" # hook aynı/düşük version'u reddeder
1938
-
1939
- xcore tag # lint + test + build + version tekrar kontrol
1940
- ```
1941
-
1942
- **EN:** `xcore doctor` / `xcore version` show `latest tag` and `bump vs latest tag`.
1943
- **TR:** `xcore doctor` / `xcore version` → `latest tag` ve bump durumu.
1944
-
1945
- **EN:** Hook not installed? Commits still work — **`xcore tag`** enforces the bump at release.
1946
- **TR:** Hook kurulu değilse commit olur — release'te **`xcore tag`** yine kontrol eder.
1947
-
1948
-
1949
-
1950
- ---
1951
-
1952
- ### `doctor` — iki sürüm
1953
-
1954
- `xcore doctor` ayrıca **Runtimes (PATH)** ve **Node version managers** envanterini listeler (`node`, `bun`, `npm`, `fnm`, `nvm`, …) — hangi binary’nin aktif olduğunu gösterir.
1955
-
1956
- | Alan | Anlam |
1957
- |------|--------|
1958
- | **CLI (tool)** | Çalışan `xcore` binary’sinin `@xrystal/core` sürümü |
1959
- | **Project (service)** | `api-gateway-svc@1.x` — servisin kendi `package.json` `version` |
1960
- | **node_modules** | Kurulu `@xrystal/core` — CLI ile eşleşiyor mu |
1961
- | **Toolchain** | `defaults.json` → önerilen `outDir` / `include` / eslint — `tsconfig.json` uyumu |
1962
-
1963
- ---
1964
-
1965
- ### npm + Node (Express gibi — framework/runtime bağımsız)
1966
-
1967
- **Runtime:** Tüketici projede `import … from '@xrystal/core'` → **Node.js ESM** (Express/Fastify/Elysia fark etmez). Publish sonrası paket `.js` + `.d.ts` içerir; uygulama çalıştırmak için Bun şart değil.
1968
-
1969
- **Tooling:** `xcore` CLI (dev, build, test) geliştirme aracıdır — repo içinde Bun kullanır. npm’e yüklenen kütüphane Bun’a bağımlı değildir.
1970
-
1971
- | Katman | Bun gerekli mi? | Ne yapar |
1972
- |--------|-----------------|----------|
1973
- | `import '@xrystal/core'` | Hayır (Node) | Lib runtime |
1974
- | `xcore dev` / `build` | Evet (CLI) | Proje geliştirme |
1975
- | Docker prod `node x/dist/index.js` | Hayır | Servis prod |
1976
-
1977
- ---
1978
-
1979
- ### Toolchain — klasör adları `tmp.yml`, kurallar `tsconfig.base.json`
1980
-
1981
- **Sorun:** `tsconfig` / `eslint` içinde `x`, `source` hardcode → serviste `infra`, `src` olunca kırılır.
1982
-
1983
- **Çözüm:** Klasör yolları **yalnızca `tmp.yml`**; tsconfig path alanları **sync** ile yazılır:
1984
-
1985
- ```yaml
1986
- configs:
1987
- file:
1988
- rootFolderPath: infra # x yerine
1989
- service:
1990
- folderPath: ./src
1991
- paths:
1992
- dist: dist
1993
- ```
1994
-
1995
- ```bash
1996
- xcore sync-toolchain # tsconfig include / outDir / @/* ← tmp.yml
1997
- xcore doctor # drift var mı
1998
- ```
1999
-
2000
- | Dosya | Klasör adı var mı? | Rol |
2001
- |-------|-------------------|-----|
2002
- | `tmp.yml` | **Evet — tek kaynak** | `service.paths.root`, `service.paths.source`, `service.paths.*` |
2003
- | `tsconfig.base.json` | Hayır | `strict`, `module`, `target` (npm export) |
2004
- | `tsconfig.json` | Sync ile | `include`, `outDir`, `paths` — elle yazma |
2005
- | `eslint.config.js` | tmp'den okur | `createEslintConfigFromProject(cwd)` |
2006
-
2007
- **Servis eslint.config.js:**
2008
-
2009
- ```js
2010
- import tseslint from 'typescript-eslint'
2011
- import { createEslintConfigFromProject } from '@xrystal/core/x/bin/helpers/toolchain-config.mjs'
2012
-
2013
- export default createEslintConfigFromProject(process.cwd(), tseslint)
2014
- ```
2015
-
2016
- ---
2017
-
2018
- ### Servislerde `sync-toolchain` (manuel)
2019
-
2020
- **Evet — servislerde de öneriyoruz.** Otomatik değil; **sen çalıştırırsın**, sadece **klasör/layout** değişince.
2021
-
2022
- | tmp.yml değişikliği | `sync-toolchain` gerekir mi? |
2023
- |---------------------|------------------------------|
2024
- | `service.paths.root` (`x` → `infra`) | **Evet** |
2025
- | `service.paths.source` (`./source` → `./src`) | **Evet** |
2026
- | `service.paths.dist` / `service.paths.tests` | **Evet** |
2027
- | `loaders`, `logLevel`, `protocols` | **Hayır** — runtime watch yeterli |
2028
-
2029
- **Ne yapar:** `tmp.yml` layout → `tsconfig.json` (`include`, `outDir`, `@/*`, `extends: @xrystal/core/tsconfig.base.json`).
2030
- **Ne yapmaz:** eslint dosyasını yazmaz — eslint her `lint`/`dev` öncesi tmp'yi okur. `bunfig.toml` satırını **çıktıda gösterir**, sen eklersin.
2031
-
2032
- **Servis akışı:**
2033
-
2034
- ```bash
2035
- # 1) Yeni servis veya template clone sonrası — tmp.yml layout'u düzenle
2036
- # 2) Bir kez sync
2037
- bun run sync-toolchain
2038
- # 3) Kontrol
2039
- bun run doctor
2040
- # 4) bunfig.toml — sync'in yazdığı alias satırını ekle
2041
- ```
2042
-
2043
- **package.json script (servislere ekle):**
2044
-
2045
- ```json
2046
- "sync-toolchain": "xcore sync-toolchain",
2047
- "lint": "eslint ."
2048
- ```
2049
-
2050
- **Dry-run:** `xcore sync-toolchain --dry-run` — yazmadan ne üreteceğini gösterir.
2051
-
2052
- Runtime (`xcore dev` çalışırken) loader ayarları tmp watch ile güncellenir; **sync-toolchain buna karışmaz** — bilinçli ayrım.
2053
-
2054
- ---
2055
-
2056
- ### `x/` folder layout / `x/` klasörü (configured via tmp.yml)
2057
-
2058
- **EN:** The `@xrystal/core` npm package ships seed `x/tmp.yml` (default `configs.file.rootFolderPath: x`). **Services** read layout from their own `tmp.yml` → `configs`; folder names are configurable.
2059
-
2060
- **TR:** `@xrystal/core` paketi seed `x/tmp.yml` taşır (default `configs.file.rootFolderPath: x`). **Servisler** kendi `tmp.yml` → `configs` ayarlarından layout okur; klasör adları değiştirilebilir.
2061
-
2062
- ```yaml
2063
- # configs = proje ayarları (servis tek kaynak)
2064
- configs:
2065
- file:
2066
- rootFolderPath: x # serviste infra, config, … olabilir
2067
-
2068
- service:
2069
- name: my-api
2070
- folderPath: ./source
2071
- paths:
2072
- tests: tests
2073
- environments: environments
2074
- dist: dist
2075
- build:
2076
- typecheck: true
2077
- ```
2078
-
2079
- Seed / ensure source: `node_modules/@xrystal/core/x/tmp.yml` (no separate template file / ayrı template yok).
2080
-
2081
- | `configs` field / alan | EN | TR |
2082
- |------------------------|----|----|
2083
- | `service.paths.root` | CLI root folder (`xcore test`/`dev`/`build`) | CLI kök klasörü (`xcore test`/`dev`/`build`) |
2084
- | `core.tmp.fileWatchIntervalMs` | `tmp.yml` watch interval (ms, default `500`) | `tmp.yml` izleme aralığı (ms, default `500`) |
2085
- | `service.paths.source` | Source tree + `xcore dev` entry | Kaynak klasörü + `xcore dev` girişi |
2086
- | `service.paths.*` | `tests` / `environments` / `dist` subpaths | `tests` / `environments` / `dist` alt yolları |
2087
- | `service.loaders`, `service.framework` | Runtime (System, dto, logger, …) | Runtime (System, dto, logger, …) |
2088
- | `service.build.*` | Build override (`typecheck`, …) — tsconfig is primary | Build override — tsconfig birincil |
2089
-
2090
- **EN:** In services, `tmp.yml` is found recursively; in the core repo only `x/tmp.yml` is allowed.
2091
-
2092
- **TR:** Servislerde `tmp.yml` recursive bulunur; core repo’da yalnızca `x/tmp.yml` kabul edilir.
2093
-
2094
- ```
2095
- {rootFolderPath}/
2096
- ├── tmp.yml
2097
- ├── tests/
2098
- ├── environments/
2099
- └── dist/
2100
- ```
2101
-
2102
- | Repo | `{rootFolderPath}/tests` |
2103
- |------|--------------------------|
2104
- | **@xrystal/core** | EN: lib unit/integration tests · TR: lib unit/integration testleri |
2105
- | **Service / Servis** | EN: service tests · TR: servis testleri |
2106
-
2107
- **EN:** `xcore test` = `bun test ./{rootFolderPath}/{paths.tests}`.
2108
-
2109
- **TR:** `xcore test` = `bun test ./{rootFolderPath}/{paths.tests}`.
2110
-
2111
- ---
2112
-
2113
- ## Kullanım örnekleri (sıralı — kopyala-yapıştır)
2114
-
2115
- ### 1) tmp.yml
2116
-
2117
- ```yaml
2118
- configs:
2119
- framework: elysia
2120
- service: my-api
2121
- protocols: [http, ws]
2122
- loaders:
2123
- dto: { withDefaultHeaders: true }
2124
- localization: { fallbackLang: en, preloadLangs: [en, tr] }
2125
- loggers: { logLevel: debug }
2126
- controller: {}
2127
- ```
2128
-
2129
- ### 2) Controller + ctr (HTTP)
2130
-
2131
- ```typescript
2132
- import Controller from '@xrystal/core/loader/controller'
2133
-
2134
- class UserController extends Controller {
2135
- list = this.ctr({
2136
- logic: async ({ req }) => ({ data: [] }),
2137
- })
2138
- create = this.ctr({
2139
- logic: async ({ req }) => ({ data: req.body }),
2140
- })
2141
- }
2142
-
2143
- const userCtrl = new UserController()
2144
- ```
2145
-
2146
- ### 3) Elysia HTTP (default)
401
+ ### Elysia — end-to-end / uçtan uca
2147
402
 
2148
403
  ```typescript
404
+ // source/index.ts
2149
405
  import { Elysia } from 'elysia'
406
+ import coreLoader from '@xrystal/core'
2150
407
  import { dtoMiddleware } from '@xrystal/core/utils'
408
+ import { userCtrl } from './controllers/user'
409
+
410
+ await coreLoader({})
2151
411
 
2152
412
  new Elysia()
2153
413
  .use(dtoMiddleware())
2154
414
  .get('/users', userCtrl.list)
2155
- .post('/users', userCtrl.create)
2156
- ```
2157
-
2158
- ### 4) Express HTTP
2159
-
2160
- ```typescript
2161
- import express from 'express'
2162
- import { dtoMiddleware } from '@xrystal/core/utils'
2163
-
2164
- const app = express()
2165
- app.use(dtoMiddleware('express'))
2166
- app.get('/users', userCtrl.list)
2167
- ```
2168
-
2169
- ### 5) Fetch / Bun.serve
2170
-
2171
- `tmp.yml` → `framework: fetch`
2172
-
2173
- ```typescript
2174
- import { dtoMiddleware } from '@xrystal/core/utils'
2175
-
2176
- Bun.serve({
2177
- fetch: (req) => userCtrl.list(req),
2178
- })
2179
- ```
2180
-
2181
- ### 6) Node http
2182
-
2183
- `tmp.yml` → `framework: node`
2184
-
2185
- ```typescript
2186
- import http from 'node:http'
2187
-
2188
- http.createServer((req, res) => userCtrl.list(req, res)).listen(3000)
2189
- ```
2190
-
2191
- ### 7) i18n + HTTP
2192
-
2193
- ```typescript
2194
- app.use(i18nextMiddleware.handle(i18n))
2195
- app.use(dtoMiddleware())
2196
-
2197
- list = this.ctr({
2198
- logic: async ({ req }) => ({
2199
- data: [],
2200
- message: '@successfully user',
2201
- }),
2202
- })
2203
- ```
2204
-
2205
- ### 8) WebSocket — ctr + middleware
2206
-
2207
- ```typescript
2208
- import { WebSocketServer } from 'ws'
2209
- import { realtimeMiddleware } from '@xrystal/core/utils'
2210
-
2211
- class ChatController extends Controller {
2212
- onMessage = this.ctr({
2213
- logic: async ({ req }) => ({ data: { text: req.body } }),
2214
- }, { protocol: 'ws' })
2215
- }
2216
-
2217
- const wss = new WebSocketServer({ port: 3001 })
2218
- wss.on('connection', (socket) => {
2219
- realtimeMiddleware('ws')(socket, () => {})
2220
- socket.on('message', chatCtrl.onMessage.with(socket))
2221
- })
2222
- ```
2223
-
2224
- ### 9) Socket.IO — aynı controller, farklı protocol
2225
-
2226
- ```typescript
2227
- import { Server } from 'socket.io'
2228
- import { realtimeMiddleware } from '@xrystal/core/utils'
2229
-
2230
- class ChatController extends Controller {
2231
- onMessage = this.ctr({ logic: async () => ({ data: {} }) }, { protocol: 'ws' })
2232
- onChat = this.ctr({ logic: async () => ({ data: { room: 'lobby' } }) }, { protocol: 'socketio' })
2233
- }
2234
-
2235
- const io = new Server(3002)
2236
- io.use(realtimeMiddleware('socketio'))
2237
- io.on('connection', (socket) => {
2238
- socket.on('chat', chatCtrl.onChat.with(socket))
2239
- })
415
+ .listen(3000)
2240
416
  ```
2241
417
 
2242
- ### 10) ws + socketio birlikte (tmp.yml)
418
+ ### DI + locale + G store together / birlikte
2243
419
 
2244
420
  ```yaml
421
+ # x/tmp.yml
2245
422
  configs:
2246
- protocols: [http, ws, socketio]
2247
- ```
2248
-
2249
- ```typescript
2250
- io.use(realtimeMiddleware('socketio'))
2251
- wss.on('connection', (s) => realtimeMiddleware('ws')(s, () => {}))
423
+ service:
424
+ framework: express
425
+ loaders:
426
+ localization: { fallbackLang: en, preloadLangs: [en, tr] }
427
+ system:
428
+ gStore:
429
+ vars: { maintenance: false }
430
+ dto: { withDefaultHeaders: true }
431
+ loggers: { logLevel: info }
432
+ controller: {}
2252
433
  ```
2253
434
 
2254
- ### 11) Controller yok — runAction
2255
-
2256
435
  ```typescript
2257
- import { realtimeMiddleware, runAction } from '@xrystal/core/utils'
2258
-
2259
- wss.on('connection', (socket) => {
2260
- realtimeMiddleware('ws')(socket, () => {})
2261
- socket.on('message', async () => {
2262
- await runAction({ protocol: 'ws', socket }, async () =>
2263
- socket.builder.as.ok({ pong: true }).build(),
2264
- )
436
+ class UserController extends Controller {
437
+ list = this.ctr({
438
+ checks: () => G.get('maintenance') ? { message: '@unsuccessful maintenance' } : true,
439
+ logic: async ({ req }) => ({
440
+ data: [],
441
+ message: '@successfully user',
442
+ }),
2265
443
  })
2266
- })
2267
- ```
2268
-
2269
- ### 12) Cron / queue — trace, protocol yok
2270
-
2271
- ```typescript
2272
- import { runWithTrace, LoggerLayerEnum } from '@xrystal/core/utils'
2273
-
2274
- await runWithTrace('nightly-sync', async () => {
2275
- logger.log(LoggerLayerEnum.INFO, 'started')
2276
- }, 'sync-job')
2277
- ```
2278
-
2279
- ### 13) G — düz prop store (System boot)
2280
-
2281
- ```yaml
2282
- configs:
2283
- loaders:
2284
- system:
2285
- gStore:
2286
- options:
2287
- bootstrap: true
2288
- autoCreateProps: false
2289
- vars:
2290
- test: false
2291
- ```
2292
-
2293
- ```typescript
2294
- import { G, GStoreScopeEnum } from '@xrystal/core/utils'
2295
-
2296
- G.get('test')
2297
- G.set('test', true) // declared in vars
2298
- // G.set('runtimeProp', 1) // throws when autoCreateProps: false
2299
-
2300
- G.scope(GStoreScopeEnum.GLOBAL)
2301
-
2302
- G.subscribeKey('test', (value, prev) => {
2303
- logger.log(LoggerLayerEnum.INFO, 'test', { value, prev })
2304
- })
2305
- ```
2306
-
2307
- Detay: [Three stores → G](#g--global-store-zustand)
2308
-
2309
- ---
2310
-
2311
- ## Tests / Testler
2312
-
2313
- ```bash
2314
- bun run release:prepare # lint + test + build — same as tag pre-check / tag öncesi kontrol
2315
- bun test x/tests # 103 tests — CLI, realtime, i18n, tmp guard, …
2316
- bun run lint # @/ alias rules on source/*.ts
2317
- bun run build # tsc → x/dist (+ fix-dist-imports; minify if tmp build.minify)
444
+ }
2318
445
  ```
2319
446
 
2320
- **EN:** Lightweight unit/integration tests (no full Awilix boot in most suites). Path alias `@/*` → `./source/*` via `bunfig.toml`.
2321
- **TR:** Hafif unit/integration testleri (çoğu suite’te tam Awilix boot yok). `@/*` alias `bunfig.toml` ile çözülür.
2322
-
2323
- **EN:** Publish CI: `lint` → `build` → `test` → `prepare-npm-publish` → `verify-npm-pack` → `npm publish`. Details: [npm publish](#npm-publish--npm-yayın).
2324
-
2325
- **TR:** Publish CI: `lint` → `build` → `test` → `prepare-npm-publish` → `verify-npm-pack` → `npm publish`. Detay: [npm publish](#npm-publish--npm-yayın).
2326
-
2327
- `express` is a **devDependency** only — not shipped to apps / uygulamalara gitmez.
2328
-
2329
- ---
2330
-
2331
- ## DTO re-exports
2332
-
2333
- ```typescript
2334
- import { LogDTO, QueueDTO, ResponseDTO, Builder } from '@xrystal/core/utils'
2335
- ```
447
+ ### Import summary / Import özeti
2336
448
 
2337
- Same types as `@xrystal/dto` — use for logs, queues, standalone responses outside controllers.
449
+ | What / Ne | Import |
450
+ |-----------|--------|
451
+ | Boot | `import coreLoader from '@xrystal/core'` |
452
+ | Controller base | `import Controller from '@xrystal/core/loader/controller'` |
453
+ | Middleware, G, tmp helpers | `import { … } from '@xrystal/core/utils'` |
2338
454
 
2339
455
  ---
2340
456
 
2341
- ## Log schema (Kafka)
457
+ ## Maintainer note / Geliştirici notu
2342
458
 
2343
- ```text
2344
- {
2345
- service,
2346
- level,
2347
- message,
2348
- payload?,
2349
- code?,
2350
- timestamp,
2351
- id,
2352
- env
2353
- }
2354
- ```
459
+ **EN:** This repo is the `@xrystal/core` source. npm publish and build pipeline live in repo scripts (`release:prepare`, `x/bin/scripts/`) — not needed for library consumers.
2355
460
 
2356
- Built via `LogDTO.schema().build()` inside the logger.
461
+ **TR:** Bu repo `@xrystal/core` kaynak kodudur. npm publish ve build pipeline repo script'lerinde — kütüphane tüketicisi için gerekli değildir.