@514labs/moose-lib 0.6.295-ci-17-gc22400d0 → 0.6.295-ci-20-gbe187727

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