@xrystal/core 3.55.18 → 3.55.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -262,6 +262,10 @@ bun run dev
262
262
  **EN:** `x/environments/.global.env` and `.dev.env` are for **local dev** and **Telepresence** only. They must not be copied into container images. In k8s, inject the same keys via Secret (`envFrom`); `xry start` / `Configs` read **`process.env`** only (detects `KUBERNETES_SERVICE_HOST`, `/.dockerenv`, or `XRY_RUNTIME=container`). Docker Compose: use `env_file:` at compose level — not `COPY x/environments` in the Dockerfile.
263
263
 
264
264
  **TR:** `x/environments/*` yalnızca lokal dev + Telepresence. Image'a gömme. Cluster'da Secret inject; runtime dosya okumaz.
265
+
266
+ **Infra preflight:** Before Kafka/Redis/Mongo connect, parallel TCP (~500ms) from tmp.yml + env. **Default fail-fast** (structured report with UTC time, runtime, probe stats; exit 1 without stack). Lenient: `STRICT_INFRA_PREFLIGHT=0`. Disable TCP: `INFRA_PREFLIGHT_TCP=0`. Timeout: `INFRA_PREFLIGHT_TIMEOUT_MS`.
267
+
268
+ **Docker / Compose:** Image `CMD ["bun", "xry", "start"]` (dev: `xry dev`). Runtime skips `x/environments` when `/.dockerenv` or k8s is detected (optional override: `XRY_RUNTIME=container|docker|k8s`). Compose: `env_file:` on `x/docker/docker-compose*.yml` — not `COPY` env into the image.
265
269
  | `xry test` | Run `x/tests` | `x/tests` çalıştır |
266
270
  | `xry doctor` | CLI, runtime, package health | CLI, runtime, paket uyumu |
267
271
  | `xry tag` | **This repo only** — tag + npm publish (`@xrystal/core`) | **Sadece core** — servislerde çalışmaz / git tag yok |
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Yusuf Yasir KAYGUSUZ",
3
3
  "name": "@xrystal/core",
4
- "version": "3.55.18",
4
+ "version": "3.55.62",
5
5
  "description": "Runtime framework and CLI for API services, frontends, and multi-repo workspaces",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -13,7 +13,6 @@ import {
13
13
  resolveDevEntry,
14
14
  resolveDevRunnerEnvFiles,
15
15
  resolveDistEntryAbs,
16
- isProcessEnvInjectedRuntime,
17
16
  resolveStartEnvFiles,
18
17
  resolvePackageScriptRunner,
19
18
  resolveRuntimeRunner,
@@ -65,8 +64,6 @@ export function registerProjectCommands(cli, { cliName = CLI_PRIMARY_NAME } = {}
65
64
  console.log(chalk.gray(` entry: ${entry} (.ts)`))
66
65
  if (envFiles.length) {
67
66
  console.log(chalk.gray(` env: ${envFiles.map((f) => path.relative(root, f)).join(' · ')}\n`))
68
- } else if (isProcessEnvInjectedRuntime()) {
69
- console.log(chalk.gray(' env: process environment (injected runtime)\n'))
70
67
  } else {
71
68
  console.log('')
72
69
  }
@@ -141,7 +138,7 @@ export function registerProjectCommands(cli, { cliName = CLI_PRIMARY_NAME } = {}
141
138
  if (envFiles.length) {
142
139
  console.log(chalk.gray(` env: ${envFiles.map((f) => path.relative(root, f)).join(' · ')}\n`))
143
140
  } else {
144
- console.log(chalk.gray(' env: process environment (no --env-file)\n'))
141
+ console.log('')
145
142
  }
146
143
  runRunner(root, runner, argv)
147
144
  }, { cliName, command: 'start' })
@@ -3,6 +3,7 @@ import Configs from "./configs";
3
3
  import KafkaForCore from "./kafka";
4
4
  import RedisForCore from "./redis";
5
5
  import MongoForCore from "./mongo";
6
+ import InfraPreflight from "./infra-preflight";
6
7
  import Logger from "./logger";
7
8
  import Events from "./events";
8
9
  import Localizations from "./localizations";
@@ -10,4 +11,4 @@ import DtoRuntime from "./dto";
10
11
  import Controller from "./controller";
11
12
  import Service from "./service";
12
13
  import Clients from "./clients";
13
- export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore };
14
+ export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore, InfraPreflight };
@@ -3,6 +3,7 @@ import Configs from "./configs/index.js";
3
3
  import KafkaForCore from "./kafka/index.js";
4
4
  import RedisForCore from "./redis/index.js";
5
5
  import MongoForCore from "./mongo/index.js";
6
+ import InfraPreflight from "./infra-preflight/index.js";
6
7
  import Logger from "./logger/index.js";
7
8
  import Events from "./events/index.js";
8
9
  import Localizations from "./localizations/index.js";
@@ -10,4 +11,4 @@ import DtoRuntime from "./dto/index.js";
10
11
  import Controller from "./controller/index.js";
11
12
  import Service from "./service/index.js";
12
13
  import Clients from "./clients/index.js";
13
- export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore };
14
+ export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore, InfraPreflight };
@@ -0,0 +1,9 @@
1
+ import Configs from '../../loader/configs';
2
+ import { IProvide } from '../../utils/models/classes/class.interfaces';
3
+ export default class InfraPreflight implements IProvide<void> {
4
+ #private;
5
+ constructor({ configs }: {
6
+ configs: Configs;
7
+ });
8
+ onInit: () => Promise<void>;
9
+ }
@@ -0,0 +1,10 @@
1
+ import { runInfraPreflight } from '../../utils/helpers/infra-preflight/index.js';
2
+ export default class InfraPreflight {
3
+ #configs;
4
+ constructor({ configs }) {
5
+ this.#configs = configs;
6
+ }
7
+ onInit = async () => {
8
+ await runInfraPreflight(this.#configs.all);
9
+ };
10
+ }
@@ -1,6 +1,6 @@
1
1
  import path from 'path';
2
2
  import { fileURLToPath } from 'node:url';
3
- import { System, Configs, Logger, Events, Localizations, DtoRuntime, Clients, Controller, KafkaForCore, RedisForCore, MongoForCore, } from '../loader/index.js';
3
+ import { System, Configs, Logger, Events, Localizations, DtoRuntime, Clients, Controller, KafkaForCore, RedisForCore, MongoForCore, InfraPreflight, } from '../loader/index.js';
4
4
  import { Constants, getCore, x } from '../utils/index.js';
5
5
  import { ensureCoreTmpEntry, isCorePackageRoot } from '../utils/helpers/core/tmp-layout.js';
6
6
  import { getTmpSnapshot } from '../utils/helpers/tmp/tmp-loader.js';
@@ -24,6 +24,7 @@ function buildLoaderInitList(plan, coreRef) {
24
24
  const entries = [
25
25
  { service: System, props: { core: coreRef } },
26
26
  { service: Configs, props: {} },
27
+ { service: InfraPreflight, props: {} },
27
28
  ];
28
29
  if (isInfraLoaderEnabled(plan, InfraLoaderEnum.KAFKA))
29
30
  entries.push({ service: KafkaForCore, props: {} });
@@ -26,3 +26,4 @@ export * from '../../utils/helpers/handlers';
26
26
  export * from '../../utils/helpers/runtime';
27
27
  export * from '../../utils/helpers/node-env';
28
28
  export * from '../../utils/helpers/workspace';
29
+ export * from '../../utils/helpers/infra-preflight';
@@ -26,3 +26,4 @@ export * from '../../utils/helpers/handlers/index.js';
26
26
  export * from '../../utils/helpers/runtime/index.js';
27
27
  export * from '../../utils/helpers/node-env/index.js';
28
28
  export * from '../../utils/helpers/workspace/index.js';
29
+ export * from '../../utils/helpers/infra-preflight/index.js';
@@ -0,0 +1,48 @@
1
+ import type { IConfig } from '../../../loader/configs';
2
+ import { type LoaderBootPlan } from '../../../utils/helpers/tmp/loader-boot-plan';
3
+ export type InfraEndpoint = {
4
+ service: string;
5
+ label: string;
6
+ host: string;
7
+ port: number;
8
+ envKey: string;
9
+ };
10
+ export type InfraProbeResult = {
11
+ endpoint: InfraEndpoint;
12
+ ok: boolean;
13
+ error?: string;
14
+ };
15
+ type PreflightRow = {
16
+ service: string;
17
+ envKey: string;
18
+ target: string;
19
+ result: 'OK' | 'UNREACHABLE' | 'CONFIG' | 'INVALID';
20
+ detail?: string;
21
+ };
22
+ export type PreflightReportMeta = {
23
+ atUtc: string;
24
+ runtime: string;
25
+ host: string;
26
+ namespace?: string;
27
+ coreVersion: string;
28
+ probeTimeoutMs: number;
29
+ tcpProbe: boolean;
30
+ durationMs: number;
31
+ };
32
+ export declare function buildPreflightReportMeta(options: {
33
+ probeTimeoutMs: number;
34
+ tcpProbe: boolean;
35
+ startedAtMs: number;
36
+ }): PreflightReportMeta;
37
+ /** Strict fail: one report on stderr, exit 1 — no Error stack (avoids duplicate lines + Bun SIGTERM noise in k8s). */
38
+ export declare function abortInfraPreflight(report: string): never;
39
+ export declare function resolveProbeTimeoutMs(): number;
40
+ /** Default: fail-fast. Set STRICT_INFRA_PREFLIGHT=0|false|no|off to warn only (local edge cases). */
41
+ export declare function isStrictInfraPreflight(): boolean;
42
+ /** Default: same fast TCP probe everywhere (local, Docker, Kubernetes). Opt out: INFRA_PREFLIGHT_TCP=0. */
43
+ export declare function shouldTcpProbeInfraPreflight(): boolean;
44
+ export declare function collectInfraEndpoints(plan: LoaderBootPlan, config: IConfig): InfraEndpoint[];
45
+ export declare function collectInfraConfigGaps(plan: LoaderBootPlan, config: IConfig): PreflightRow[];
46
+ export declare function probeInfraEndpoints(endpoints: InfraEndpoint[]): Promise<InfraProbeResult[]>;
47
+ export declare function runInfraPreflight(config: IConfig, plan?: LoaderBootPlan): Promise<void>;
48
+ export {};
@@ -0,0 +1,354 @@
1
+ import fs from 'node:fs';
2
+ import net from 'node:net';
3
+ import { parseRedisUri } from '../../../loader/redis/parse-uri.js';
4
+ import { InfraLoaderEnum } from '../../../utils/models/enums/index.js';
5
+ import { isInfraLoaderEnabled, resolveLoaderBootPlan, } from '../../../utils/helpers/tmp/loader-boot-plan.js';
6
+ import { resolveTmpRuntimeConfigs } from '../../../utils/helpers/tmp/tmp-schema.js';
7
+ import { getTmpSnapshot } from '../../../utils/helpers/tmp/tmp-loader.js';
8
+ const DEFAULT_PROBE_TIMEOUT_MS = 500;
9
+ const RULE = '─'.repeat(72);
10
+ function resolveRuntimeLabel() {
11
+ if (process.env.KUBERNETES_SERVICE_HOST)
12
+ return 'kubernetes';
13
+ try {
14
+ if (fs.existsSync('/.dockerenv'))
15
+ return 'docker';
16
+ }
17
+ catch {
18
+ /* ignore */
19
+ }
20
+ return 'local';
21
+ }
22
+ export function buildPreflightReportMeta(options) {
23
+ const ns = (process.env.KUBERNETES_NAMESPACE ?? process.env.POD_NAMESPACE ?? '').trim();
24
+ return {
25
+ atUtc: new Date().toISOString(),
26
+ runtime: resolveRuntimeLabel(),
27
+ host: (process.env.HOSTNAME ?? process.env.HOST ?? 'unknown').trim() || 'unknown',
28
+ namespace: ns || undefined,
29
+ coreVersion: (process.env.npm_package_version ?? 'unknown').trim() || 'unknown',
30
+ probeTimeoutMs: options.probeTimeoutMs,
31
+ tcpProbe: options.tcpProbe,
32
+ durationMs: Math.max(0, Date.now() - options.startedAtMs),
33
+ };
34
+ }
35
+ /** Strict fail: one report on stderr, exit 1 — no Error stack (avoids duplicate lines + Bun SIGTERM noise in k8s). */
36
+ export function abortInfraPreflight(report) {
37
+ console.error(report);
38
+ process.exit(1);
39
+ }
40
+ export function resolveProbeTimeoutMs() {
41
+ const raw = (process.env.INFRA_PREFLIGHT_TIMEOUT_MS ?? '').trim();
42
+ if (!raw)
43
+ return DEFAULT_PROBE_TIMEOUT_MS;
44
+ const n = Number.parseInt(raw, 10);
45
+ if (!Number.isFinite(n) || n < 100)
46
+ return DEFAULT_PROBE_TIMEOUT_MS;
47
+ return Math.min(n, 5000);
48
+ }
49
+ /** Default: fail-fast. Set STRICT_INFRA_PREFLIGHT=0|false|no|off to warn only (local edge cases). */
50
+ export function isStrictInfraPreflight() {
51
+ const raw = (process.env.STRICT_INFRA_PREFLIGHT ?? '').trim().toLowerCase();
52
+ if (!raw)
53
+ return true;
54
+ if (raw === '0' || raw === 'false' || raw === 'no' || raw === 'off')
55
+ return false;
56
+ return true;
57
+ }
58
+ /** Default: same fast TCP probe everywhere (local, Docker, Kubernetes). Opt out: INFRA_PREFLIGHT_TCP=0. */
59
+ export function shouldTcpProbeInfraPreflight() {
60
+ const raw = (process.env.INFRA_PREFLIGHT_TCP ?? '').trim().toLowerCase();
61
+ if (raw === '0' || raw === 'false' || raw === 'no' || raw === 'off')
62
+ return false;
63
+ return true;
64
+ }
65
+ function runtimeContextHint() {
66
+ if (process.env.KUBERNETES_SERVICE_HOST) {
67
+ if (!shouldTcpProbeInfraPreflight()) {
68
+ return 'Kubernetes: TCP preflight disabled (INFRA_PREFLIGHT_TCP=0). Config-only check.';
69
+ }
70
+ return 'Kubernetes: pod must reach bare-metal hosts in env (often Tailscale IP). Fix UFW/routes if UNREACHABLE.';
71
+ }
72
+ try {
73
+ if (fs.existsSync('/.dockerenv')) {
74
+ return 'Docker: URIs must resolve from inside the container (Tailscale IP, host gateway, not host-only 127.0.0.1).';
75
+ }
76
+ }
77
+ catch {
78
+ /* ignore */
79
+ }
80
+ return 'Local: verify VPN/Tailscale and that env hosts match this process.';
81
+ }
82
+ function parseMongoEndpoints(uri) {
83
+ const trimmed = uri.trim();
84
+ if (!trimmed)
85
+ return [];
86
+ if (trimmed.startsWith('mongodb+srv://')) {
87
+ const host = trimmed.replace(/^mongodb\+srv:\/\//, '').split('/')[0]?.split('?')[0] ?? '';
88
+ return [{
89
+ service: 'MongoDB',
90
+ label: 'mongodb+srv',
91
+ host: host || '(srv)',
92
+ port: 27017,
93
+ envKey: 'MONGODB_URI',
94
+ }];
95
+ }
96
+ const withoutScheme = trimmed.replace(/^mongodb:\/\//, '');
97
+ const authority = withoutScheme.split('/')[0] ?? '';
98
+ const hostsCsv = authority.includes('@') ? authority.split('@').pop() ?? '' : authority;
99
+ return hostsCsv
100
+ .split(',')
101
+ .map((part) => part.trim())
102
+ .filter(Boolean)
103
+ .map((part, index) => {
104
+ const colon = part.lastIndexOf(':');
105
+ const host = colon === -1 ? part : part.slice(0, colon);
106
+ const port = colon === -1 ? 27017 : Number.parseInt(part.slice(colon + 1), 10);
107
+ return {
108
+ service: 'MongoDB',
109
+ label: index === 0 ? 'primary' : `host-${index + 1}`,
110
+ host,
111
+ port: Number.isFinite(port) ? port : 27017,
112
+ envKey: 'MONGODB_URI',
113
+ };
114
+ });
115
+ }
116
+ function parseKafkaEndpoints(brokers) {
117
+ return brokers
118
+ .split(',')
119
+ .map((part) => part.trim())
120
+ .filter(Boolean)
121
+ .map((part, index) => {
122
+ const colon = part.lastIndexOf(':');
123
+ const host = colon === -1 ? part : part.slice(0, colon);
124
+ const port = colon === -1 ? 9092 : Number.parseInt(part.slice(colon + 1), 10);
125
+ return {
126
+ service: 'Kafka',
127
+ label: index === 0 ? 'broker' : `broker-${index + 1}`,
128
+ host,
129
+ port: Number.isFinite(port) ? port : 9092,
130
+ envKey: 'KAFKA_BROKERS',
131
+ };
132
+ });
133
+ }
134
+ function probeTcp(host, port, timeoutMs) {
135
+ const ms = timeoutMs ?? resolveProbeTimeoutMs();
136
+ if (host === '(srv)' || host === '_srv_') {
137
+ return Promise.resolve({ ok: true });
138
+ }
139
+ return new Promise((resolve) => {
140
+ const socket = net.connect({ host, port });
141
+ let settled = false;
142
+ const finish = (ok, error) => {
143
+ if (settled)
144
+ return;
145
+ settled = true;
146
+ socket.destroy();
147
+ resolve({ ok, error });
148
+ };
149
+ socket.setTimeout(ms);
150
+ socket.on('connect', () => finish(true));
151
+ socket.on('timeout', () => finish(false, 'connection timed out'));
152
+ socket.on('error', (err) => finish(false, err.code ?? err.message));
153
+ });
154
+ }
155
+ export function collectInfraEndpoints(plan, config) {
156
+ const endpoints = [];
157
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.KAFKA) && !config.isKafkaPassive && config.kafkaBrokers?.trim()) {
158
+ endpoints.push(...parseKafkaEndpoints(config.kafkaBrokers));
159
+ }
160
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.REDIS) && !config.isRedisPassive && config.redisUri?.trim()) {
161
+ try {
162
+ const parsed = parseRedisUri(config.redisUri);
163
+ for (const [index, ep] of parsed.endpoints.entries()) {
164
+ endpoints.push({
165
+ service: 'Redis',
166
+ label: parsed.useSentinel ? `sentinel-${index + 1}` : 'data',
167
+ host: ep.host,
168
+ port: ep.port,
169
+ envKey: 'REDIS_URI',
170
+ });
171
+ }
172
+ }
173
+ catch {
174
+ endpoints.push({
175
+ service: 'Redis',
176
+ label: 'uri',
177
+ host: '(invalid REDIS_URI)',
178
+ port: 6379,
179
+ envKey: 'REDIS_URI',
180
+ });
181
+ }
182
+ }
183
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.MONGO) && !config.isMongoPassive && config.mongodbUri?.trim()) {
184
+ endpoints.push(...parseMongoEndpoints(config.mongodbUri));
185
+ }
186
+ if (config.isRegistryEnabled && config.registryMongodbUri?.trim()) {
187
+ for (const ep of parseMongoEndpoints(config.registryMongodbUri)) {
188
+ endpoints.push({ ...ep, service: 'Registry MongoDB', envKey: 'REGISTRY_MONGODB_URI' });
189
+ }
190
+ }
191
+ return endpoints;
192
+ }
193
+ export function collectInfraConfigGaps(plan, config) {
194
+ const rows = [];
195
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.KAFKA) && !config.isKafkaPassive && !config.kafkaBrokers?.trim()) {
196
+ rows.push({
197
+ service: 'Kafka',
198
+ envKey: 'KAFKA_BROKERS',
199
+ target: '(not set)',
200
+ result: 'CONFIG',
201
+ detail: 'loader enabled in tmp.yml',
202
+ });
203
+ }
204
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.REDIS) && !config.isRedisPassive && !config.redisUri?.trim()) {
205
+ rows.push({
206
+ service: 'Redis',
207
+ envKey: 'REDIS_URI',
208
+ target: '(not set)',
209
+ result: 'CONFIG',
210
+ detail: 'loader enabled in tmp.yml',
211
+ });
212
+ }
213
+ if (isInfraLoaderEnabled(plan, InfraLoaderEnum.MONGO) && !config.isMongoPassive && !config.mongodbUri?.trim()) {
214
+ rows.push({
215
+ service: 'MongoDB',
216
+ envKey: 'MONGODB_URI',
217
+ target: '(not set)',
218
+ result: 'CONFIG',
219
+ detail: 'loader enabled in tmp.yml',
220
+ });
221
+ }
222
+ if (config.isRegistryEnabled && !config.registryMongodbUri?.trim()) {
223
+ rows.push({
224
+ service: 'Registry MongoDB',
225
+ envKey: 'REGISTRY_MONGODB_URI',
226
+ target: '(not set)',
227
+ result: 'CONFIG',
228
+ detail: 'IS_REGISTRY_ENABLED=true',
229
+ });
230
+ }
231
+ return rows;
232
+ }
233
+ export async function probeInfraEndpoints(endpoints) {
234
+ const timeoutMs = resolveProbeTimeoutMs();
235
+ const sockets = new Map();
236
+ for (const ep of endpoints) {
237
+ if (ep.host.startsWith('('))
238
+ continue;
239
+ sockets.set(`${ep.host}:${ep.port}`, { host: ep.host, port: ep.port });
240
+ }
241
+ const socketStatus = new Map();
242
+ await Promise.all([...sockets.entries()].map(async ([key, { host, port }]) => {
243
+ socketStatus.set(key, await probeTcp(host, port, timeoutMs));
244
+ }));
245
+ const results = [];
246
+ for (const endpoint of endpoints) {
247
+ if (endpoint.host.startsWith('('))
248
+ continue;
249
+ const key = `${endpoint.host}:${endpoint.port}`;
250
+ const status = socketStatus.get(key) ?? { ok: false, error: 'not probed' };
251
+ results.push({ endpoint, ok: status.ok, error: status.error });
252
+ }
253
+ return results;
254
+ }
255
+ function pad(value, width) {
256
+ if (value.length >= width)
257
+ return value.slice(0, width);
258
+ return value + ' '.repeat(width - value.length);
259
+ }
260
+ function formatReportMeta(meta) {
261
+ const lines = [
262
+ `At ${meta.atUtc}`,
263
+ `Runtime ${meta.runtime}`,
264
+ `Host ${meta.host}`,
265
+ ];
266
+ if (meta.namespace)
267
+ lines.push(`Namespace ${meta.namespace}`);
268
+ lines.push(`Core @xrystal/core ${meta.coreVersion}`, `Probe timeout ${meta.probeTimeoutMs}ms · TCP ${meta.tcpProbe ? 'on' : 'off'} · elapsed ${meta.durationMs}ms`);
269
+ return lines;
270
+ }
271
+ function formatReport(outcome, rows, context, meta, action) {
272
+ const lines = [
273
+ 'Infrastructure preflight',
274
+ RULE,
275
+ ...formatReportMeta(meta),
276
+ RULE,
277
+ outcome,
278
+ RULE,
279
+ `${pad('Service', 14)} ${pad('Env', 22)} ${pad('Target', 22)} Result`,
280
+ RULE,
281
+ ];
282
+ for (const row of rows) {
283
+ const detail = row.detail ? ` ${row.detail}` : '';
284
+ lines.push(`${pad(row.service, 14)} ${pad(row.envKey, 22)} ${pad(row.target, 22)} ${row.result}${detail}`);
285
+ }
286
+ lines.push(RULE, `Context ${context}`);
287
+ if (action)
288
+ lines.push(`Action ${action}`);
289
+ lines.push(RULE);
290
+ return lines.join('\n');
291
+ }
292
+ function buildFailureAction(strict) {
293
+ if (strict)
294
+ return 'Boot aborted. Set STRICT_INFRA_PREFLIGHT=0 only for warn-only local runs.';
295
+ return 'Boot continues (lenient mode). Fix connectivity before relying on infra loaders.';
296
+ }
297
+ export async function runInfraPreflight(config, plan) {
298
+ const startedAtMs = Date.now();
299
+ const strict = isStrictInfraPreflight();
300
+ const probeTimeoutMs = resolveProbeTimeoutMs();
301
+ const tcpProbe = shouldTcpProbeInfraPreflight();
302
+ const bootPlan = plan ?? resolveLoaderBootPlan(resolveTmpRuntimeConfigs(getTmpSnapshot()));
303
+ const rows = [...collectInfraConfigGaps(bootPlan, config)];
304
+ const endpoints = collectInfraEndpoints(bootPlan, config);
305
+ const meta = () => buildPreflightReportMeta({ probeTimeoutMs, tcpProbe, startedAtMs });
306
+ for (const ep of endpoints.filter((e) => e.host.startsWith('('))) {
307
+ rows.push({
308
+ service: ep.service,
309
+ envKey: ep.envKey,
310
+ target: '(invalid uri)',
311
+ result: 'INVALID',
312
+ detail: 'could not parse host',
313
+ });
314
+ }
315
+ const configFailed = rows.filter((r) => r.result !== 'OK');
316
+ if (!shouldTcpProbeInfraPreflight()) {
317
+ if (configFailed.length === 0) {
318
+ console.log('Infrastructure preflight: config OK (TCP disabled via INFRA_PREFLIGHT_TCP=0).');
319
+ return;
320
+ }
321
+ const outcome = `Outcome FAILED | ${configFailed.length} config issue(s), TCP disabled`;
322
+ const report = formatReport(outcome, rows, runtimeContextHint(), meta(), buildFailureAction(strict));
323
+ if (strict)
324
+ abortInfraPreflight(report);
325
+ console.error(report);
326
+ return;
327
+ }
328
+ const probeTargets = endpoints.filter((ep) => !ep.host.startsWith('('));
329
+ const results = probeTargets.length ? await probeInfraEndpoints(probeTargets) : [];
330
+ for (const { endpoint, ok, error } of results) {
331
+ rows.push({
332
+ service: endpoint.service,
333
+ envKey: endpoint.envKey,
334
+ target: `${endpoint.host}:${endpoint.port}`,
335
+ result: ok ? 'OK' : 'UNREACHABLE',
336
+ detail: ok ? undefined : error,
337
+ });
338
+ }
339
+ if (rows.length === 0)
340
+ return;
341
+ const failed = rows.filter((r) => r.result !== 'OK');
342
+ const passed = rows.filter((r) => r.result === 'OK');
343
+ if (failed.length === 0) {
344
+ const names = [...new Set(passed.map((r) => r.service))].join(', ');
345
+ const m = meta();
346
+ console.log(`Infrastructure preflight: passed (${passed.length} checks: ${names}, ${m.durationMs}ms)`);
347
+ return;
348
+ }
349
+ const outcome = `Outcome FAILED | ${failed.length} issue(s), ${passed.length} passed`;
350
+ const report = formatReport(outcome, rows, runtimeContextHint(), meta(), buildFailureAction(strict));
351
+ if (strict)
352
+ abortInfraPreflight(report);
353
+ console.error(report);
354
+ }
@@ -0,0 +1,40 @@
1
+ FROM oven/bun:1.1-alpine AS builder
2
+ ARG SERVICE_PATH
3
+ WORKDIR /app
4
+
5
+ COPY ${SERVICE_PATH}/package.json ${SERVICE_PATH}/bun.lockb* ./
6
+ COPY ${SERVICE_PATH}/tsconfig.json ./
7
+
8
+ RUN bun install --frozen-lockfile
9
+
10
+ COPY ${SERVICE_PATH} .
11
+
12
+ ARG OUTPUT_DIR=x
13
+ ENV ROOT_FOLDER_PATH=${OUTPUT_DIR}
14
+ RUN bun run build
15
+
16
+ FROM oven/bun:1.1-alpine
17
+ ARG OUTPUT_DIR=x
18
+ ENV ROOT_FOLDER_PATH=${OUTPUT_DIR}
19
+ WORKDIR /app
20
+
21
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/dist ./${ROOT_FOLDER_PATH}/dist
22
+ COPY --from=builder /app/package.json ./package.json
23
+ COPY --from=builder /app/node_modules ./node_modules
24
+ COPY --from=builder /app/tsconfig.json ./
25
+
26
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/tmp.yml ./${ROOT_FOLDER_PATH}/tmp.yml
27
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/assets/ ./${ROOT_FOLDER_PATH}/assets/
28
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/certificates/ ./${ROOT_FOLDER_PATH}/certificates/
29
+ COPY --from=builder /app/${ROOT_FOLDER_PATH}/public/ ./${ROOT_FOLDER_PATH}/public/
30
+
31
+ RUN addgroup -S nodeuser && adduser -S nodeuser -G nodeuser
32
+ RUN chown -R nodeuser:nodeuser /app
33
+ USER nodeuser
34
+
35
+ EXPOSE 3000
36
+
37
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
38
+ CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:3000/health || exit 1
39
+
40
+ CMD ["bun", "xry", "start"]
@@ -0,0 +1,34 @@
1
+ ARG SERVICE_PATH
2
+
3
+ FROM oven/bun:1.1-alpine AS base
4
+ ARG SERVICE_PATH
5
+ WORKDIR /app
6
+
7
+ COPY ${SERVICE_PATH}/package.json ${SERVICE_PATH}/bun.lockb* ./
8
+
9
+ RUN --mount=type=cache,id=bun,target=/root/.bun/install/cache \
10
+ bun install
11
+
12
+ FROM oven/bun:1.1-alpine AS release
13
+ ARG SERVICE_PATH
14
+ WORKDIR /app
15
+
16
+ COPY --from=base /app/node_modules ./node_modules
17
+
18
+ COPY ${SERVICE_PATH}/package.json ./
19
+
20
+ COPY ${SERVICE_PATH}/source ./source
21
+ COPY ${SERVICE_PATH}/x ./x
22
+ COPY ${SERVICE_PATH}/tsconfig.json ./
23
+ COPY ${SERVICE_PATH}/bunfig.toml* ./
24
+
25
+ RUN addgroup -S nodeuser && adduser -S nodeuser -G nodeuser
26
+ RUN chown -R nodeuser:nodeuser /app
27
+ USER nodeuser
28
+
29
+ EXPOSE 3000
30
+
31
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
32
+ CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:3000/health || exit 1
33
+
34
+ CMD ["bun", "xry", "dev"]
@@ -0,0 +1,14 @@
1
+ # Local dev image — env via compose (not COPY x/environments into the image).
2
+ # Run from repo root: docker compose -f x/docker/docker-compose.dev.yml up --build
3
+ services:
4
+ app:
5
+ build:
6
+ context: ../..
7
+ dockerfile: x/docker/Dockerfile.dev
8
+ args:
9
+ SERVICE_PATH: .
10
+ env_file:
11
+ - ../environments/.global.env
12
+ - ../environments/.dev.env
13
+ ports:
14
+ - "${PORT:-3000}:3000"
@@ -0,0 +1,17 @@
1
+ # Prod-like dist image — env via compose (same keys as k8s Secret inject).
2
+ # Run from repo root: docker compose -f x/docker/docker-compose.yml up --build
3
+ services:
4
+ app:
5
+ build:
6
+ context: ../..
7
+ dockerfile: x/docker/Dockerfile
8
+ args:
9
+ SERVICE_PATH: .
10
+ OUTPUT_DIR: x
11
+ env_file:
12
+ - ../environments/.global.env
13
+ - ../environments/.prod.env
14
+ environment:
15
+ NODE_ENV: production
16
+ ports:
17
+ - "${PORT:-3000}:3000"