@bayoudhi/moose-lib-serverless 0.1.0

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.
@@ -0,0 +1,2989 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/commons-types.ts
12
+ function isTruthy(value) {
13
+ if (!value) return false;
14
+ switch (value.trim().toLowerCase()) {
15
+ case "1":
16
+ case "true":
17
+ case "yes":
18
+ case "on":
19
+ return true;
20
+ default:
21
+ return false;
22
+ }
23
+ }
24
+ function mapTstoJs(filePath) {
25
+ return filePath.replace(/\.ts$/, ".js").replace(/\.cts$/, ".cjs").replace(/\.mts$/, ".mjs");
26
+ }
27
+ var compilerLog, antiCachePath, getFileName, cliLog, MAX_RETRIES, MAX_RETRY_TIME_MS, RETRY_INITIAL_TIME_MS, MAX_RETRIES_PRODUCER, RETRY_FACTOR_PRODUCER, ACKs, logError;
28
+ var init_commons_types = __esm({
29
+ "src/commons-types.ts"() {
30
+ "use strict";
31
+ compilerLog = (message) => {
32
+ if (!isTruthy(process.env.MOOSE_DISABLE_COMPILER_LOGS)) {
33
+ console.log(message);
34
+ }
35
+ };
36
+ antiCachePath = (path2) => `${path2}?num=${Math.random().toString()}&time=${Date.now()}`;
37
+ getFileName = (filePath) => {
38
+ const regex = /\/([^/]+)\.ts/;
39
+ const matches = filePath.match(regex);
40
+ if (matches && matches.length > 1) {
41
+ return matches[1];
42
+ }
43
+ return "";
44
+ };
45
+ cliLog = (log) => {
46
+ const level = log.message_type === "Error" ? "error" : log.message_type === "Warning" ? "warn" : "info";
47
+ const structuredLog = {
48
+ __moose_structured_log__: true,
49
+ level,
50
+ message: log.message,
51
+ resource_type: "runtime",
52
+ cli_action: log.action,
53
+ cli_message_type: log.message_type ?? "Info",
54
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
55
+ };
56
+ process.stderr.write(JSON.stringify(structuredLog) + "\n");
57
+ };
58
+ MAX_RETRIES = 150;
59
+ MAX_RETRY_TIME_MS = 1e3;
60
+ RETRY_INITIAL_TIME_MS = 100;
61
+ MAX_RETRIES_PRODUCER = 150;
62
+ RETRY_FACTOR_PRODUCER = 0.2;
63
+ ACKs = -1;
64
+ logError = (logger, e) => {
65
+ logger.error(e.message);
66
+ const stack = e.stack;
67
+ if (stack) {
68
+ logger.error(stack);
69
+ }
70
+ };
71
+ }
72
+ });
73
+
74
+ // src/config/configFile.ts
75
+ import path from "path";
76
+ import * as toml from "toml";
77
+ async function findConfigFile(startDir = process.cwd()) {
78
+ const fs = await import("fs");
79
+ let currentDir = path.resolve(startDir);
80
+ while (true) {
81
+ const configPath = path.join(currentDir, "moose.config.toml");
82
+ if (fs.existsSync(configPath)) {
83
+ return configPath;
84
+ }
85
+ const parentDir = path.dirname(currentDir);
86
+ if (parentDir === currentDir) {
87
+ break;
88
+ }
89
+ currentDir = parentDir;
90
+ }
91
+ return null;
92
+ }
93
+ async function readProjectConfig() {
94
+ const fs = await import("fs");
95
+ const configPath = await findConfigFile();
96
+ if (!configPath) {
97
+ throw new ConfigError(
98
+ "moose.config.toml not found in current directory or any parent directory"
99
+ );
100
+ }
101
+ try {
102
+ const configContent = fs.readFileSync(configPath, "utf-8");
103
+ const config = toml.parse(configContent);
104
+ return config;
105
+ } catch (error) {
106
+ throw new ConfigError(`Failed to parse moose.config.toml: ${error}`);
107
+ }
108
+ }
109
+ var ConfigError;
110
+ var init_configFile = __esm({
111
+ "src/config/configFile.ts"() {
112
+ "use strict";
113
+ ConfigError = class extends Error {
114
+ constructor(message) {
115
+ super(message);
116
+ this.name = "ConfigError";
117
+ }
118
+ };
119
+ }
120
+ });
121
+
122
+ // src/config/runtime.ts
123
+ var runtime_exports = {};
124
+ var ConfigurationRegistry;
125
+ var init_runtime = __esm({
126
+ "src/config/runtime.ts"() {
127
+ "use strict";
128
+ init_configFile();
129
+ ConfigurationRegistry = class _ConfigurationRegistry {
130
+ static instance;
131
+ clickhouseConfig;
132
+ kafkaConfig;
133
+ static getInstance() {
134
+ if (!_ConfigurationRegistry.instance) {
135
+ _ConfigurationRegistry.instance = new _ConfigurationRegistry();
136
+ }
137
+ return _ConfigurationRegistry.instance;
138
+ }
139
+ setClickHouseConfig(config) {
140
+ this.clickhouseConfig = config;
141
+ }
142
+ setKafkaConfig(config) {
143
+ this.kafkaConfig = config;
144
+ }
145
+ _env(name) {
146
+ const value = process.env[name];
147
+ if (value === void 0) return void 0;
148
+ const trimmed = value.trim();
149
+ return trimmed.length > 0 ? trimmed : void 0;
150
+ }
151
+ _parseBool(value) {
152
+ if (value === void 0) return void 0;
153
+ switch (value.trim().toLowerCase()) {
154
+ case "1":
155
+ case "true":
156
+ case "yes":
157
+ case "on":
158
+ return true;
159
+ case "0":
160
+ case "false":
161
+ case "no":
162
+ case "off":
163
+ return false;
164
+ default:
165
+ return void 0;
166
+ }
167
+ }
168
+ async getClickHouseConfig() {
169
+ if (this.clickhouseConfig) {
170
+ return this.clickhouseConfig;
171
+ }
172
+ const projectConfig = await readProjectConfig();
173
+ const envHost = this._env("MOOSE_CLICKHOUSE_CONFIG__HOST");
174
+ const envPort = this._env("MOOSE_CLICKHOUSE_CONFIG__HOST_PORT");
175
+ const envUser = this._env("MOOSE_CLICKHOUSE_CONFIG__USER");
176
+ const envPassword = this._env("MOOSE_CLICKHOUSE_CONFIG__PASSWORD");
177
+ const envDb = this._env("MOOSE_CLICKHOUSE_CONFIG__DB_NAME");
178
+ const envUseSSL = this._parseBool(
179
+ this._env("MOOSE_CLICKHOUSE_CONFIG__USE_SSL")
180
+ );
181
+ return {
182
+ host: envHost ?? projectConfig.clickhouse_config.host,
183
+ port: envPort ?? projectConfig.clickhouse_config.host_port.toString(),
184
+ username: envUser ?? projectConfig.clickhouse_config.user,
185
+ password: envPassword ?? projectConfig.clickhouse_config.password,
186
+ database: envDb ?? projectConfig.clickhouse_config.db_name,
187
+ useSSL: envUseSSL !== void 0 ? envUseSSL : projectConfig.clickhouse_config.use_ssl || false
188
+ };
189
+ }
190
+ async getStandaloneClickhouseConfig(overrides) {
191
+ if (this.clickhouseConfig) {
192
+ return { ...this.clickhouseConfig, ...overrides };
193
+ }
194
+ const envHost = this._env("MOOSE_CLICKHOUSE_CONFIG__HOST");
195
+ const envPort = this._env("MOOSE_CLICKHOUSE_CONFIG__HOST_PORT");
196
+ const envUser = this._env("MOOSE_CLICKHOUSE_CONFIG__USER");
197
+ const envPassword = this._env("MOOSE_CLICKHOUSE_CONFIG__PASSWORD");
198
+ const envDb = this._env("MOOSE_CLICKHOUSE_CONFIG__DB_NAME");
199
+ const envUseSSL = this._parseBool(
200
+ this._env("MOOSE_CLICKHOUSE_CONFIG__USE_SSL")
201
+ );
202
+ let projectConfig;
203
+ try {
204
+ projectConfig = await readProjectConfig();
205
+ } catch (error) {
206
+ projectConfig = null;
207
+ }
208
+ const defaults = {
209
+ host: "localhost",
210
+ port: "18123",
211
+ username: "default",
212
+ password: "",
213
+ database: "local",
214
+ useSSL: false
215
+ };
216
+ return {
217
+ host: overrides?.host ?? envHost ?? projectConfig?.clickhouse_config.host ?? defaults.host,
218
+ port: overrides?.port ?? envPort ?? projectConfig?.clickhouse_config.host_port.toString() ?? defaults.port,
219
+ username: overrides?.username ?? envUser ?? projectConfig?.clickhouse_config.user ?? defaults.username,
220
+ password: overrides?.password ?? envPassword ?? projectConfig?.clickhouse_config.password ?? defaults.password,
221
+ database: overrides?.database ?? envDb ?? projectConfig?.clickhouse_config.db_name ?? defaults.database,
222
+ useSSL: overrides?.useSSL ?? envUseSSL ?? projectConfig?.clickhouse_config.use_ssl ?? defaults.useSSL
223
+ };
224
+ }
225
+ async getKafkaConfig() {
226
+ if (this.kafkaConfig) {
227
+ return this.kafkaConfig;
228
+ }
229
+ const projectConfig = await readProjectConfig();
230
+ const envBroker = this._env("MOOSE_REDPANDA_CONFIG__BROKER") ?? this._env("MOOSE_KAFKA_CONFIG__BROKER");
231
+ const envMsgTimeout = this._env("MOOSE_REDPANDA_CONFIG__MESSAGE_TIMEOUT_MS") ?? this._env("MOOSE_KAFKA_CONFIG__MESSAGE_TIMEOUT_MS");
232
+ const envSaslUsername = this._env("MOOSE_REDPANDA_CONFIG__SASL_USERNAME") ?? this._env("MOOSE_KAFKA_CONFIG__SASL_USERNAME");
233
+ const envSaslPassword = this._env("MOOSE_REDPANDA_CONFIG__SASL_PASSWORD") ?? this._env("MOOSE_KAFKA_CONFIG__SASL_PASSWORD");
234
+ const envSaslMechanism = this._env("MOOSE_REDPANDA_CONFIG__SASL_MECHANISM") ?? this._env("MOOSE_KAFKA_CONFIG__SASL_MECHANISM");
235
+ const envSecurityProtocol = this._env("MOOSE_REDPANDA_CONFIG__SECURITY_PROTOCOL") ?? this._env("MOOSE_KAFKA_CONFIG__SECURITY_PROTOCOL");
236
+ const envNamespace = this._env("MOOSE_REDPANDA_CONFIG__NAMESPACE") ?? this._env("MOOSE_KAFKA_CONFIG__NAMESPACE");
237
+ const envSchemaRegistryUrl = this._env("MOOSE_REDPANDA_CONFIG__SCHEMA_REGISTRY_URL") ?? this._env("MOOSE_KAFKA_CONFIG__SCHEMA_REGISTRY_URL");
238
+ const fileKafka = projectConfig.kafka_config ?? projectConfig.redpanda_config;
239
+ return {
240
+ broker: envBroker ?? fileKafka?.broker ?? "localhost:19092",
241
+ messageTimeoutMs: envMsgTimeout ? parseInt(envMsgTimeout, 10) : fileKafka?.message_timeout_ms ?? 1e3,
242
+ saslUsername: envSaslUsername ?? fileKafka?.sasl_username,
243
+ saslPassword: envSaslPassword ?? fileKafka?.sasl_password,
244
+ saslMechanism: envSaslMechanism ?? fileKafka?.sasl_mechanism,
245
+ securityProtocol: envSecurityProtocol ?? fileKafka?.security_protocol,
246
+ namespace: envNamespace ?? fileKafka?.namespace,
247
+ schemaRegistryUrl: envSchemaRegistryUrl ?? fileKafka?.schema_registry_url
248
+ };
249
+ }
250
+ hasRuntimeConfig() {
251
+ return !!this.clickhouseConfig || !!this.kafkaConfig;
252
+ }
253
+ };
254
+ globalThis._mooseConfigRegistry = ConfigurationRegistry.getInstance();
255
+ }
256
+ });
257
+
258
+ // src/commons.ts
259
+ var commons_exports = {};
260
+ __export(commons_exports, {
261
+ ACKs: () => ACKs,
262
+ MAX_RETRIES: () => MAX_RETRIES,
263
+ MAX_RETRIES_PRODUCER: () => MAX_RETRIES_PRODUCER,
264
+ MAX_RETRY_TIME_MS: () => MAX_RETRY_TIME_MS,
265
+ RETRY_FACTOR_PRODUCER: () => RETRY_FACTOR_PRODUCER,
266
+ RETRY_INITIAL_TIME_MS: () => RETRY_INITIAL_TIME_MS,
267
+ antiCachePath: () => antiCachePath,
268
+ cliLog: () => cliLog,
269
+ compilerLog: () => compilerLog,
270
+ createProducerConfig: () => createProducerConfig,
271
+ getClickhouseClient: () => getClickhouseClient,
272
+ getFileName: () => getFileName,
273
+ getKafkaClient: () => getKafkaClient,
274
+ getKafkaProducer: () => getKafkaProducer,
275
+ logError: () => logError,
276
+ mapTstoJs: () => mapTstoJs,
277
+ rewriteImportExtensions: () => rewriteImportExtensions
278
+ });
279
+ import { KafkaJS } from "@514labs/kafka-javascript";
280
+ import { createClient } from "@clickhouse/client";
281
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "fs";
282
+ import nodePath from "path";
283
+ function walkDirectory(dir, extensions) {
284
+ const results = [];
285
+ if (!existsSync(dir)) {
286
+ return results;
287
+ }
288
+ try {
289
+ const entries = readdirSync(dir, { withFileTypes: true });
290
+ for (const entry of entries) {
291
+ const fullPath = nodePath.join(dir, entry.name);
292
+ if (entry.isDirectory()) {
293
+ if (entry.name !== "node_modules") {
294
+ results.push(...walkDirectory(fullPath, extensions));
295
+ }
296
+ } else if (entry.isFile()) {
297
+ const ext = nodePath.extname(entry.name);
298
+ if (extensions.includes(ext)) {
299
+ results.push(fullPath);
300
+ }
301
+ }
302
+ }
303
+ } catch (e) {
304
+ console.debug(`[moose] Failed to read directory ${dir}:`, e);
305
+ }
306
+ return results;
307
+ }
308
+ function addJsExtensionToImports(content, fileDir) {
309
+ const fromPattern = /(from\s+['"])(\.\.?\/[^'"]*?)(['"])/g;
310
+ const bareImportPattern = /(import\s+['"])(\.\.?\/[^'"]*?)(['"])/g;
311
+ const dynamicPattern = /(import\s*\(\s*['"])(\.\.?\/[^'"]*?)(['"])/g;
312
+ let result = content;
313
+ result = result.replace(fromPattern, (match, prefix, importPath, quote) => {
314
+ return rewriteImportPath(match, prefix, importPath, quote, fileDir);
315
+ });
316
+ result = result.replace(bareImportPattern, (match, prefix, importPath, quote) => {
317
+ return rewriteImportPath(match, prefix, importPath, quote, fileDir);
318
+ });
319
+ result = result.replace(dynamicPattern, (match, prefix, importPath, quote) => {
320
+ return rewriteImportPath(match, prefix, importPath, quote, fileDir);
321
+ });
322
+ return result;
323
+ }
324
+ function rewriteImportPath(match, prefix, importPath, quote, fileDir) {
325
+ if (/\.[cm]?js$/.test(importPath)) {
326
+ return match;
327
+ }
328
+ if (/\.json$/.test(importPath)) {
329
+ return match;
330
+ }
331
+ if (fileDir) {
332
+ const resolvedPath = nodePath.resolve(fileDir, importPath);
333
+ if (existsSync(`${resolvedPath}.js`)) {
334
+ return `${prefix}${importPath}.js${quote}`;
335
+ }
336
+ if (existsSync(nodePath.join(resolvedPath, "index.js"))) {
337
+ return `${prefix}${importPath}/index.js${quote}`;
338
+ }
339
+ if (existsSync(`${resolvedPath}.mjs`)) {
340
+ return `${prefix}${importPath}.mjs${quote}`;
341
+ }
342
+ if (existsSync(nodePath.join(resolvedPath, "index.mjs"))) {
343
+ return `${prefix}${importPath}/index.mjs${quote}`;
344
+ }
345
+ if (existsSync(`${resolvedPath}.cjs`)) {
346
+ return `${prefix}${importPath}.cjs${quote}`;
347
+ }
348
+ if (existsSync(nodePath.join(resolvedPath, "index.cjs"))) {
349
+ return `${prefix}${importPath}/index.cjs${quote}`;
350
+ }
351
+ }
352
+ return `${prefix}${importPath}.js${quote}`;
353
+ }
354
+ function rewriteImportExtensions(outDir) {
355
+ const files = walkDirectory(outDir, [".js", ".mjs"]);
356
+ for (const filePath of files) {
357
+ const content = readFileSync(filePath, "utf-8");
358
+ const fileDir = nodePath.dirname(filePath);
359
+ const rewritten = addJsExtensionToImports(content, fileDir);
360
+ if (content !== rewritten) {
361
+ writeFileSync(filePath, rewritten, "utf-8");
362
+ }
363
+ }
364
+ }
365
+ function createProducerConfig(maxMessageBytes) {
366
+ return {
367
+ kafkaJS: {
368
+ idempotent: false,
369
+ // Not needed for at-least-once delivery
370
+ acks: ACKs,
371
+ retry: {
372
+ retries: MAX_RETRIES_PRODUCER,
373
+ maxRetryTime: MAX_RETRY_TIME_MS
374
+ }
375
+ },
376
+ "linger.ms": 0,
377
+ // This is to make sure at least once delivery with immediate feedback on the send
378
+ ...maxMessageBytes && { "message.max.bytes": maxMessageBytes }
379
+ };
380
+ }
381
+ async function getKafkaProducer(cfg, logger, maxMessageBytes) {
382
+ const kafka = await getKafkaClient(cfg, logger);
383
+ const producer = kafka.producer(createProducerConfig(maxMessageBytes));
384
+ await producer.connect();
385
+ return producer;
386
+ }
387
+ var Kafka, getClickhouseClient, parseBrokerString, buildSaslConfig, getKafkaClient;
388
+ var init_commons = __esm({
389
+ "src/commons.ts"() {
390
+ "use strict";
391
+ init_commons_types();
392
+ init_commons_types();
393
+ ({ Kafka } = KafkaJS);
394
+ getClickhouseClient = ({
395
+ username,
396
+ password,
397
+ database,
398
+ useSSL,
399
+ host,
400
+ port
401
+ }) => {
402
+ const protocol = useSSL === "1" || useSSL.toLowerCase() === "true" ? "https" : "http";
403
+ console.log(`Connecting to Clickhouse at ${protocol}://${host}:${port}`);
404
+ return createClient({
405
+ url: `${protocol}://${host}:${port}`,
406
+ username,
407
+ password,
408
+ database,
409
+ application: "moose"
410
+ // Note: wait_end_of_query is configured per operation type, not globally
411
+ // to preserve SELECT query performance while ensuring INSERT/DDL reliability
412
+ });
413
+ };
414
+ parseBrokerString = (brokerString) => brokerString.split(",").map((b) => b.trim()).filter((b) => b.length > 0);
415
+ buildSaslConfig = (logger, args) => {
416
+ const mechanism = args.saslMechanism ? args.saslMechanism.toLowerCase() : "";
417
+ switch (mechanism) {
418
+ case "plain":
419
+ case "scram-sha-256":
420
+ case "scram-sha-512":
421
+ return {
422
+ mechanism,
423
+ username: args.saslUsername || "",
424
+ password: args.saslPassword || ""
425
+ };
426
+ default:
427
+ logger.warn(`Unsupported SASL mechanism: ${args.saslMechanism}`);
428
+ return void 0;
429
+ }
430
+ };
431
+ getKafkaClient = async (cfg, logger) => {
432
+ const brokers = parseBrokerString(cfg.broker || "");
433
+ if (brokers.length === 0) {
434
+ throw new Error(`No valid broker addresses found in: "${cfg.broker}"`);
435
+ }
436
+ logger.log(`Creating Kafka client with brokers: ${brokers.join(", ")}`);
437
+ logger.log(`Security protocol: ${cfg.securityProtocol || "plaintext"}`);
438
+ logger.log(`Client ID: ${cfg.clientId}`);
439
+ const saslConfig = buildSaslConfig(logger, cfg);
440
+ return new Kafka({
441
+ kafkaJS: {
442
+ clientId: cfg.clientId,
443
+ brokers,
444
+ ssl: cfg.securityProtocol === "SASL_SSL",
445
+ ...saslConfig && { sasl: saslConfig },
446
+ retry: {
447
+ initialRetryTime: RETRY_INITIAL_TIME_MS,
448
+ maxRetryTime: MAX_RETRY_TIME_MS,
449
+ retries: MAX_RETRIES
450
+ }
451
+ }
452
+ });
453
+ };
454
+ }
455
+ });
456
+
457
+ // src/dataModels/types.ts
458
+ var ClickHouseEngines = /* @__PURE__ */ ((ClickHouseEngines2) => {
459
+ ClickHouseEngines2["MergeTree"] = "MergeTree";
460
+ ClickHouseEngines2["ReplacingMergeTree"] = "ReplacingMergeTree";
461
+ ClickHouseEngines2["SummingMergeTree"] = "SummingMergeTree";
462
+ ClickHouseEngines2["AggregatingMergeTree"] = "AggregatingMergeTree";
463
+ ClickHouseEngines2["CollapsingMergeTree"] = "CollapsingMergeTree";
464
+ ClickHouseEngines2["VersionedCollapsingMergeTree"] = "VersionedCollapsingMergeTree";
465
+ ClickHouseEngines2["GraphiteMergeTree"] = "GraphiteMergeTree";
466
+ ClickHouseEngines2["S3Queue"] = "S3Queue";
467
+ ClickHouseEngines2["S3"] = "S3";
468
+ ClickHouseEngines2["Buffer"] = "Buffer";
469
+ ClickHouseEngines2["Distributed"] = "Distributed";
470
+ ClickHouseEngines2["IcebergS3"] = "IcebergS3";
471
+ ClickHouseEngines2["Kafka"] = "Kafka";
472
+ ClickHouseEngines2["ReplicatedMergeTree"] = "ReplicatedMergeTree";
473
+ ClickHouseEngines2["ReplicatedReplacingMergeTree"] = "ReplicatedReplacingMergeTree";
474
+ ClickHouseEngines2["ReplicatedAggregatingMergeTree"] = "ReplicatedAggregatingMergeTree";
475
+ ClickHouseEngines2["ReplicatedSummingMergeTree"] = "ReplicatedSummingMergeTree";
476
+ ClickHouseEngines2["ReplicatedCollapsingMergeTree"] = "ReplicatedCollapsingMergeTree";
477
+ ClickHouseEngines2["ReplicatedVersionedCollapsingMergeTree"] = "ReplicatedVersionedCollapsingMergeTree";
478
+ return ClickHouseEngines2;
479
+ })(ClickHouseEngines || {});
480
+
481
+ // src/dmv2/utils/stackTrace.ts
482
+ function shouldSkipStackLine(line) {
483
+ return line.includes("node_modules") || // Skip npm installed packages (prod)
484
+ line.includes("node:internal") || // Skip Node.js internals (modern format)
485
+ line.includes("internal/modules") || // Skip Node.js internals (older format)
486
+ line.includes("ts-node") || // Skip TypeScript execution
487
+ line.includes("/ts-moose-lib/src/") || // Skip dev/linked moose-lib src (Unix)
488
+ line.includes("\\ts-moose-lib\\src\\") || // Skip dev/linked moose-lib src (Windows)
489
+ line.includes("/ts-moose-lib/dist/") || // Skip dev/linked moose-lib dist (Unix)
490
+ line.includes("\\ts-moose-lib\\dist\\");
491
+ }
492
+ function parseStackLine(line) {
493
+ const match = line.match(/\((.*):(\d+):(\d+)\)/) || line.match(/at (.*):(\d+):(\d+)/);
494
+ if (match && match[1]) {
495
+ return {
496
+ file: match[1],
497
+ line: match[2]
498
+ };
499
+ }
500
+ return void 0;
501
+ }
502
+ function getSourceFileInfo(stack) {
503
+ if (!stack) return {};
504
+ const lines = stack.split("\n");
505
+ for (const line of lines) {
506
+ if (shouldSkipStackLine(line)) continue;
507
+ const info = parseStackLine(line);
508
+ if (info) return info;
509
+ }
510
+ return {};
511
+ }
512
+ function getSourceLocationFromStack(stack) {
513
+ if (!stack) return void 0;
514
+ const lines = stack.split("\n");
515
+ for (const line of lines.slice(1)) {
516
+ if (shouldSkipStackLine(line)) {
517
+ continue;
518
+ }
519
+ const v8Match = line.match(/at\s+(?:.*?\s+\()?(.+):(\d+):(\d+)\)?/);
520
+ if (v8Match) {
521
+ return {
522
+ file: v8Match[1],
523
+ line: parseInt(v8Match[2], 10),
524
+ column: parseInt(v8Match[3], 10)
525
+ };
526
+ }
527
+ const smMatch = line.match(/(?:.*@)?(.+):(\d+):(\d+)/);
528
+ if (smMatch) {
529
+ return {
530
+ file: smMatch[1],
531
+ line: parseInt(smMatch[2], 10),
532
+ column: parseInt(smMatch[3], 10)
533
+ };
534
+ }
535
+ }
536
+ return void 0;
537
+ }
538
+ function getSourceFileFromStack(stack) {
539
+ const location = getSourceLocationFromStack(stack);
540
+ return location?.file;
541
+ }
542
+
543
+ // src/dmv2/typedBase.ts
544
+ var TypedBase = class {
545
+ /** The JSON schema representation of type T. Injected by the compiler plugin. */
546
+ schema;
547
+ /** The name assigned to this resource instance. */
548
+ name;
549
+ /** A dictionary mapping column names (keys of T) to their Column definitions. */
550
+ columns;
551
+ /** An array containing the Column definitions for this resource. Injected by the compiler plugin. */
552
+ columnArray;
553
+ /** The configuration object specific to this resource type. */
554
+ config;
555
+ /** Typia validation functions for type T. Injected by the compiler plugin for OlapTable. */
556
+ validators;
557
+ /** Optional metadata for the resource, always present as an object. */
558
+ metadata;
559
+ /**
560
+ * Whether this resource allows extra fields beyond the defined columns.
561
+ * When true, extra fields in payloads are passed through to streaming functions.
562
+ * Injected by the compiler plugin when the type has an index signature.
563
+ */
564
+ allowExtraFields;
565
+ /**
566
+ * @internal Constructor intended for internal use by subclasses and the compiler plugin.
567
+ * It expects the schema and columns to be provided, typically injected by the compiler.
568
+ *
569
+ * @param name The name for the resource instance.
570
+ * @param config The configuration object for the resource.
571
+ * @param schema The JSON schema for the resource's data type T (injected).
572
+ * @param columns The array of Column definitions for T (injected).
573
+ * @param allowExtraFields Whether extra fields are allowed (injected when type has index signature).
574
+ */
575
+ constructor(name, config, schema, columns, validators, allowExtraFields) {
576
+ if (schema === void 0 || columns === void 0) {
577
+ throw new Error(
578
+ "Supply the type param T so that the schema is inserted by the compiler plugin."
579
+ );
580
+ }
581
+ this.schema = schema;
582
+ this.columnArray = columns;
583
+ const columnsObj = {};
584
+ columns.forEach((column) => {
585
+ columnsObj[column.name] = column;
586
+ });
587
+ this.columns = columnsObj;
588
+ this.name = name;
589
+ this.config = config;
590
+ this.validators = validators;
591
+ this.allowExtraFields = allowExtraFields ?? false;
592
+ this.metadata = config?.metadata ? { ...config.metadata } : {};
593
+ if (!this.metadata.source) {
594
+ const stack = new Error().stack;
595
+ if (stack) {
596
+ const info = getSourceFileInfo(stack);
597
+ this.metadata.source = { file: info.file, line: info.line };
598
+ }
599
+ }
600
+ }
601
+ };
602
+
603
+ // src/dataModels/dataModelTypes.ts
604
+ function isArrayNestedType(dt) {
605
+ return typeof dt === "object" && dt !== null && dt.elementType !== null && typeof dt.elementType === "object" && dt.elementType.hasOwnProperty("columns") && Array.isArray(dt.elementType.columns);
606
+ }
607
+ function isNestedType(dt) {
608
+ return typeof dt === "object" && dt !== null && Array.isArray(dt.columns);
609
+ }
610
+
611
+ // src/dmv2/internal.ts
612
+ init_commons_types();
613
+ import process2 from "process";
614
+ var isClientOnlyMode = () => process2.env.MOOSE_CLIENT_ONLY === "true";
615
+ var moose_internal = {
616
+ tables: /* @__PURE__ */ new Map(),
617
+ streams: /* @__PURE__ */ new Map(),
618
+ ingestApis: /* @__PURE__ */ new Map(),
619
+ apis: /* @__PURE__ */ new Map(),
620
+ sqlResources: /* @__PURE__ */ new Map(),
621
+ workflows: /* @__PURE__ */ new Map(),
622
+ webApps: /* @__PURE__ */ new Map(),
623
+ materializedViews: /* @__PURE__ */ new Map(),
624
+ views: /* @__PURE__ */ new Map()
625
+ };
626
+ var defaultRetentionPeriod = 60 * 60 * 24 * 7;
627
+ var getMooseInternal = () => globalThis.moose_internal;
628
+ if (getMooseInternal() === void 0) {
629
+ globalThis.moose_internal = moose_internal;
630
+ }
631
+ var dlqSchema = {
632
+ version: "3.1",
633
+ components: {
634
+ schemas: {
635
+ DeadLetterModel: {
636
+ type: "object",
637
+ properties: {
638
+ originalRecord: {
639
+ $ref: "#/components/schemas/Recordstringany"
640
+ },
641
+ errorMessage: {
642
+ type: "string"
643
+ },
644
+ errorType: {
645
+ type: "string"
646
+ },
647
+ failedAt: {
648
+ type: "string",
649
+ format: "date-time"
650
+ },
651
+ source: {
652
+ oneOf: [
653
+ {
654
+ const: "api"
655
+ },
656
+ {
657
+ const: "transform"
658
+ },
659
+ {
660
+ const: "table"
661
+ }
662
+ ]
663
+ }
664
+ },
665
+ required: ["originalRecord", "errorMessage", "errorType", "failedAt", "source"]
666
+ },
667
+ Recordstringany: {
668
+ type: "object",
669
+ properties: {},
670
+ required: [],
671
+ description: "Construct a type with a set of properties K of type T",
672
+ additionalProperties: {}
673
+ }
674
+ }
675
+ },
676
+ schemas: [
677
+ {
678
+ $ref: "#/components/schemas/DeadLetterModel"
679
+ }
680
+ ]
681
+ };
682
+ var dlqColumns = [
683
+ {
684
+ name: "originalRecord",
685
+ data_type: "Json",
686
+ primary_key: false,
687
+ required: true,
688
+ unique: false,
689
+ default: null,
690
+ annotations: [],
691
+ ttl: null,
692
+ codec: null,
693
+ materialized: null,
694
+ comment: null
695
+ },
696
+ {
697
+ name: "errorMessage",
698
+ data_type: "String",
699
+ primary_key: false,
700
+ required: true,
701
+ unique: false,
702
+ default: null,
703
+ annotations: [],
704
+ ttl: null,
705
+ codec: null,
706
+ materialized: null,
707
+ comment: null
708
+ },
709
+ {
710
+ name: "errorType",
711
+ data_type: "String",
712
+ primary_key: false,
713
+ required: true,
714
+ unique: false,
715
+ default: null,
716
+ annotations: [],
717
+ ttl: null,
718
+ codec: null,
719
+ materialized: null,
720
+ comment: null
721
+ },
722
+ {
723
+ name: "failedAt",
724
+ data_type: "DateTime",
725
+ primary_key: false,
726
+ required: true,
727
+ unique: false,
728
+ default: null,
729
+ annotations: [],
730
+ ttl: null,
731
+ codec: null,
732
+ materialized: null,
733
+ comment: null
734
+ },
735
+ {
736
+ name: "source",
737
+ data_type: "String",
738
+ primary_key: false,
739
+ required: true,
740
+ unique: false,
741
+ default: null,
742
+ annotations: [],
743
+ ttl: null,
744
+ codec: null,
745
+ materialized: null,
746
+ comment: null
747
+ }
748
+ ];
749
+
750
+ // src/dmv2/sdk/olapTable.ts
751
+ import { Readable } from "stream";
752
+ import { createHash } from "crypto";
753
+
754
+ // src/sqlHelpers.ts
755
+ var quoteIdentifier = (name) => {
756
+ return name.startsWith("`") && name.endsWith("`") ? name : `\`${name}\``;
757
+ };
758
+ var isTable = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "OlapTable";
759
+ var isView = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "View";
760
+ var isColumn = (value) => typeof value === "object" && value !== null && !("kind" in value) && "name" in value && "annotations" in value;
761
+ function sqlImpl(strings, ...values) {
762
+ return new Sql(strings, values);
763
+ }
764
+ var sql = sqlImpl;
765
+ var instanceofSql = (value) => typeof value === "object" && "values" in value && "strings" in value;
766
+ var Sql = class _Sql {
767
+ values;
768
+ strings;
769
+ constructor(rawStrings, rawValues) {
770
+ if (rawStrings.length - 1 !== rawValues.length) {
771
+ if (rawStrings.length === 0) {
772
+ throw new TypeError("Expected at least 1 string");
773
+ }
774
+ throw new TypeError(
775
+ `Expected ${rawStrings.length} strings to have ${rawStrings.length - 1} values`
776
+ );
777
+ }
778
+ const valuesLength = rawValues.reduce(
779
+ (len, value) => len + (instanceofSql(value) ? value.values.length : isColumn(value) || isTable(value) || isView(value) ? 0 : 1),
780
+ 0
781
+ );
782
+ this.values = new Array(valuesLength);
783
+ this.strings = new Array(valuesLength + 1);
784
+ this.strings[0] = rawStrings[0];
785
+ let i = 0, pos = 0;
786
+ while (i < rawValues.length) {
787
+ const child = rawValues[i++];
788
+ const rawString = rawStrings[i];
789
+ if (instanceofSql(child)) {
790
+ this.strings[pos] += child.strings[0];
791
+ let childIndex = 0;
792
+ while (childIndex < child.values.length) {
793
+ this.values[pos++] = child.values[childIndex++];
794
+ this.strings[pos] = child.strings[childIndex];
795
+ }
796
+ this.strings[pos] += rawString;
797
+ } else if (isColumn(child)) {
798
+ const aggregationFunction = child.annotations.find(
799
+ ([k, _]) => k === "aggregationFunction"
800
+ );
801
+ if (aggregationFunction !== void 0) {
802
+ this.strings[pos] += `${aggregationFunction[1].functionName}Merge(\`${child.name}\`)`;
803
+ } else {
804
+ this.strings[pos] += `\`${child.name}\``;
805
+ }
806
+ this.strings[pos] += rawString;
807
+ } else if (isTable(child)) {
808
+ if (child.config.database) {
809
+ this.strings[pos] += `\`${child.config.database}\`.\`${child.name}\``;
810
+ } else {
811
+ this.strings[pos] += `\`${child.name}\``;
812
+ }
813
+ this.strings[pos] += rawString;
814
+ } else if (isView(child)) {
815
+ this.strings[pos] += `\`${child.name}\``;
816
+ this.strings[pos] += rawString;
817
+ } else {
818
+ this.values[pos++] = child;
819
+ this.strings[pos] = rawString;
820
+ }
821
+ }
822
+ }
823
+ /**
824
+ * Append another Sql fragment, returning a new Sql instance.
825
+ */
826
+ append(other) {
827
+ return new _Sql([...this.strings, ""], [...this.values, other]);
828
+ }
829
+ };
830
+ sql.join = function(fragments, separator) {
831
+ if (fragments.length === 0) return new Sql([""], []);
832
+ if (fragments.length === 1) return fragments[0];
833
+ const sep = separator ?? ", ";
834
+ const normalized = sep.includes(" ") ? sep : ` ${sep} `;
835
+ const strings = ["", ...Array(fragments.length - 1).fill(normalized), ""];
836
+ return new Sql(strings, fragments);
837
+ };
838
+ sql.raw = function(text) {
839
+ return new Sql([text], []);
840
+ };
841
+ var toStaticQuery = (sql2) => {
842
+ const [query, params] = toQuery(sql2);
843
+ if (Object.keys(params).length !== 0) {
844
+ throw new Error(
845
+ "Dynamic SQL is not allowed in the select statement in view creation."
846
+ );
847
+ }
848
+ return query;
849
+ };
850
+ var toQuery = (sql2) => {
851
+ const parameterizedStubs = sql2.values.map(
852
+ (v, i) => createClickhouseParameter(i, v)
853
+ );
854
+ const query = sql2.strings.map(
855
+ (s, i) => s != "" ? `${s}${emptyIfUndefined(parameterizedStubs[i])}` : ""
856
+ ).join("");
857
+ const query_params = sql2.values.reduce(
858
+ (acc, v, i) => ({
859
+ ...acc,
860
+ [`p${i}`]: getValueFromParameter(v)
861
+ }),
862
+ {}
863
+ );
864
+ return [query, query_params];
865
+ };
866
+ var toQueryPreview = (sql2) => {
867
+ try {
868
+ const formatValue = (v) => {
869
+ if (Array.isArray(v)) {
870
+ const [type, val] = v;
871
+ if (type === "Identifier") {
872
+ return `\`${String(val)}\``;
873
+ }
874
+ return `[${v.map((x) => formatValue(x)).join(", ")}]`;
875
+ }
876
+ if (v === null || v === void 0) return "NULL";
877
+ if (typeof v === "string") return `'${v.replace(/'/g, "''")}'`;
878
+ if (typeof v === "number") return String(v);
879
+ if (typeof v === "boolean") return v ? "true" : "false";
880
+ if (v instanceof Date)
881
+ return `'${v.toISOString().replace("T", " ").slice(0, 19)}'`;
882
+ try {
883
+ return JSON.stringify(v);
884
+ } catch {
885
+ return String(v);
886
+ }
887
+ };
888
+ let out = sql2.strings[0] ?? "";
889
+ for (let i = 0; i < sql2.values.length; i++) {
890
+ const val = getValueFromParameter(sql2.values[i]);
891
+ out += formatValue(val);
892
+ out += sql2.strings[i + 1] ?? "";
893
+ }
894
+ return out.replace(/\s+/g, " ").trim();
895
+ } catch (error) {
896
+ console.log(`toQueryPreview error: ${error}`);
897
+ return "/* query preview unavailable */";
898
+ }
899
+ };
900
+ var getValueFromParameter = (value) => {
901
+ if (Array.isArray(value)) {
902
+ const [type, val] = value;
903
+ if (type === "Identifier") return val;
904
+ }
905
+ return value;
906
+ };
907
+ function createClickhouseParameter(parameterIndex, value) {
908
+ return `{p${parameterIndex}:${mapToClickHouseType(value)}}`;
909
+ }
910
+ var mapToClickHouseType = (value) => {
911
+ if (typeof value === "number") {
912
+ return Number.isInteger(value) ? "Int" : "Float";
913
+ }
914
+ if (typeof value === "boolean") return "Bool";
915
+ if (value instanceof Date) return "DateTime";
916
+ if (Array.isArray(value)) {
917
+ const [type, _] = value;
918
+ return type;
919
+ }
920
+ return "String";
921
+ };
922
+ function emptyIfUndefined(value) {
923
+ return value === void 0 ? "" : value;
924
+ }
925
+
926
+ // src/dmv2/sdk/olapTable.ts
927
+ var OlapTable = class extends TypedBase {
928
+ name;
929
+ /** @internal */
930
+ kind = "OlapTable";
931
+ /** @internal Memoized ClickHouse client for reusing connections across insert calls */
932
+ _memoizedClient;
933
+ /** @internal Hash of the configuration used to create the memoized client */
934
+ _configHash;
935
+ /** @internal Cached table name to avoid repeated generation */
936
+ _cachedTableName;
937
+ constructor(name, config, schema, columns, validators) {
938
+ const resolvedConfig = config ? "engine" in config ? config : { ...config, engine: "MergeTree" /* MergeTree */ } : { engine: "MergeTree" /* MergeTree */ };
939
+ const hasFields = Array.isArray(resolvedConfig.orderByFields) && resolvedConfig.orderByFields.length > 0;
940
+ const hasExpr = typeof resolvedConfig.orderByExpression === "string" && resolvedConfig.orderByExpression.length > 0;
941
+ if (hasFields && hasExpr) {
942
+ throw new Error(
943
+ `OlapTable ${name}: Provide either orderByFields or orderByExpression, not both.`
944
+ );
945
+ }
946
+ const hasCluster = typeof resolvedConfig.cluster === "string";
947
+ const hasKeeperPath = typeof resolvedConfig.keeperPath === "string";
948
+ const hasReplicaName = typeof resolvedConfig.replicaName === "string";
949
+ if (hasCluster && (hasKeeperPath || hasReplicaName)) {
950
+ throw new Error(
951
+ `OlapTable ${name}: Cannot specify both 'cluster' and explicit replication params ('keeperPath' or 'replicaName'). Use 'cluster' for auto-injected params, or use explicit 'keeperPath' and 'replicaName' without 'cluster'.`
952
+ );
953
+ }
954
+ super(name, resolvedConfig, schema, columns, validators);
955
+ this.name = name;
956
+ const tables = getMooseInternal().tables;
957
+ const registryKey = this.config.version ? `${name}_${this.config.version}` : name;
958
+ if (!isClientOnlyMode() && tables.has(registryKey)) {
959
+ throw new Error(
960
+ `OlapTable with name ${name} and version ${config?.version ?? "unversioned"} already exists`
961
+ );
962
+ }
963
+ tables.set(registryKey, this);
964
+ }
965
+ /**
966
+ * Generates the versioned table name following Moose's naming convention
967
+ * Format: {tableName}_{version_with_dots_replaced_by_underscores}
968
+ */
969
+ generateTableName() {
970
+ if (this._cachedTableName) {
971
+ return this._cachedTableName;
972
+ }
973
+ const tableVersion = this.config.version;
974
+ if (!tableVersion) {
975
+ this._cachedTableName = this.name;
976
+ } else {
977
+ const versionSuffix = tableVersion.replace(/\./g, "_");
978
+ this._cachedTableName = `${this.name}_${versionSuffix}`;
979
+ }
980
+ return this._cachedTableName;
981
+ }
982
+ /**
983
+ * Creates a fast hash of the ClickHouse configuration.
984
+ * Uses crypto.createHash for better performance than JSON.stringify.
985
+ *
986
+ * @private
987
+ */
988
+ createConfigHash(clickhouseConfig) {
989
+ const effectiveDatabase = this.config.database ?? clickhouseConfig.database;
990
+ const configString = `${clickhouseConfig.host}:${clickhouseConfig.port}:${clickhouseConfig.username}:${clickhouseConfig.password}:${effectiveDatabase}:${clickhouseConfig.useSSL}`;
991
+ return createHash("sha256").update(configString).digest("hex").substring(0, 16);
992
+ }
993
+ /**
994
+ * Gets or creates a memoized ClickHouse client.
995
+ * The client is cached and reused across multiple insert calls for better performance.
996
+ * If the configuration changes, a new client will be created.
997
+ *
998
+ * @private
999
+ */
1000
+ async getMemoizedClient() {
1001
+ await Promise.resolve().then(() => (init_runtime(), runtime_exports));
1002
+ const configRegistry = globalThis._mooseConfigRegistry;
1003
+ const { getClickhouseClient: getClickhouseClient2 } = await Promise.resolve().then(() => (init_commons(), commons_exports));
1004
+ const clickhouseConfig = await configRegistry.getClickHouseConfig();
1005
+ const currentConfigHash = this.createConfigHash(clickhouseConfig);
1006
+ if (this._memoizedClient && this._configHash === currentConfigHash) {
1007
+ return { client: this._memoizedClient, config: clickhouseConfig };
1008
+ }
1009
+ if (this._memoizedClient && this._configHash !== currentConfigHash) {
1010
+ try {
1011
+ await this._memoizedClient.close();
1012
+ } catch (error) {
1013
+ }
1014
+ }
1015
+ const effectiveDatabase = this.config.database ?? clickhouseConfig.database;
1016
+ const client = getClickhouseClient2({
1017
+ username: clickhouseConfig.username,
1018
+ password: clickhouseConfig.password,
1019
+ database: effectiveDatabase,
1020
+ useSSL: clickhouseConfig.useSSL ? "true" : "false",
1021
+ host: clickhouseConfig.host,
1022
+ port: clickhouseConfig.port
1023
+ });
1024
+ this._memoizedClient = client;
1025
+ this._configHash = currentConfigHash;
1026
+ return { client, config: clickhouseConfig };
1027
+ }
1028
+ /**
1029
+ * Closes the memoized ClickHouse client if it exists.
1030
+ * This is useful for cleaning up connections when the table instance is no longer needed.
1031
+ * The client will be automatically recreated on the next insert call if needed.
1032
+ */
1033
+ async closeClient() {
1034
+ if (this._memoizedClient) {
1035
+ try {
1036
+ await this._memoizedClient.close();
1037
+ } catch (error) {
1038
+ } finally {
1039
+ this._memoizedClient = void 0;
1040
+ this._configHash = void 0;
1041
+ }
1042
+ }
1043
+ }
1044
+ /**
1045
+ * Validates a single record using typia's comprehensive type checking.
1046
+ * This provides the most accurate validation as it uses the exact TypeScript type information.
1047
+ *
1048
+ * @param record The record to validate
1049
+ * @returns Validation result with detailed error information
1050
+ */
1051
+ validateRecord(record) {
1052
+ if (this.validators?.validate) {
1053
+ try {
1054
+ const result = this.validators.validate(record);
1055
+ return {
1056
+ success: result.success,
1057
+ data: result.data,
1058
+ errors: result.errors?.map(
1059
+ (err) => typeof err === "string" ? err : JSON.stringify(err)
1060
+ )
1061
+ };
1062
+ } catch (error) {
1063
+ return {
1064
+ success: false,
1065
+ errors: [error instanceof Error ? error.message : String(error)]
1066
+ };
1067
+ }
1068
+ }
1069
+ throw new Error("No typia validator found");
1070
+ }
1071
+ /**
1072
+ * Type guard function using typia's is() function.
1073
+ * Provides compile-time type narrowing for TypeScript.
1074
+ *
1075
+ * @param record The record to check
1076
+ * @returns True if record matches type T, with type narrowing
1077
+ */
1078
+ isValidRecord(record) {
1079
+ if (this.validators?.is) {
1080
+ return this.validators.is(record);
1081
+ }
1082
+ throw new Error("No typia validator found");
1083
+ }
1084
+ /**
1085
+ * Assert that a record matches type T, throwing detailed errors if not.
1086
+ * Uses typia's assert() function for the most detailed error reporting.
1087
+ *
1088
+ * @param record The record to assert
1089
+ * @returns The validated and typed record
1090
+ * @throws Detailed validation error if record doesn't match type T
1091
+ */
1092
+ assertValidRecord(record) {
1093
+ if (this.validators?.assert) {
1094
+ return this.validators.assert(record);
1095
+ }
1096
+ throw new Error("No typia validator found");
1097
+ }
1098
+ /**
1099
+ * Validates an array of records with comprehensive error reporting.
1100
+ * Uses the most appropriate validation method available (typia or basic).
1101
+ *
1102
+ * @param data Array of records to validate
1103
+ * @returns Detailed validation results
1104
+ */
1105
+ async validateRecords(data) {
1106
+ const valid = [];
1107
+ const invalid = [];
1108
+ valid.length = 0;
1109
+ invalid.length = 0;
1110
+ const dataLength = data.length;
1111
+ for (let i = 0; i < dataLength; i++) {
1112
+ const record = data[i];
1113
+ try {
1114
+ if (this.isValidRecord(record)) {
1115
+ valid.push(this.mapToClickhouseRecord(record));
1116
+ } else {
1117
+ const result = this.validateRecord(record);
1118
+ if (result.success) {
1119
+ valid.push(this.mapToClickhouseRecord(record));
1120
+ } else {
1121
+ invalid.push({
1122
+ record,
1123
+ error: result.errors?.join(", ") || "Validation failed",
1124
+ index: i,
1125
+ path: "root"
1126
+ });
1127
+ }
1128
+ }
1129
+ } catch (error) {
1130
+ invalid.push({
1131
+ record,
1132
+ error: error instanceof Error ? error.message : String(error),
1133
+ index: i,
1134
+ path: "root"
1135
+ });
1136
+ }
1137
+ }
1138
+ return {
1139
+ valid,
1140
+ invalid,
1141
+ total: dataLength
1142
+ };
1143
+ }
1144
+ /**
1145
+ * Optimized batch retry that minimizes individual insert operations.
1146
+ * Groups records into smaller batches to reduce round trips while still isolating failures.
1147
+ *
1148
+ * @private
1149
+ */
1150
+ async retryIndividualRecords(client, tableName, records) {
1151
+ const successful = [];
1152
+ const failed = [];
1153
+ const RETRY_BATCH_SIZE = 10;
1154
+ const totalRecords = records.length;
1155
+ for (let i = 0; i < totalRecords; i += RETRY_BATCH_SIZE) {
1156
+ const batchEnd = Math.min(i + RETRY_BATCH_SIZE, totalRecords);
1157
+ const batch = records.slice(i, batchEnd);
1158
+ try {
1159
+ await client.insert({
1160
+ table: quoteIdentifier(tableName),
1161
+ values: batch,
1162
+ format: "JSONEachRow",
1163
+ clickhouse_settings: {
1164
+ date_time_input_format: "best_effort",
1165
+ // Add performance settings for retries
1166
+ max_insert_block_size: RETRY_BATCH_SIZE,
1167
+ max_block_size: RETRY_BATCH_SIZE
1168
+ }
1169
+ });
1170
+ successful.push(...batch);
1171
+ } catch (batchError) {
1172
+ for (let j = 0; j < batch.length; j++) {
1173
+ const record = batch[j];
1174
+ try {
1175
+ await client.insert({
1176
+ table: quoteIdentifier(tableName),
1177
+ values: [record],
1178
+ format: "JSONEachRow",
1179
+ clickhouse_settings: {
1180
+ date_time_input_format: "best_effort"
1181
+ }
1182
+ });
1183
+ successful.push(record);
1184
+ } catch (error) {
1185
+ failed.push({
1186
+ record,
1187
+ error: error instanceof Error ? error.message : String(error),
1188
+ index: i + j
1189
+ });
1190
+ }
1191
+ }
1192
+ }
1193
+ }
1194
+ return { successful, failed };
1195
+ }
1196
+ /**
1197
+ * Validates input parameters and strategy compatibility
1198
+ * @private
1199
+ */
1200
+ validateInsertParameters(data, options) {
1201
+ const isStream = data instanceof Readable;
1202
+ const strategy = options?.strategy || "fail-fast";
1203
+ const shouldValidate = options?.validate !== false;
1204
+ if (isStream && strategy === "isolate") {
1205
+ throw new Error(
1206
+ "The 'isolate' error strategy is not supported with stream input. Use 'fail-fast' or 'discard' instead."
1207
+ );
1208
+ }
1209
+ if (isStream && shouldValidate) {
1210
+ console.warn(
1211
+ "Validation is not supported with stream input. Validation will be skipped."
1212
+ );
1213
+ }
1214
+ return { isStream, strategy, shouldValidate };
1215
+ }
1216
+ /**
1217
+ * Handles early return cases for empty data
1218
+ * @private
1219
+ */
1220
+ handleEmptyData(data, isStream) {
1221
+ if (isStream && !data) {
1222
+ return {
1223
+ successful: 0,
1224
+ failed: 0,
1225
+ total: 0
1226
+ };
1227
+ }
1228
+ if (!isStream && (!data || data.length === 0)) {
1229
+ return {
1230
+ successful: 0,
1231
+ failed: 0,
1232
+ total: 0
1233
+ };
1234
+ }
1235
+ return null;
1236
+ }
1237
+ /**
1238
+ * Performs pre-insertion validation for array data
1239
+ * @private
1240
+ */
1241
+ async performPreInsertionValidation(data, shouldValidate, strategy, options) {
1242
+ if (!shouldValidate) {
1243
+ return { validatedData: data, validationErrors: [] };
1244
+ }
1245
+ try {
1246
+ const validationResult = await this.validateRecords(data);
1247
+ const validatedData = validationResult.valid;
1248
+ const validationErrors = validationResult.invalid;
1249
+ if (validationErrors.length > 0) {
1250
+ this.handleValidationErrors(validationErrors, strategy, data, options);
1251
+ switch (strategy) {
1252
+ case "discard":
1253
+ return { validatedData, validationErrors };
1254
+ case "isolate":
1255
+ return { validatedData: data, validationErrors };
1256
+ default:
1257
+ return { validatedData, validationErrors };
1258
+ }
1259
+ }
1260
+ return { validatedData, validationErrors };
1261
+ } catch (validationError) {
1262
+ if (strategy === "fail-fast") {
1263
+ throw validationError;
1264
+ }
1265
+ console.warn("Validation error:", validationError);
1266
+ return { validatedData: data, validationErrors: [] };
1267
+ }
1268
+ }
1269
+ /**
1270
+ * Handles validation errors based on the specified strategy
1271
+ * @private
1272
+ */
1273
+ handleValidationErrors(validationErrors, strategy, data, options) {
1274
+ switch (strategy) {
1275
+ case "fail-fast":
1276
+ const firstError = validationErrors[0];
1277
+ throw new Error(
1278
+ `Validation failed for record at index ${firstError.index}: ${firstError.error}`
1279
+ );
1280
+ case "discard":
1281
+ this.checkValidationThresholds(validationErrors, data.length, options);
1282
+ break;
1283
+ case "isolate":
1284
+ break;
1285
+ }
1286
+ }
1287
+ /**
1288
+ * Checks if validation errors exceed configured thresholds
1289
+ * @private
1290
+ */
1291
+ checkValidationThresholds(validationErrors, totalRecords, options) {
1292
+ const validationFailedCount = validationErrors.length;
1293
+ const validationFailedRatio = validationFailedCount / totalRecords;
1294
+ if (options?.allowErrors !== void 0 && validationFailedCount > options.allowErrors) {
1295
+ throw new Error(
1296
+ `Too many validation failures: ${validationFailedCount} > ${options.allowErrors}. Errors: ${validationErrors.map((e) => e.error).join(", ")}`
1297
+ );
1298
+ }
1299
+ if (options?.allowErrorsRatio !== void 0 && validationFailedRatio > options.allowErrorsRatio) {
1300
+ throw new Error(
1301
+ `Validation failure ratio too high: ${validationFailedRatio.toFixed(3)} > ${options.allowErrorsRatio}. Errors: ${validationErrors.map((e) => e.error).join(", ")}`
1302
+ );
1303
+ }
1304
+ }
1305
+ /**
1306
+ * Optimized insert options preparation with better memory management
1307
+ * @private
1308
+ */
1309
+ prepareInsertOptions(tableName, data, validatedData, isStream, strategy, options) {
1310
+ const insertOptions = {
1311
+ table: quoteIdentifier(tableName),
1312
+ format: "JSONEachRow",
1313
+ clickhouse_settings: {
1314
+ date_time_input_format: "best_effort",
1315
+ wait_end_of_query: 1,
1316
+ // Ensure at least once delivery for INSERT operations
1317
+ // Performance optimizations
1318
+ max_insert_block_size: isStream ? 1e5 : Math.min(validatedData.length, 1e5),
1319
+ max_block_size: 65536,
1320
+ // Use async inserts for better performance with large datasets
1321
+ async_insert: validatedData.length > 1e3 ? 1 : 0,
1322
+ wait_for_async_insert: 1
1323
+ // For at least once delivery
1324
+ }
1325
+ };
1326
+ if (isStream) {
1327
+ insertOptions.values = data;
1328
+ } else {
1329
+ insertOptions.values = validatedData;
1330
+ }
1331
+ if (strategy === "discard" && (options?.allowErrors !== void 0 || options?.allowErrorsRatio !== void 0)) {
1332
+ if (options.allowErrors !== void 0) {
1333
+ insertOptions.clickhouse_settings.input_format_allow_errors_num = options.allowErrors;
1334
+ }
1335
+ if (options.allowErrorsRatio !== void 0) {
1336
+ insertOptions.clickhouse_settings.input_format_allow_errors_ratio = options.allowErrorsRatio;
1337
+ }
1338
+ }
1339
+ return insertOptions;
1340
+ }
1341
+ /**
1342
+ * Creates success result for completed insertions
1343
+ * @private
1344
+ */
1345
+ createSuccessResult(data, validatedData, validationErrors, isStream, shouldValidate, strategy) {
1346
+ if (isStream) {
1347
+ return {
1348
+ successful: -1,
1349
+ // -1 indicates stream mode where count is unknown
1350
+ failed: 0,
1351
+ total: -1
1352
+ };
1353
+ }
1354
+ const insertedCount = validatedData.length;
1355
+ const totalProcessed = shouldValidate ? data.length : insertedCount;
1356
+ const result = {
1357
+ successful: insertedCount,
1358
+ failed: shouldValidate ? validationErrors.length : 0,
1359
+ total: totalProcessed
1360
+ };
1361
+ if (shouldValidate && validationErrors.length > 0 && strategy === "discard") {
1362
+ result.failedRecords = validationErrors.map((ve) => ({
1363
+ record: ve.record,
1364
+ error: `Validation error: ${ve.error}`,
1365
+ index: ve.index
1366
+ }));
1367
+ }
1368
+ return result;
1369
+ }
1370
+ /**
1371
+ * Handles insertion errors based on the specified strategy
1372
+ * @private
1373
+ */
1374
+ async handleInsertionError(batchError, strategy, tableName, data, validatedData, validationErrors, isStream, shouldValidate, options) {
1375
+ switch (strategy) {
1376
+ case "fail-fast":
1377
+ throw new Error(
1378
+ `Failed to insert data into table ${tableName}: ${batchError}`
1379
+ );
1380
+ case "discard":
1381
+ throw new Error(
1382
+ `Too many errors during insert into table ${tableName}. Error threshold exceeded: ${batchError}`
1383
+ );
1384
+ case "isolate":
1385
+ return await this.handleIsolateStrategy(
1386
+ batchError,
1387
+ tableName,
1388
+ data,
1389
+ validatedData,
1390
+ validationErrors,
1391
+ isStream,
1392
+ shouldValidate,
1393
+ options
1394
+ );
1395
+ default:
1396
+ throw new Error(`Unknown error strategy: ${strategy}`);
1397
+ }
1398
+ }
1399
+ /**
1400
+ * Handles the isolate strategy for insertion errors
1401
+ * @private
1402
+ */
1403
+ async handleIsolateStrategy(batchError, tableName, data, validatedData, validationErrors, isStream, shouldValidate, options) {
1404
+ if (isStream) {
1405
+ throw new Error(
1406
+ `Isolate strategy is not supported with stream input: ${batchError}`
1407
+ );
1408
+ }
1409
+ try {
1410
+ const { client } = await this.getMemoizedClient();
1411
+ const skipValidationOnRetry = options?.skipValidationOnRetry || false;
1412
+ const retryData = skipValidationOnRetry ? data : validatedData;
1413
+ const { successful, failed } = await this.retryIndividualRecords(
1414
+ client,
1415
+ tableName,
1416
+ retryData
1417
+ );
1418
+ const allFailedRecords = [
1419
+ // Validation errors (if any and not skipping validation on retry)
1420
+ ...shouldValidate && !skipValidationOnRetry ? validationErrors.map((ve) => ({
1421
+ record: ve.record,
1422
+ error: `Validation error: ${ve.error}`,
1423
+ index: ve.index
1424
+ })) : [],
1425
+ // Insertion errors
1426
+ ...failed
1427
+ ];
1428
+ this.checkInsertionThresholds(
1429
+ allFailedRecords,
1430
+ data.length,
1431
+ options
1432
+ );
1433
+ return {
1434
+ successful: successful.length,
1435
+ failed: allFailedRecords.length,
1436
+ total: data.length,
1437
+ failedRecords: allFailedRecords
1438
+ };
1439
+ } catch (isolationError) {
1440
+ throw new Error(
1441
+ `Failed to insert data into table ${tableName} during record isolation: ${isolationError}`
1442
+ );
1443
+ }
1444
+ }
1445
+ /**
1446
+ * Checks if insertion errors exceed configured thresholds
1447
+ * @private
1448
+ */
1449
+ checkInsertionThresholds(failedRecords, totalRecords, options) {
1450
+ const totalFailed = failedRecords.length;
1451
+ const failedRatio = totalFailed / totalRecords;
1452
+ if (options?.allowErrors !== void 0 && totalFailed > options.allowErrors) {
1453
+ throw new Error(
1454
+ `Too many failed records: ${totalFailed} > ${options.allowErrors}. Failed records: ${failedRecords.map((f) => f.error).join(", ")}`
1455
+ );
1456
+ }
1457
+ if (options?.allowErrorsRatio !== void 0 && failedRatio > options.allowErrorsRatio) {
1458
+ throw new Error(
1459
+ `Failed record ratio too high: ${failedRatio.toFixed(3)} > ${options.allowErrorsRatio}. Failed records: ${failedRecords.map((f) => f.error).join(", ")}`
1460
+ );
1461
+ }
1462
+ }
1463
+ /**
1464
+ * Recursively transforms a record to match ClickHouse's JSONEachRow requirements
1465
+ *
1466
+ * - For every Array(Nested(...)) field at any depth, each item is wrapped in its own array and recursively processed.
1467
+ * - For every Nested struct (not array), it recurses into the struct.
1468
+ * - This ensures compatibility with kafka_clickhouse_sync
1469
+ *
1470
+ * @param record The input record to transform (may be deeply nested)
1471
+ * @param columns The schema columns for this level (defaults to this.columnArray at the top level)
1472
+ * @returns The transformed record, ready for ClickHouse JSONEachRow insertion
1473
+ */
1474
+ mapToClickhouseRecord(record, columns = this.columnArray) {
1475
+ const result = { ...record };
1476
+ for (const col of columns) {
1477
+ const value = record[col.name];
1478
+ const dt = col.data_type;
1479
+ if (isArrayNestedType(dt)) {
1480
+ if (Array.isArray(value) && (value.length === 0 || typeof value[0] === "object")) {
1481
+ result[col.name] = value.map((item) => [
1482
+ this.mapToClickhouseRecord(item, dt.elementType.columns)
1483
+ ]);
1484
+ }
1485
+ } else if (isNestedType(dt)) {
1486
+ if (value && typeof value === "object") {
1487
+ result[col.name] = this.mapToClickhouseRecord(value, dt.columns);
1488
+ }
1489
+ }
1490
+ }
1491
+ return result;
1492
+ }
1493
+ /**
1494
+ * Inserts data directly into the ClickHouse table with enhanced error handling and validation.
1495
+ * This method establishes a direct connection to ClickHouse using the project configuration
1496
+ * and inserts the provided data into the versioned table.
1497
+ *
1498
+ * PERFORMANCE OPTIMIZATIONS:
1499
+ * - Memoized client connections with fast config hashing
1500
+ * - Single-pass validation with pre-allocated arrays
1501
+ * - Batch-optimized retry strategy (batches of 10, then individual)
1502
+ * - Optimized ClickHouse settings for large datasets
1503
+ * - Reduced memory allocations and object creation
1504
+ *
1505
+ * Uses advanced typia validation when available for comprehensive type checking,
1506
+ * with fallback to basic validation for compatibility.
1507
+ *
1508
+ * The ClickHouse client is memoized and reused across multiple insert calls for better performance.
1509
+ * If the configuration changes, a new client will be automatically created.
1510
+ *
1511
+ * @param data Array of objects conforming to the table schema, or a Node.js Readable stream
1512
+ * @param options Optional configuration for error handling, validation, and insertion behavior
1513
+ * @returns Promise resolving to detailed insertion results
1514
+ * @throws {ConfigError} When configuration cannot be read or parsed
1515
+ * @throws {ClickHouseError} When insertion fails based on the error strategy
1516
+ * @throws {ValidationError} When validation fails and strategy is 'fail-fast'
1517
+ *
1518
+ * @example
1519
+ * ```typescript
1520
+ * // Create an OlapTable instance (typia validators auto-injected)
1521
+ * const userTable = new OlapTable<User>('users');
1522
+ *
1523
+ * // Insert with comprehensive typia validation
1524
+ * const result1 = await userTable.insert([
1525
+ * { id: 1, name: 'John', email: 'john@example.com' },
1526
+ * { id: 2, name: 'Jane', email: 'jane@example.com' }
1527
+ * ]);
1528
+ *
1529
+ * // Insert data with stream input (validation not available for streams)
1530
+ * const dataStream = new Readable({
1531
+ * objectMode: true,
1532
+ * read() { // Stream implementation }
1533
+ * });
1534
+ * const result2 = await userTable.insert(dataStream, { strategy: 'fail-fast' });
1535
+ *
1536
+ * // Insert with validation disabled for performance
1537
+ * const result3 = await userTable.insert(data, { validate: false });
1538
+ *
1539
+ * // Insert with error handling strategies
1540
+ * const result4 = await userTable.insert(mixedData, {
1541
+ * strategy: 'isolate',
1542
+ * allowErrorsRatio: 0.1,
1543
+ * validate: true // Use typia validation (default)
1544
+ * });
1545
+ *
1546
+ * // Optional: Clean up connection when completely done
1547
+ * await userTable.closeClient();
1548
+ * ```
1549
+ */
1550
+ async insert(data, options) {
1551
+ const { isStream, strategy, shouldValidate } = this.validateInsertParameters(data, options);
1552
+ const emptyResult = this.handleEmptyData(data, isStream);
1553
+ if (emptyResult) {
1554
+ return emptyResult;
1555
+ }
1556
+ let validatedData = [];
1557
+ let validationErrors = [];
1558
+ if (!isStream && shouldValidate) {
1559
+ const validationResult = await this.performPreInsertionValidation(
1560
+ data,
1561
+ shouldValidate,
1562
+ strategy,
1563
+ options
1564
+ );
1565
+ validatedData = validationResult.validatedData;
1566
+ validationErrors = validationResult.validationErrors;
1567
+ } else {
1568
+ validatedData = isStream ? [] : data;
1569
+ }
1570
+ const { client } = await this.getMemoizedClient();
1571
+ const tableName = this.generateTableName();
1572
+ try {
1573
+ const insertOptions = this.prepareInsertOptions(
1574
+ tableName,
1575
+ data,
1576
+ validatedData,
1577
+ isStream,
1578
+ strategy,
1579
+ options
1580
+ );
1581
+ await client.insert(insertOptions);
1582
+ return this.createSuccessResult(
1583
+ data,
1584
+ validatedData,
1585
+ validationErrors,
1586
+ isStream,
1587
+ shouldValidate,
1588
+ strategy
1589
+ );
1590
+ } catch (batchError) {
1591
+ return await this.handleInsertionError(
1592
+ batchError,
1593
+ strategy,
1594
+ tableName,
1595
+ data,
1596
+ validatedData,
1597
+ validationErrors,
1598
+ isStream,
1599
+ shouldValidate,
1600
+ options
1601
+ );
1602
+ }
1603
+ }
1604
+ // Note: Static factory methods (withS3Queue, withReplacingMergeTree, withMergeTree)
1605
+ // were removed in ENG-856. Use direct configuration instead, e.g.:
1606
+ // new OlapTable(name, { engine: ClickHouseEngines.ReplacingMergeTree, orderByFields: ["id"], ver: "updated_at" })
1607
+ };
1608
+
1609
+ // src/dmv2/sdk/stream.ts
1610
+ import { createHash as createHash2 } from "crypto";
1611
+ var RoutedMessage = class {
1612
+ /** The destination stream for the message */
1613
+ destination;
1614
+ /** The message value(s) to send */
1615
+ values;
1616
+ /**
1617
+ * Creates a new routed message.
1618
+ *
1619
+ * @param destination The target stream
1620
+ * @param values The message(s) to route
1621
+ */
1622
+ constructor(destination, values) {
1623
+ this.destination = destination;
1624
+ this.values = values;
1625
+ }
1626
+ };
1627
+ var Stream = class extends TypedBase {
1628
+ defaultDeadLetterQueue;
1629
+ /** @internal Memoized KafkaJS producer for reusing connections across sends */
1630
+ _memoizedProducer;
1631
+ /** @internal Hash of the configuration used to create the memoized Kafka producer */
1632
+ _kafkaConfigHash;
1633
+ constructor(name, config, schema, columns, validators, allowExtraFields) {
1634
+ super(name, config ?? {}, schema, columns, void 0, allowExtraFields);
1635
+ const streams = getMooseInternal().streams;
1636
+ if (streams.has(name)) {
1637
+ throw new Error(`Stream with name ${name} already exists`);
1638
+ }
1639
+ streams.set(name, this);
1640
+ this.defaultDeadLetterQueue = this.config.defaultDeadLetterQueue;
1641
+ }
1642
+ /**
1643
+ * Internal map storing transformation configurations.
1644
+ * Maps destination stream names to arrays of transformation functions and their configs.
1645
+ *
1646
+ * @internal
1647
+ */
1648
+ _transformations = /* @__PURE__ */ new Map();
1649
+ /**
1650
+ * Internal function for multi-stream transformations.
1651
+ * Allows a single transformation to route messages to multiple destinations.
1652
+ *
1653
+ * @internal
1654
+ */
1655
+ _multipleTransformations;
1656
+ /**
1657
+ * Internal array storing consumer configurations.
1658
+ *
1659
+ * @internal
1660
+ */
1661
+ _consumers = [];
1662
+ /**
1663
+ * Builds the full Kafka topic name including optional namespace and version suffix.
1664
+ * Version suffix is appended as _x_y_z where dots in version are replaced with underscores.
1665
+ */
1666
+ buildFullTopicName(namespace) {
1667
+ const versionSuffix = this.config.version ? `_${this.config.version.replace(/\./g, "_")}` : "";
1668
+ const base = `${this.name}${versionSuffix}`;
1669
+ return namespace !== void 0 && namespace.length > 0 ? `${namespace}.${base}` : base;
1670
+ }
1671
+ /**
1672
+ * Creates a fast hash string from relevant Kafka configuration fields.
1673
+ */
1674
+ createConfigHash(kafkaConfig) {
1675
+ const configString = [
1676
+ kafkaConfig.broker,
1677
+ kafkaConfig.messageTimeoutMs,
1678
+ kafkaConfig.saslUsername,
1679
+ kafkaConfig.saslPassword,
1680
+ kafkaConfig.saslMechanism,
1681
+ kafkaConfig.securityProtocol,
1682
+ kafkaConfig.namespace
1683
+ ].join(":");
1684
+ return createHash2("sha256").update(configString).digest("hex").substring(0, 16);
1685
+ }
1686
+ /**
1687
+ * Gets or creates a memoized KafkaJS producer using runtime configuration.
1688
+ */
1689
+ async getMemoizedProducer() {
1690
+ await Promise.resolve().then(() => (init_runtime(), runtime_exports));
1691
+ const configRegistry = globalThis._mooseConfigRegistry;
1692
+ const { getKafkaProducer: getKafkaProducer2 } = await Promise.resolve().then(() => (init_commons(), commons_exports));
1693
+ const kafkaConfig = await configRegistry.getKafkaConfig();
1694
+ const currentHash = this.createConfigHash(kafkaConfig);
1695
+ if (this._memoizedProducer && this._kafkaConfigHash === currentHash) {
1696
+ return { producer: this._memoizedProducer, kafkaConfig };
1697
+ }
1698
+ if (this._memoizedProducer && this._kafkaConfigHash !== currentHash) {
1699
+ try {
1700
+ await this._memoizedProducer.disconnect();
1701
+ } catch {
1702
+ }
1703
+ this._memoizedProducer = void 0;
1704
+ }
1705
+ const clientId = `moose-sdk-stream-${this.name}`;
1706
+ const logger = {
1707
+ logPrefix: clientId,
1708
+ log: (message) => {
1709
+ console.log(`${clientId}: ${message}`);
1710
+ },
1711
+ error: (message) => {
1712
+ console.error(`${clientId}: ${message}`);
1713
+ },
1714
+ warn: (message) => {
1715
+ console.warn(`${clientId}: ${message}`);
1716
+ }
1717
+ };
1718
+ const producer = await getKafkaProducer2(
1719
+ {
1720
+ clientId,
1721
+ broker: kafkaConfig.broker,
1722
+ securityProtocol: kafkaConfig.securityProtocol,
1723
+ saslUsername: kafkaConfig.saslUsername,
1724
+ saslPassword: kafkaConfig.saslPassword,
1725
+ saslMechanism: kafkaConfig.saslMechanism
1726
+ },
1727
+ logger
1728
+ );
1729
+ this._memoizedProducer = producer;
1730
+ this._kafkaConfigHash = currentHash;
1731
+ return { producer, kafkaConfig };
1732
+ }
1733
+ /**
1734
+ * Closes the memoized Kafka producer if it exists.
1735
+ */
1736
+ async closeProducer() {
1737
+ if (this._memoizedProducer) {
1738
+ try {
1739
+ await this._memoizedProducer.disconnect();
1740
+ } catch {
1741
+ } finally {
1742
+ this._memoizedProducer = void 0;
1743
+ this._kafkaConfigHash = void 0;
1744
+ }
1745
+ }
1746
+ }
1747
+ /**
1748
+ * Sends one or more records to this stream's Kafka topic.
1749
+ * Values are JSON-serialized as message values.
1750
+ */
1751
+ async send(values) {
1752
+ const flat = Array.isArray(values) ? values : values !== void 0 && values !== null ? [values] : [];
1753
+ if (flat.length === 0) return;
1754
+ const { producer, kafkaConfig } = await this.getMemoizedProducer();
1755
+ const topic = this.buildFullTopicName(kafkaConfig.namespace);
1756
+ const sr = this.config.schemaConfig;
1757
+ if (sr && sr.kind === "JSON") {
1758
+ const schemaRegistryUrl = kafkaConfig.schemaRegistryUrl;
1759
+ if (!schemaRegistryUrl) {
1760
+ throw new Error("Schema Registry URL not configured");
1761
+ }
1762
+ const {
1763
+ default: { SchemaRegistry }
1764
+ } = await import("@kafkajs/confluent-schema-registry");
1765
+ const registry = new SchemaRegistry({ host: schemaRegistryUrl });
1766
+ let schemaId;
1767
+ if ("id" in sr.reference) {
1768
+ schemaId = sr.reference.id;
1769
+ } else if ("subjectLatest" in sr.reference) {
1770
+ schemaId = await registry.getLatestSchemaId(sr.reference.subjectLatest);
1771
+ } else if ("subject" in sr.reference) {
1772
+ schemaId = await registry.getRegistryId(sr.reference.subject, sr.reference.version);
1773
+ }
1774
+ if (schemaId === void 0) {
1775
+ throw new Error("Malformed schema reference.");
1776
+ }
1777
+ const encoded = await Promise.all(
1778
+ flat.map((v) => registry.encode(schemaId, v))
1779
+ );
1780
+ await producer.send({
1781
+ topic,
1782
+ messages: encoded.map((value) => ({ value }))
1783
+ });
1784
+ return;
1785
+ } else if (sr !== void 0) {
1786
+ throw new Error("Currently only JSON Schema is supported.");
1787
+ }
1788
+ await producer.send({
1789
+ topic,
1790
+ messages: flat.map((v) => ({ value: JSON.stringify(v) }))
1791
+ });
1792
+ }
1793
+ /**
1794
+ * Adds a transformation step that processes messages from this stream and sends the results to a destination stream.
1795
+ * Multiple transformations to the same destination stream can be added if they have distinct `version` identifiers in their config.
1796
+ *
1797
+ * @template U The data type of the messages in the destination stream.
1798
+ * @param destination The destination stream for the transformed messages.
1799
+ * @param transformation A function that takes a message of type T and returns zero or more messages of type U (or a Promise thereof).
1800
+ * Return `null` or `undefined` or an empty array `[]` to filter out a message. Return an array to emit multiple messages.
1801
+ * @param config Optional configuration for this specific transformation step, like a version.
1802
+ */
1803
+ addTransform(destination, transformation, config) {
1804
+ const sourceFile = getSourceFileFromStack(new Error().stack);
1805
+ const transformConfig = {
1806
+ ...config ?? {},
1807
+ sourceFile
1808
+ };
1809
+ if (transformConfig.deadLetterQueue === void 0) {
1810
+ transformConfig.deadLetterQueue = this.defaultDeadLetterQueue;
1811
+ }
1812
+ if (this._transformations.has(destination.name)) {
1813
+ const existingTransforms = this._transformations.get(destination.name);
1814
+ const hasVersion = existingTransforms.some(
1815
+ ([_, __, cfg]) => cfg.version === transformConfig.version
1816
+ );
1817
+ if (!hasVersion) {
1818
+ existingTransforms.push([destination, transformation, transformConfig]);
1819
+ }
1820
+ } else {
1821
+ this._transformations.set(destination.name, [[destination, transformation, transformConfig]]);
1822
+ }
1823
+ }
1824
+ /**
1825
+ * Adds a consumer function that processes messages from this stream.
1826
+ * Multiple consumers can be added if they have distinct `version` identifiers in their config.
1827
+ *
1828
+ * @param consumer A function that takes a message of type T and performs an action (e.g., side effect, logging). Should return void or Promise<void>.
1829
+ * @param config Optional configuration for this specific consumer, like a version.
1830
+ */
1831
+ addConsumer(consumer, config) {
1832
+ const sourceFile = getSourceFileFromStack(new Error().stack);
1833
+ const consumerConfig = {
1834
+ ...config ?? {},
1835
+ sourceFile
1836
+ };
1837
+ if (consumerConfig.deadLetterQueue === void 0) {
1838
+ consumerConfig.deadLetterQueue = this.defaultDeadLetterQueue;
1839
+ }
1840
+ const hasVersion = this._consumers.some(
1841
+ (existing) => existing.config.version === consumerConfig.version
1842
+ );
1843
+ if (!hasVersion) {
1844
+ this._consumers.push({ consumer, config: consumerConfig });
1845
+ }
1846
+ }
1847
+ /**
1848
+ * Helper method for `addMultiTransform` to specify the destination and values for a routed message.
1849
+ * @param values The value or values to send to this stream.
1850
+ * @returns A `RoutedMessage` object associating the values with this stream.
1851
+ *
1852
+ * @example
1853
+ * ```typescript
1854
+ * sourceStream.addMultiTransform((record) => [
1855
+ * destinationStream1.routed(transformedRecord1),
1856
+ * destinationStream2.routed([record2a, record2b])
1857
+ * ]);
1858
+ * ```
1859
+ */
1860
+ routed = (values) => new RoutedMessage(this, values);
1861
+ /**
1862
+ * Adds a single transformation function that can route messages to multiple destination streams.
1863
+ * This is an alternative to adding multiple individual `addTransform` calls.
1864
+ * Only one multi-transform function can be added per stream.
1865
+ *
1866
+ * @param transformation A function that takes a message of type T and returns an array of `RoutedMessage` objects,
1867
+ * each specifying a destination stream and the message(s) to send to it.
1868
+ */
1869
+ addMultiTransform(transformation) {
1870
+ this._multipleTransformations = transformation;
1871
+ }
1872
+ };
1873
+ function attachTypeGuard(dl, typeGuard) {
1874
+ dl.asTyped = () => typeGuard(dl.originalRecord);
1875
+ }
1876
+ var DeadLetterQueue = class extends Stream {
1877
+ constructor(name, config, typeGuard) {
1878
+ if (typeGuard === void 0) {
1879
+ throw new Error(
1880
+ "Supply the type param T so that the schema is inserted by the compiler plugin."
1881
+ );
1882
+ }
1883
+ super(name, config ?? {}, dlqSchema, dlqColumns, void 0, false);
1884
+ this.typeGuard = typeGuard;
1885
+ getMooseInternal().streams.set(name, this);
1886
+ }
1887
+ /**
1888
+ * Internal type guard function for validating and casting original records.
1889
+ *
1890
+ * @internal
1891
+ */
1892
+ typeGuard;
1893
+ /**
1894
+ * Adds a transformation step for dead letter records.
1895
+ * The transformation function receives a DeadLetter<T> with type recovery capabilities.
1896
+ *
1897
+ * @template U The output type for the transformation
1898
+ * @param destination The destination stream for transformed messages
1899
+ * @param transformation Function to transform dead letter records
1900
+ * @param config Optional transformation configuration
1901
+ */
1902
+ addTransform(destination, transformation, config) {
1903
+ const withValidate = (deadLetter) => {
1904
+ attachTypeGuard(deadLetter, this.typeGuard);
1905
+ return transformation(deadLetter);
1906
+ };
1907
+ super.addTransform(destination, withValidate, config);
1908
+ }
1909
+ /**
1910
+ * Adds a consumer for dead letter records.
1911
+ * The consumer function receives a DeadLetter<T> with type recovery capabilities.
1912
+ *
1913
+ * @param consumer Function to process dead letter records
1914
+ * @param config Optional consumer configuration
1915
+ */
1916
+ addConsumer(consumer, config) {
1917
+ const withValidate = (deadLetter) => {
1918
+ attachTypeGuard(deadLetter, this.typeGuard);
1919
+ return consumer(deadLetter);
1920
+ };
1921
+ super.addConsumer(withValidate, config);
1922
+ }
1923
+ /**
1924
+ * Adds a multi-stream transformation for dead letter records.
1925
+ * The transformation function receives a DeadLetter<T> with type recovery capabilities.
1926
+ *
1927
+ * @param transformation Function to route dead letter records to multiple destinations
1928
+ */
1929
+ addMultiTransform(transformation) {
1930
+ const withValidate = (deadLetter) => {
1931
+ attachTypeGuard(deadLetter, this.typeGuard);
1932
+ return transformation(deadLetter);
1933
+ };
1934
+ super.addMultiTransform(withValidate);
1935
+ }
1936
+ };
1937
+
1938
+ // src/dmv2/sdk/workflow.ts
1939
+ var Task = class {
1940
+ /**
1941
+ * Creates a new Task instance.
1942
+ *
1943
+ * @param name - Unique identifier for the task
1944
+ * @param config - Configuration object defining the task behavior
1945
+ *
1946
+ * @example
1947
+ * ```typescript
1948
+ * // No input, no output
1949
+ * const task1 = new Task<null, void>("task1", {
1950
+ * run: async () => {
1951
+ * console.log("No input/output");
1952
+ * }
1953
+ * });
1954
+ *
1955
+ * // No input, but has output
1956
+ * const task2 = new Task<null, OutputType>("task2", {
1957
+ * run: async () => {
1958
+ * return someOutput;
1959
+ * }
1960
+ * });
1961
+ *
1962
+ * // Has input, no output
1963
+ * const task3 = new Task<InputType, void>("task3", {
1964
+ * run: async (input: InputType) => {
1965
+ * // process input but return nothing
1966
+ * }
1967
+ * });
1968
+ *
1969
+ * // Has both input and output
1970
+ * const task4 = new Task<InputType, OutputType>("task4", {
1971
+ * run: async (input: InputType) => {
1972
+ * return process(input);
1973
+ * }
1974
+ * });
1975
+ * ```
1976
+ */
1977
+ constructor(name, config) {
1978
+ this.name = name;
1979
+ this.config = config;
1980
+ }
1981
+ };
1982
+ var Workflow = class {
1983
+ /**
1984
+ * Creates a new Workflow instance and registers it with the Moose system.
1985
+ *
1986
+ * @param name - Unique identifier for the workflow
1987
+ * @param config - Configuration object defining the workflow behavior and task orchestration
1988
+ * @throws {Error} When the workflow contains null/undefined tasks or infinite loops
1989
+ */
1990
+ constructor(name, config) {
1991
+ this.name = name;
1992
+ this.config = config;
1993
+ const workflows = getMooseInternal().workflows;
1994
+ if (workflows.has(name)) {
1995
+ throw new Error(`Workflow with name ${name} already exists`);
1996
+ }
1997
+ this.validateTaskGraph(config.startingTask, name);
1998
+ workflows.set(name, this);
1999
+ }
2000
+ /**
2001
+ * Validates the task graph to ensure there are no null tasks or infinite loops.
2002
+ *
2003
+ * @private
2004
+ * @param startingTask - The starting task to begin validation from
2005
+ * @param workflowName - The name of the workflow being validated (for error messages)
2006
+ * @throws {Error} When null/undefined tasks are found or infinite loops are detected
2007
+ */
2008
+ validateTaskGraph(startingTask, workflowName) {
2009
+ if (startingTask === null || startingTask === void 0) {
2010
+ throw new Error(
2011
+ `Workflow "${workflowName}" has a null or undefined starting task`
2012
+ );
2013
+ }
2014
+ const visited = /* @__PURE__ */ new Set();
2015
+ const recursionStack = /* @__PURE__ */ new Set();
2016
+ const validateTask = (task, currentPath) => {
2017
+ if (task === null || task === void 0) {
2018
+ const pathStr = currentPath.length > 0 ? currentPath.join(" -> ") + " -> " : "";
2019
+ throw new Error(
2020
+ `Workflow "${workflowName}" contains a null or undefined task in the task chain: ${pathStr}null`
2021
+ );
2022
+ }
2023
+ const taskName = task.name;
2024
+ if (recursionStack.has(taskName)) {
2025
+ const cycleStartIndex = currentPath.indexOf(taskName);
2026
+ const cyclePath = cycleStartIndex >= 0 ? currentPath.slice(cycleStartIndex).concat(taskName) : currentPath.concat(taskName);
2027
+ throw new Error(
2028
+ `Workflow "${workflowName}" contains an infinite loop in task chain: ${cyclePath.join(" -> ")}`
2029
+ );
2030
+ }
2031
+ if (visited.has(taskName)) {
2032
+ return;
2033
+ }
2034
+ visited.add(taskName);
2035
+ recursionStack.add(taskName);
2036
+ if (task.config.onComplete) {
2037
+ for (const nextTask of task.config.onComplete) {
2038
+ validateTask(nextTask, [...currentPath, taskName]);
2039
+ }
2040
+ }
2041
+ recursionStack.delete(taskName);
2042
+ };
2043
+ validateTask(startingTask, []);
2044
+ }
2045
+ };
2046
+
2047
+ // src/dmv2/sdk/ingestApi.ts
2048
+ var IngestApi = class extends TypedBase {
2049
+ constructor(name, config, schema, columns, validators, allowExtraFields) {
2050
+ super(name, config, schema, columns, void 0, allowExtraFields);
2051
+ const ingestApis = getMooseInternal().ingestApis;
2052
+ if (ingestApis.has(name)) {
2053
+ throw new Error(`Ingest API with name ${name} already exists`);
2054
+ }
2055
+ ingestApis.set(name, this);
2056
+ }
2057
+ };
2058
+
2059
+ // src/dmv2/sdk/consumptionApi.ts
2060
+ var Api = class extends TypedBase {
2061
+ /** @internal The handler function that processes requests and generates responses. */
2062
+ _handler;
2063
+ /** @internal The JSON schema definition for the response type R. */
2064
+ responseSchema;
2065
+ constructor(name, handler, config, schema, columns, responseSchema) {
2066
+ super(name, config ?? {}, schema, columns);
2067
+ this._handler = handler;
2068
+ this.responseSchema = responseSchema ?? {
2069
+ version: "3.1",
2070
+ schemas: [{ type: "array", items: { type: "object" } }],
2071
+ components: { schemas: {} }
2072
+ };
2073
+ const apis = getMooseInternal().apis;
2074
+ const key = `${name}${config?.version ? `:${config.version}` : ""}`;
2075
+ if (apis.has(key)) {
2076
+ throw new Error(
2077
+ `Consumption API with name ${name} and version ${config?.version} already exists`
2078
+ );
2079
+ }
2080
+ apis.set(key, this);
2081
+ if (config?.path) {
2082
+ if (config.version) {
2083
+ const pathEndsWithVersion = config.path.endsWith(`/${config.version}`) || config.path === config.version || config.path.endsWith(config.version) && config.path.length > config.version.length && config.path[config.path.length - config.version.length - 1] === "/";
2084
+ if (pathEndsWithVersion) {
2085
+ if (apis.has(config.path)) {
2086
+ const existing = apis.get(config.path);
2087
+ throw new Error(
2088
+ `Cannot register API "${name}" with path "${config.path}" - this path is already used by API "${existing.name}"`
2089
+ );
2090
+ }
2091
+ apis.set(config.path, this);
2092
+ } else {
2093
+ const versionedPath = `${config.path.replace(/\/$/, "")}/${config.version}`;
2094
+ if (apis.has(versionedPath)) {
2095
+ const existing = apis.get(versionedPath);
2096
+ throw new Error(
2097
+ `Cannot register API "${name}" with path "${versionedPath}" - this path is already used by API "${existing.name}"`
2098
+ );
2099
+ }
2100
+ apis.set(versionedPath, this);
2101
+ if (!apis.has(config.path)) {
2102
+ apis.set(config.path, this);
2103
+ }
2104
+ }
2105
+ } else {
2106
+ if (apis.has(config.path)) {
2107
+ const existing = apis.get(config.path);
2108
+ throw new Error(
2109
+ `Cannot register API "${name}" with custom path "${config.path}" - this path is already used by API "${existing.name}"`
2110
+ );
2111
+ }
2112
+ apis.set(config.path, this);
2113
+ }
2114
+ }
2115
+ }
2116
+ /**
2117
+ * Retrieves the handler function associated with this Consumption API.
2118
+ * @returns The handler function.
2119
+ */
2120
+ getHandler = () => {
2121
+ return this._handler;
2122
+ };
2123
+ async call(baseUrl, queryParams) {
2124
+ let path2;
2125
+ if (this.config?.path) {
2126
+ if (this.config.version) {
2127
+ const pathEndsWithVersion = this.config.path.endsWith(`/${this.config.version}`) || this.config.path === this.config.version || this.config.path.endsWith(this.config.version) && this.config.path.length > this.config.version.length && this.config.path[this.config.path.length - this.config.version.length - 1] === "/";
2128
+ if (pathEndsWithVersion) {
2129
+ path2 = this.config.path;
2130
+ } else {
2131
+ path2 = `${this.config.path.replace(/\/$/, "")}/${this.config.version}`;
2132
+ }
2133
+ } else {
2134
+ path2 = this.config.path;
2135
+ }
2136
+ } else {
2137
+ path2 = this.config?.version ? `${this.name}/${this.config.version}` : this.name;
2138
+ }
2139
+ const url = new URL(`${baseUrl.replace(/\/$/, "")}/api/${path2}`);
2140
+ const searchParams = url.searchParams;
2141
+ for (const [key, value] of Object.entries(queryParams)) {
2142
+ if (Array.isArray(value)) {
2143
+ for (const item of value) {
2144
+ if (item !== null && item !== void 0) {
2145
+ searchParams.append(key, String(item));
2146
+ }
2147
+ }
2148
+ } else if (value !== null && value !== void 0) {
2149
+ searchParams.append(key, String(value));
2150
+ }
2151
+ }
2152
+ const response = await fetch(url, {
2153
+ method: "GET",
2154
+ headers: {
2155
+ Accept: "application/json"
2156
+ }
2157
+ });
2158
+ if (!response.ok) {
2159
+ throw new Error(`HTTP error! status: ${response.status}`);
2160
+ }
2161
+ const data = await response.json();
2162
+ return data;
2163
+ }
2164
+ };
2165
+ var ConsumptionApi = Api;
2166
+
2167
+ // src/dmv2/sdk/ingestPipeline.ts
2168
+ var IngestPipeline = class extends TypedBase {
2169
+ /**
2170
+ * The OLAP table component of the pipeline, if configured.
2171
+ * Provides analytical query capabilities for the ingested data.
2172
+ * Only present when `config.table` is not `false`.
2173
+ */
2174
+ table;
2175
+ /**
2176
+ * The stream component of the pipeline, if configured.
2177
+ * Handles real-time data flow and processing between components.
2178
+ * Only present when `config.stream` is not `false`.
2179
+ */
2180
+ stream;
2181
+ /**
2182
+ * The ingest API component of the pipeline, if configured.
2183
+ * Provides HTTP endpoints for data ingestion.
2184
+ * Only present when `config.ingestApi` is not `false`.
2185
+ */
2186
+ ingestApi;
2187
+ /** The dead letter queue of the pipeline, if configured. */
2188
+ deadLetterQueue;
2189
+ constructor(name, config, schema, columns, validators, allowExtraFields) {
2190
+ super(name, config, schema, columns, validators, allowExtraFields);
2191
+ if (config.ingest !== void 0) {
2192
+ console.warn(
2193
+ "\u26A0\uFE0F DEPRECATION WARNING: The 'ingest' parameter is deprecated and will be removed in a future version. Please use 'ingestApi' instead."
2194
+ );
2195
+ if (config.ingestApi === void 0) {
2196
+ config.ingestApi = config.ingest;
2197
+ }
2198
+ }
2199
+ if (config.table) {
2200
+ const tableConfig = typeof config.table === "object" ? {
2201
+ ...config.table,
2202
+ lifeCycle: config.table.lifeCycle ?? config.lifeCycle,
2203
+ ...config.version && { version: config.version }
2204
+ } : {
2205
+ lifeCycle: config.lifeCycle,
2206
+ engine: "MergeTree" /* MergeTree */,
2207
+ ...config.version && { version: config.version }
2208
+ };
2209
+ this.table = new OlapTable(
2210
+ name,
2211
+ tableConfig,
2212
+ this.schema,
2213
+ this.columnArray,
2214
+ this.validators
2215
+ );
2216
+ }
2217
+ if (config.deadLetterQueue) {
2218
+ const streamConfig = {
2219
+ destination: void 0,
2220
+ ...typeof config.deadLetterQueue === "object" ? {
2221
+ ...config.deadLetterQueue,
2222
+ lifeCycle: config.deadLetterQueue.lifeCycle ?? config.lifeCycle
2223
+ } : { lifeCycle: config.lifeCycle },
2224
+ ...config.version && { version: config.version }
2225
+ };
2226
+ this.deadLetterQueue = new DeadLetterQueue(
2227
+ `${name}DeadLetterQueue`,
2228
+ streamConfig,
2229
+ validators.assert
2230
+ );
2231
+ }
2232
+ if (config.stream) {
2233
+ const streamConfig = {
2234
+ destination: this.table,
2235
+ defaultDeadLetterQueue: this.deadLetterQueue,
2236
+ ...typeof config.stream === "object" ? {
2237
+ ...config.stream,
2238
+ lifeCycle: config.stream.lifeCycle ?? config.lifeCycle
2239
+ } : { lifeCycle: config.lifeCycle },
2240
+ ...config.version && { version: config.version }
2241
+ };
2242
+ this.stream = new Stream(
2243
+ name,
2244
+ streamConfig,
2245
+ this.schema,
2246
+ this.columnArray,
2247
+ void 0,
2248
+ this.allowExtraFields
2249
+ );
2250
+ this.stream.pipelineParent = this;
2251
+ }
2252
+ const effectiveIngestAPI = config.ingestApi !== void 0 ? config.ingestApi : config.ingest;
2253
+ if (effectiveIngestAPI) {
2254
+ if (!this.stream) {
2255
+ throw new Error("Ingest API needs a stream to write to.");
2256
+ }
2257
+ const ingestConfig = {
2258
+ destination: this.stream,
2259
+ deadLetterQueue: this.deadLetterQueue,
2260
+ ...typeof effectiveIngestAPI === "object" ? effectiveIngestAPI : {},
2261
+ ...config.version && { version: config.version },
2262
+ ...config.path && { path: config.path }
2263
+ };
2264
+ this.ingestApi = new IngestApi(
2265
+ name,
2266
+ ingestConfig,
2267
+ this.schema,
2268
+ this.columnArray,
2269
+ void 0,
2270
+ this.allowExtraFields
2271
+ );
2272
+ this.ingestApi.pipelineParent = this;
2273
+ }
2274
+ }
2275
+ };
2276
+
2277
+ // src/dmv2/sdk/etlPipeline.ts
2278
+ var InternalBatcher = class {
2279
+ iterator;
2280
+ batchSize;
2281
+ constructor(asyncIterable, batchSize = 20) {
2282
+ this.iterator = asyncIterable[Symbol.asyncIterator]();
2283
+ this.batchSize = batchSize;
2284
+ }
2285
+ async getNextBatch() {
2286
+ const items = [];
2287
+ for (let i = 0; i < this.batchSize; i++) {
2288
+ const { value, done } = await this.iterator.next();
2289
+ if (done) {
2290
+ return { items, hasMore: false };
2291
+ }
2292
+ items.push(value);
2293
+ }
2294
+ return { items, hasMore: true };
2295
+ }
2296
+ };
2297
+ var ETLPipeline = class {
2298
+ constructor(name, config) {
2299
+ this.name = name;
2300
+ this.config = config;
2301
+ this.setupPipeline();
2302
+ }
2303
+ batcher;
2304
+ setupPipeline() {
2305
+ this.batcher = this.createBatcher();
2306
+ const tasks = this.createAllTasks();
2307
+ tasks.extract.config.onComplete = [tasks.transform];
2308
+ tasks.transform.config.onComplete = [tasks.load];
2309
+ new Workflow(this.name, {
2310
+ startingTask: tasks.extract,
2311
+ retries: 1,
2312
+ timeout: "30m"
2313
+ });
2314
+ }
2315
+ createBatcher() {
2316
+ const iterable = typeof this.config.extract === "function" ? this.config.extract() : this.config.extract;
2317
+ return new InternalBatcher(iterable);
2318
+ }
2319
+ getDefaultTaskConfig() {
2320
+ return {
2321
+ retries: 1,
2322
+ timeout: "30m"
2323
+ };
2324
+ }
2325
+ createAllTasks() {
2326
+ const taskConfig = this.getDefaultTaskConfig();
2327
+ return {
2328
+ extract: this.createExtractTask(taskConfig),
2329
+ transform: this.createTransformTask(taskConfig),
2330
+ load: this.createLoadTask(taskConfig)
2331
+ };
2332
+ }
2333
+ createExtractTask(taskConfig) {
2334
+ return new Task(`${this.name}_extract`, {
2335
+ run: async ({}) => {
2336
+ console.log(`Running extract task for ${this.name}...`);
2337
+ const batch = await this.batcher.getNextBatch();
2338
+ console.log(`Extract task completed with ${batch.items.length} items`);
2339
+ return batch;
2340
+ },
2341
+ retries: taskConfig.retries,
2342
+ timeout: taskConfig.timeout
2343
+ });
2344
+ }
2345
+ createTransformTask(taskConfig) {
2346
+ return new Task(
2347
+ `${this.name}_transform`,
2348
+ {
2349
+ // Use new single-parameter context API for handlers
2350
+ run: async ({ input }) => {
2351
+ const batch = input;
2352
+ console.log(
2353
+ `Running transform task for ${this.name} with ${batch.items.length} items...`
2354
+ );
2355
+ const transformedItems = [];
2356
+ for (const item of batch.items) {
2357
+ const transformed = await this.config.transform(item);
2358
+ transformedItems.push(transformed);
2359
+ }
2360
+ console.log(
2361
+ `Transform task completed with ${transformedItems.length} items`
2362
+ );
2363
+ return { items: transformedItems };
2364
+ },
2365
+ retries: taskConfig.retries,
2366
+ timeout: taskConfig.timeout
2367
+ }
2368
+ );
2369
+ }
2370
+ createLoadTask(taskConfig) {
2371
+ return new Task(`${this.name}_load`, {
2372
+ run: async ({ input: transformedItems }) => {
2373
+ console.log(
2374
+ `Running load task for ${this.name} with ${transformedItems.items.length} items...`
2375
+ );
2376
+ if ("insert" in this.config.load) {
2377
+ await this.config.load.insert(transformedItems.items);
2378
+ } else {
2379
+ await this.config.load(transformedItems.items);
2380
+ }
2381
+ console.log(`Load task completed`);
2382
+ },
2383
+ retries: taskConfig.retries,
2384
+ timeout: taskConfig.timeout
2385
+ });
2386
+ }
2387
+ // Execute the entire ETL pipeline
2388
+ async run() {
2389
+ console.log(`Starting ETL Pipeline: ${this.name}`);
2390
+ let batchNumber = 1;
2391
+ do {
2392
+ console.log(`Processing batch ${batchNumber}...`);
2393
+ const batch = await this.batcher.getNextBatch();
2394
+ if (batch.items.length === 0) {
2395
+ break;
2396
+ }
2397
+ const transformedItems = [];
2398
+ for (const extractedData of batch.items) {
2399
+ const transformedData = await this.config.transform(extractedData);
2400
+ transformedItems.push(transformedData);
2401
+ }
2402
+ if ("insert" in this.config.load) {
2403
+ await this.config.load.insert(transformedItems);
2404
+ } else {
2405
+ await this.config.load(transformedItems);
2406
+ }
2407
+ console.log(
2408
+ `Completed batch ${batchNumber} with ${batch.items.length} items`
2409
+ );
2410
+ batchNumber++;
2411
+ if (!batch.hasMore) {
2412
+ break;
2413
+ }
2414
+ } while (true);
2415
+ console.log(`Completed ETL Pipeline: ${this.name}`);
2416
+ }
2417
+ };
2418
+
2419
+ // src/dmv2/sdk/materializedView.ts
2420
+ function formatTableReference(table) {
2421
+ const database = table instanceof OlapTable ? table.config.database : void 0;
2422
+ if (database) {
2423
+ return `\`${database}\`.\`${table.name}\``;
2424
+ }
2425
+ return `\`${table.name}\``;
2426
+ }
2427
+ var requireTargetTableName = (tableName) => {
2428
+ if (typeof tableName === "string") {
2429
+ return tableName;
2430
+ } else {
2431
+ throw new Error("Name of targetTable is not specified.");
2432
+ }
2433
+ };
2434
+ var MaterializedView = class {
2435
+ /** @internal */
2436
+ kind = "MaterializedView";
2437
+ /** The name of the materialized view */
2438
+ name;
2439
+ /** The target OlapTable instance where the materialized data is stored. */
2440
+ targetTable;
2441
+ /** The SELECT SQL statement */
2442
+ selectSql;
2443
+ /** Names of source tables that the SELECT reads from */
2444
+ sourceTables;
2445
+ /** Optional metadata for the materialized view */
2446
+ metadata;
2447
+ constructor(options, targetSchema, targetColumns) {
2448
+ let selectStatement = options.selectStatement;
2449
+ if (typeof selectStatement !== "string") {
2450
+ selectStatement = toStaticQuery(selectStatement);
2451
+ }
2452
+ if (targetSchema === void 0 || targetColumns === void 0) {
2453
+ throw new Error(
2454
+ "Supply the type param T so that the schema is inserted by the compiler plugin."
2455
+ );
2456
+ }
2457
+ const targetTable = options.targetTable instanceof OlapTable ? options.targetTable : new OlapTable(
2458
+ requireTargetTableName(
2459
+ options.targetTable?.name ?? options.tableName
2460
+ ),
2461
+ {
2462
+ orderByFields: options.targetTable?.orderByFields ?? options.orderByFields,
2463
+ engine: options.targetTable?.engine ?? options.engine ?? "MergeTree" /* MergeTree */
2464
+ },
2465
+ targetSchema,
2466
+ targetColumns
2467
+ );
2468
+ if (targetTable.name === options.materializedViewName) {
2469
+ throw new Error(
2470
+ "Materialized view name cannot be the same as the target table name."
2471
+ );
2472
+ }
2473
+ this.name = options.materializedViewName;
2474
+ this.targetTable = targetTable;
2475
+ this.selectSql = selectStatement;
2476
+ this.sourceTables = options.selectTables.map(
2477
+ (t) => formatTableReference(t)
2478
+ );
2479
+ this.metadata = options.metadata ? { ...options.metadata } : {};
2480
+ if (!this.metadata.source) {
2481
+ const stack = new Error().stack;
2482
+ const sourceInfo = getSourceFileFromStack(stack);
2483
+ if (sourceInfo) {
2484
+ this.metadata.source = { file: sourceInfo };
2485
+ }
2486
+ }
2487
+ const materializedViews = getMooseInternal().materializedViews;
2488
+ if (!isClientOnlyMode() && materializedViews.has(this.name)) {
2489
+ throw new Error(`MaterializedView with name ${this.name} already exists`);
2490
+ }
2491
+ materializedViews.set(this.name, this);
2492
+ }
2493
+ };
2494
+
2495
+ // src/dmv2/sdk/sqlResource.ts
2496
+ var SqlResource = class {
2497
+ /** @internal */
2498
+ kind = "SqlResource";
2499
+ /** Array of SQL statements to execute for setting up the resource. */
2500
+ setup;
2501
+ /** Array of SQL statements to execute for tearing down the resource. */
2502
+ teardown;
2503
+ /** The name of the SQL resource (e.g., view name, materialized view name). */
2504
+ name;
2505
+ /** List of OlapTables or Views that this resource reads data from. */
2506
+ pullsDataFrom;
2507
+ /** List of OlapTables or Views that this resource writes data to. */
2508
+ pushesDataTo;
2509
+ /** @internal Source file path where this resource was defined */
2510
+ sourceFile;
2511
+ /** @internal Source line number where this resource was defined */
2512
+ sourceLine;
2513
+ /** @internal Source column number where this resource was defined */
2514
+ sourceColumn;
2515
+ /**
2516
+ * Creates a new SqlResource instance.
2517
+ * @param name The name of the resource.
2518
+ * @param setup An array of SQL DDL statements to create the resource.
2519
+ * @param teardown An array of SQL DDL statements to drop the resource.
2520
+ * @param options Optional configuration for specifying data dependencies.
2521
+ * @param options.pullsDataFrom Tables/Views this resource reads from.
2522
+ * @param options.pushesDataTo Tables/Views this resource writes to.
2523
+ */
2524
+ constructor(name, setup, teardown, options) {
2525
+ const sqlResources = getMooseInternal().sqlResources;
2526
+ if (!isClientOnlyMode() && sqlResources.has(name)) {
2527
+ throw new Error(`SqlResource with name ${name} already exists`);
2528
+ }
2529
+ sqlResources.set(name, this);
2530
+ this.name = name;
2531
+ this.setup = setup.map(
2532
+ (sql2) => typeof sql2 === "string" ? sql2 : toStaticQuery(sql2)
2533
+ );
2534
+ this.teardown = teardown.map(
2535
+ (sql2) => typeof sql2 === "string" ? sql2 : toStaticQuery(sql2)
2536
+ );
2537
+ this.pullsDataFrom = options?.pullsDataFrom ?? [];
2538
+ this.pushesDataTo = options?.pushesDataTo ?? [];
2539
+ const stack = new Error().stack;
2540
+ const location = getSourceLocationFromStack(stack);
2541
+ if (location) {
2542
+ this.sourceFile = location.file;
2543
+ this.sourceLine = location.line;
2544
+ this.sourceColumn = location.column;
2545
+ }
2546
+ }
2547
+ };
2548
+
2549
+ // src/dmv2/sdk/view.ts
2550
+ function formatTableReference2(table) {
2551
+ const database = table instanceof OlapTable ? table.config.database : void 0;
2552
+ if (database) {
2553
+ return `\`${database}\`.\`${table.name}\``;
2554
+ }
2555
+ return `\`${table.name}\``;
2556
+ }
2557
+ var View = class {
2558
+ /** @internal */
2559
+ kind = "View";
2560
+ /** The name of the view */
2561
+ name;
2562
+ /** The SELECT SQL statement that defines the view */
2563
+ selectSql;
2564
+ /** Names of source tables/views that the SELECT reads from */
2565
+ sourceTables;
2566
+ /** Optional metadata for the view */
2567
+ metadata;
2568
+ /**
2569
+ * Creates a new View instance.
2570
+ * @param name The name of the view to be created.
2571
+ * @param selectStatement The SQL SELECT statement that defines the view's logic.
2572
+ * @param baseTables An array of OlapTable or View objects that the `selectStatement` reads from. Used for dependency tracking.
2573
+ * @param metadata Optional metadata for the view (e.g., description, source file).
2574
+ */
2575
+ constructor(name, selectStatement, baseTables, metadata) {
2576
+ if (typeof selectStatement !== "string") {
2577
+ selectStatement = toStaticQuery(selectStatement);
2578
+ }
2579
+ this.name = name;
2580
+ this.selectSql = selectStatement;
2581
+ this.sourceTables = baseTables.map((t) => formatTableReference2(t));
2582
+ this.metadata = metadata ? { ...metadata } : {};
2583
+ if (!this.metadata.source) {
2584
+ const stack = new Error().stack;
2585
+ const sourceInfo = getSourceFileFromStack(stack);
2586
+ if (sourceInfo) {
2587
+ this.metadata.source = { file: sourceInfo };
2588
+ }
2589
+ }
2590
+ const views = getMooseInternal().views;
2591
+ if (!isClientOnlyMode() && views.has(this.name)) {
2592
+ throw new Error(`View with name ${this.name} already exists`);
2593
+ }
2594
+ views.set(this.name, this);
2595
+ }
2596
+ };
2597
+
2598
+ // src/dmv2/sdk/lifeCycle.ts
2599
+ var LifeCycle = /* @__PURE__ */ ((LifeCycle2) => {
2600
+ LifeCycle2["FULLY_MANAGED"] = "FULLY_MANAGED";
2601
+ LifeCycle2["DELETION_PROTECTED"] = "DELETION_PROTECTED";
2602
+ LifeCycle2["EXTERNALLY_MANAGED"] = "EXTERNALLY_MANAGED";
2603
+ return LifeCycle2;
2604
+ })(LifeCycle || {});
2605
+
2606
+ // src/dmv2/sdk/webApp.ts
2607
+ var RESERVED_MOUNT_PATHS = [
2608
+ "/admin",
2609
+ "/api",
2610
+ "/consumption",
2611
+ "/health",
2612
+ "/ingest",
2613
+ "/liveness",
2614
+ "/moose",
2615
+ // reserved for future use
2616
+ "/ready",
2617
+ "/workflows"
2618
+ ];
2619
+ var WebApp = class {
2620
+ name;
2621
+ handler;
2622
+ config;
2623
+ _rawApp;
2624
+ constructor(name, appOrHandler, config) {
2625
+ this.name = name;
2626
+ this.config = config;
2627
+ if (!this.config.mountPath) {
2628
+ throw new Error(
2629
+ `mountPath is required. Please specify a mount path for your WebApp (e.g., "/myapi").`
2630
+ );
2631
+ }
2632
+ const mountPath = this.config.mountPath;
2633
+ if (mountPath === "/") {
2634
+ throw new Error(
2635
+ `mountPath cannot be "/" as it would allow routes to overlap with reserved paths: ${RESERVED_MOUNT_PATHS.join(", ")}`
2636
+ );
2637
+ }
2638
+ if (mountPath.endsWith("/")) {
2639
+ throw new Error(
2640
+ `mountPath cannot end with a trailing slash. Remove the '/' from: "${mountPath}"`
2641
+ );
2642
+ }
2643
+ for (const reserved of RESERVED_MOUNT_PATHS) {
2644
+ if (mountPath === reserved || mountPath.startsWith(`${reserved}/`)) {
2645
+ throw new Error(
2646
+ `mountPath cannot begin with a reserved path: ${RESERVED_MOUNT_PATHS.join(", ")}. Got: "${mountPath}"`
2647
+ );
2648
+ }
2649
+ }
2650
+ this.handler = this.toHandler(appOrHandler);
2651
+ this._rawApp = typeof appOrHandler === "function" ? void 0 : appOrHandler;
2652
+ const webApps = getMooseInternal().webApps;
2653
+ if (webApps.has(name)) {
2654
+ throw new Error(`WebApp with name ${name} already exists`);
2655
+ }
2656
+ if (this.config.mountPath) {
2657
+ for (const [existingName, existingApp] of webApps) {
2658
+ if (existingApp.config.mountPath === this.config.mountPath) {
2659
+ throw new Error(
2660
+ `WebApp with mountPath "${this.config.mountPath}" already exists (used by WebApp "${existingName}")`
2661
+ );
2662
+ }
2663
+ }
2664
+ }
2665
+ webApps.set(name, this);
2666
+ }
2667
+ toHandler(appOrHandler) {
2668
+ if (typeof appOrHandler === "function") {
2669
+ return appOrHandler;
2670
+ }
2671
+ const app = appOrHandler;
2672
+ if (typeof app.handle === "function") {
2673
+ return (req, res) => {
2674
+ app.handle(req, res, (err) => {
2675
+ if (err) {
2676
+ console.error("WebApp handler error:", err);
2677
+ if (!res.headersSent) {
2678
+ res.writeHead(500, { "Content-Type": "application/json" });
2679
+ res.end(JSON.stringify({ error: "Internal Server Error" }));
2680
+ }
2681
+ }
2682
+ });
2683
+ };
2684
+ }
2685
+ if (typeof app.callback === "function") {
2686
+ return app.callback();
2687
+ }
2688
+ if (typeof app.routing === "function") {
2689
+ const routing = app.routing;
2690
+ const appWithReady = app;
2691
+ let readyPromise = null;
2692
+ return async (req, res) => {
2693
+ if (readyPromise === null) {
2694
+ readyPromise = typeof appWithReady.ready === "function" ? appWithReady.ready() : Promise.resolve();
2695
+ }
2696
+ await readyPromise;
2697
+ routing(req, res);
2698
+ };
2699
+ }
2700
+ throw new Error(
2701
+ `Unable to convert app to handler. The provided object must be:
2702
+ - A function (raw Node.js handler)
2703
+ - An object with .handle() method (Express, Connect)
2704
+ - An object with .callback() method (Koa)
2705
+ - An object with .routing function (Fastify)
2706
+
2707
+ Examples:
2708
+ Express: new WebApp("name", expressApp)
2709
+ Koa: new WebApp("name", koaApp)
2710
+ Fastify: new WebApp("name", fastifyApp)
2711
+ Raw: new WebApp("name", (req, res) => { ... })
2712
+ `
2713
+ );
2714
+ }
2715
+ getRawApp() {
2716
+ return this._rawApp;
2717
+ }
2718
+ };
2719
+
2720
+ // src/dmv2/registry.ts
2721
+ function getTables() {
2722
+ return getMooseInternal().tables;
2723
+ }
2724
+ function getTable(name) {
2725
+ return getMooseInternal().tables.get(name);
2726
+ }
2727
+ function getStreams() {
2728
+ return getMooseInternal().streams;
2729
+ }
2730
+ function getStream(name) {
2731
+ return getMooseInternal().streams.get(name);
2732
+ }
2733
+ function getIngestApis() {
2734
+ return getMooseInternal().ingestApis;
2735
+ }
2736
+ function getIngestApi(name) {
2737
+ return getMooseInternal().ingestApis.get(name);
2738
+ }
2739
+ function getApis() {
2740
+ return getMooseInternal().apis;
2741
+ }
2742
+ function getApi(nameOrPath) {
2743
+ const registry = getMooseInternal();
2744
+ const directMatch = registry.apis.get(nameOrPath);
2745
+ if (directMatch) {
2746
+ return directMatch;
2747
+ }
2748
+ const versionedApis = /* @__PURE__ */ new Map();
2749
+ const pathMap = /* @__PURE__ */ new Map();
2750
+ registry.apis.forEach((api, key) => {
2751
+ const baseName = api.name;
2752
+ if (!versionedApis.has(baseName)) {
2753
+ versionedApis.set(baseName, []);
2754
+ }
2755
+ versionedApis.get(baseName).push(api);
2756
+ if (api.config.path) {
2757
+ pathMap.set(api.config.path, api);
2758
+ }
2759
+ });
2760
+ const candidates = versionedApis.get(nameOrPath);
2761
+ if (candidates && candidates.length === 1) {
2762
+ return candidates[0];
2763
+ }
2764
+ return pathMap.get(nameOrPath);
2765
+ }
2766
+ function getSqlResources() {
2767
+ return getMooseInternal().sqlResources;
2768
+ }
2769
+ function getSqlResource(name) {
2770
+ return getMooseInternal().sqlResources.get(name);
2771
+ }
2772
+ function getWorkflows() {
2773
+ return getMooseInternal().workflows;
2774
+ }
2775
+ function getWorkflow(name) {
2776
+ return getMooseInternal().workflows.get(name);
2777
+ }
2778
+ function getWebApps() {
2779
+ return getMooseInternal().webApps;
2780
+ }
2781
+ function getWebApp(name) {
2782
+ return getMooseInternal().webApps.get(name);
2783
+ }
2784
+ function getMaterializedViews() {
2785
+ return getMooseInternal().materializedViews;
2786
+ }
2787
+ function getMaterializedView(name) {
2788
+ return getMooseInternal().materializedViews.get(name);
2789
+ }
2790
+ function getViews() {
2791
+ return getMooseInternal().views;
2792
+ }
2793
+ function getView(name) {
2794
+ return getMooseInternal().views.get(name);
2795
+ }
2796
+
2797
+ // src/serverless.ts
2798
+ init_commons_types();
2799
+
2800
+ // src/connectors/dataSource.ts
2801
+ var DataSource = class {
2802
+ name;
2803
+ supportsIncremental;
2804
+ constructor(config) {
2805
+ this.name = config.name;
2806
+ this.supportsIncremental = config.supportsIncremental ?? false;
2807
+ }
2808
+ };
2809
+
2810
+ // src/secrets.ts
2811
+ var MOOSE_RUNTIME_ENV_PREFIX = "__MOOSE_RUNTIME_ENV__:";
2812
+ var mooseRuntimeEnv = {
2813
+ /**
2814
+ * Gets a value from an environment variable, with behavior depending on context.
2815
+ *
2816
+ * When IS_LOADING_INFRA_MAP=true (infrastructure loading):
2817
+ * Returns a marker string that Moose CLI will resolve later
2818
+ *
2819
+ * When IS_LOADING_INFRA_MAP is unset (function/workflow runtime):
2820
+ * Returns the actual value from the environment variable
2821
+ *
2822
+ * @param envVarName - Name of the environment variable to resolve
2823
+ * @returns Either a marker string or the actual environment variable value
2824
+ * @throws {Error} If the environment variable name is empty
2825
+ * @throws {Error} If the environment variable is not set (runtime mode only)
2826
+ *
2827
+ * @example
2828
+ * ```typescript
2829
+ * // Instead of this (evaluated at build time):
2830
+ * awsAccessKeyId: process.env.AWS_ACCESS_KEY_ID
2831
+ *
2832
+ * // Use this (evaluated at runtime):
2833
+ * awsAccessKeyId: mooseRuntimeEnv.get("AWS_ACCESS_KEY_ID")
2834
+ * ```
2835
+ */
2836
+ get(envVarName) {
2837
+ if (!envVarName || envVarName.trim() === "") {
2838
+ throw new Error("Environment variable name cannot be empty");
2839
+ }
2840
+ const isLoadingInfraMap = process.env.IS_LOADING_INFRA_MAP === "true";
2841
+ if (isLoadingInfraMap) {
2842
+ return `${MOOSE_RUNTIME_ENV_PREFIX}${envVarName}`;
2843
+ } else {
2844
+ const value = process.env[envVarName];
2845
+ if (value === void 0) {
2846
+ throw new Error(
2847
+ `Environment variable '${envVarName}' is not set. This is required for runtime execution of functions/workflows.`
2848
+ );
2849
+ }
2850
+ return value;
2851
+ }
2852
+ }
2853
+ };
2854
+ var mooseEnvSecrets = mooseRuntimeEnv;
2855
+
2856
+ // src/utilities/dataParser.ts
2857
+ import { parse as parse2 } from "csv-parse";
2858
+
2859
+ // src/utilities/json.ts
2860
+ function jsonDateReviver(key, value) {
2861
+ const iso8601Format = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)$/;
2862
+ if (typeof value === "string" && iso8601Format.test(value)) {
2863
+ return new Date(value);
2864
+ }
2865
+ return value;
2866
+ }
2867
+
2868
+ // src/utilities/dataParser.ts
2869
+ function parseCSV(content, config) {
2870
+ return new Promise((resolve, reject) => {
2871
+ const results = [];
2872
+ parse2(content, {
2873
+ delimiter: config.delimiter,
2874
+ columns: config.columns ?? true,
2875
+ skip_empty_lines: config.skipEmptyLines ?? true,
2876
+ trim: config.trim ?? true
2877
+ }).on("data", (row) => {
2878
+ results.push(row);
2879
+ }).on("end", () => {
2880
+ resolve(results);
2881
+ }).on("error", (error) => {
2882
+ reject(error);
2883
+ });
2884
+ });
2885
+ }
2886
+ function parseJSON(content, config = {}) {
2887
+ try {
2888
+ const parsed = JSON.parse(content, config.reviver);
2889
+ if (Array.isArray(parsed)) {
2890
+ return parsed;
2891
+ } else {
2892
+ return [parsed];
2893
+ }
2894
+ } catch (error) {
2895
+ throw new Error(
2896
+ `Failed to parse JSON: ${error instanceof Error ? error.message : "Unknown error"}`
2897
+ );
2898
+ }
2899
+ }
2900
+ function parseJSONWithDates(content) {
2901
+ return parseJSON(content, { reviver: jsonDateReviver });
2902
+ }
2903
+ function isValidCSVDelimiter(delimiter) {
2904
+ return delimiter.length === 1 && !/\s/.test(delimiter);
2905
+ }
2906
+ var CSV_DELIMITERS = {
2907
+ COMMA: ",",
2908
+ TAB: " ",
2909
+ SEMICOLON: ";",
2910
+ PIPE: "|"
2911
+ };
2912
+ var DEFAULT_CSV_CONFIG = {
2913
+ delimiter: CSV_DELIMITERS.COMMA,
2914
+ columns: true,
2915
+ skipEmptyLines: true,
2916
+ trim: true
2917
+ };
2918
+ var DEFAULT_JSON_CONFIG = {
2919
+ reviver: jsonDateReviver
2920
+ };
2921
+ export {
2922
+ ACKs,
2923
+ Api,
2924
+ CSV_DELIMITERS,
2925
+ ClickHouseEngines,
2926
+ ConsumptionApi,
2927
+ DEFAULT_CSV_CONFIG,
2928
+ DEFAULT_JSON_CONFIG,
2929
+ DataSource,
2930
+ DeadLetterQueue,
2931
+ ETLPipeline,
2932
+ IngestApi,
2933
+ IngestPipeline,
2934
+ LifeCycle,
2935
+ MAX_RETRIES,
2936
+ MAX_RETRIES_PRODUCER,
2937
+ MAX_RETRY_TIME_MS,
2938
+ MOOSE_RUNTIME_ENV_PREFIX,
2939
+ MaterializedView,
2940
+ OlapTable,
2941
+ RETRY_FACTOR_PRODUCER,
2942
+ RETRY_INITIAL_TIME_MS,
2943
+ Sql,
2944
+ SqlResource,
2945
+ Stream,
2946
+ Task,
2947
+ View,
2948
+ WebApp,
2949
+ Workflow,
2950
+ antiCachePath,
2951
+ cliLog,
2952
+ compilerLog,
2953
+ createClickhouseParameter,
2954
+ getApi,
2955
+ getApis,
2956
+ getFileName,
2957
+ getIngestApi,
2958
+ getIngestApis,
2959
+ getMaterializedView,
2960
+ getMaterializedViews,
2961
+ getSqlResource,
2962
+ getSqlResources,
2963
+ getStream,
2964
+ getStreams,
2965
+ getTable,
2966
+ getTables,
2967
+ getValueFromParameter,
2968
+ getView,
2969
+ getViews,
2970
+ getWebApp,
2971
+ getWebApps,
2972
+ getWorkflow,
2973
+ getWorkflows,
2974
+ isValidCSVDelimiter,
2975
+ logError,
2976
+ mapToClickHouseType,
2977
+ mapTstoJs,
2978
+ mooseEnvSecrets,
2979
+ mooseRuntimeEnv,
2980
+ parseCSV,
2981
+ parseJSON,
2982
+ parseJSONWithDates,
2983
+ quoteIdentifier,
2984
+ sql,
2985
+ toQuery,
2986
+ toQueryPreview,
2987
+ toStaticQuery
2988
+ };
2989
+ //# sourceMappingURL=serverless.mjs.map