@magemetrics/core 0.0.59 → 0.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/index.d.ts +3464 -0
  2. package/dist/index.js +2923 -0
  3. package/dist/index.js.map +1 -0
  4. package/package.json +12 -9
  5. package/dist/package.json +0 -59
  6. package/dist/src/adapters/storage/browser.d.ts +0 -11
  7. package/dist/src/adapters/storage/browser.d.ts.map +0 -1
  8. package/dist/src/adapters/storage/browser.js +0 -37
  9. package/dist/src/adapters/storage/browser.js.map +0 -1
  10. package/dist/src/adapters/storage/factory.d.ts +0 -8
  11. package/dist/src/adapters/storage/factory.d.ts.map +0 -1
  12. package/dist/src/adapters/storage/factory.js +0 -24
  13. package/dist/src/adapters/storage/factory.js.map +0 -1
  14. package/dist/src/adapters/storage/interface.d.ts +0 -26
  15. package/dist/src/adapters/storage/interface.d.ts.map +0 -1
  16. package/dist/src/adapters/storage/interface.js +0 -1
  17. package/dist/src/adapters/storage/interface.js.map +0 -1
  18. package/dist/src/adapters/storage/memory.d.ts +0 -11
  19. package/dist/src/adapters/storage/memory.d.ts.map +0 -1
  20. package/dist/src/adapters/storage/memory.js +0 -20
  21. package/dist/src/adapters/storage/memory.js.map +0 -1
  22. package/dist/src/core/MageMetricsClient.d.ts +0 -103
  23. package/dist/src/core/MageMetricsClient.d.ts.map +0 -1
  24. package/dist/src/core/MageMetricsClient.js +0 -509
  25. package/dist/src/core/MageMetricsClient.js.map +0 -1
  26. package/dist/src/core/MageMetricsEventEmitter.d.ts +0 -25
  27. package/dist/src/core/MageMetricsEventEmitter.d.ts.map +0 -1
  28. package/dist/src/core/MageMetricsEventEmitter.js +0 -48
  29. package/dist/src/core/MageMetricsEventEmitter.js.map +0 -1
  30. package/dist/src/core/types.d.ts +0 -37
  31. package/dist/src/core/types.d.ts.map +0 -1
  32. package/dist/src/core/types.js +0 -6
  33. package/dist/src/core/types.js.map +0 -1
  34. package/dist/src/index.d.ts +0 -8
  35. package/dist/src/index.d.ts.map +0 -1
  36. package/dist/src/index.js +0 -7
  37. package/dist/src/index.js.map +0 -1
  38. package/dist/src/utils/hash.d.ts +0 -8
  39. package/dist/src/utils/hash.d.ts.map +0 -1
  40. package/dist/src/utils/hash.js +0 -16
  41. package/dist/src/utils/hash.js.map +0 -1
  42. package/dist/src/utils/platform.d.ts +0 -10
  43. package/dist/src/utils/platform.d.ts.map +0 -1
  44. package/dist/src/utils/platform.js +0 -25
  45. package/dist/src/utils/platform.js.map +0 -1
  46. package/dist/tsconfig.tsbuildinfo +0 -1
package/dist/index.js ADDED
@@ -0,0 +1,2923 @@
1
+ import z5, { z } from 'zod';
2
+ import dayjs from 'dayjs';
3
+ import customParseFormat from 'dayjs/plugin/customParseFormat.js';
4
+ import relativeTime from 'dayjs/plugin/relativeTime.js';
5
+ import timezone from 'dayjs/plugin/timezone.js';
6
+ import utc from 'dayjs/plugin/utc.js';
7
+ import { GoTrueClient } from '@supabase/auth-js';
8
+ import createApiClient from 'openapi-fetch';
9
+ import { sha256 } from '@noble/hashes/sha2';
10
+
11
+ // ../shared/dist/src/api/client/middleware.js
12
+ var HEADER_CLIENT_VERSION = "X-Client-Version";
13
+ var HEADER_API_KEY = "X-Api-Key";
14
+ var ApiError = class extends Error {
15
+ extra;
16
+ response;
17
+ constructor(message, response, extra) {
18
+ super(message);
19
+ this.name = "ApiError";
20
+ this.response = response;
21
+ this.extra = extra;
22
+ }
23
+ };
24
+ var throwOnError = {
25
+ async onResponse({ response, request }) {
26
+ if (response.status >= 400) {
27
+ const body = response.headers.get("content-type")?.includes("json") ? await response.clone().json() : await response.clone().text();
28
+ throw new ApiError(`[${response.status}] ${request.method} ${request.url}`, response, {
29
+ body,
30
+ status: response.status,
31
+ statusText: response.statusText,
32
+ url: request.url,
33
+ method: request.method
34
+ });
35
+ }
36
+ return void 0;
37
+ }
38
+ };
39
+ var addVersionHeader = (clientVersion) => {
40
+ return {
41
+ onRequest({ request }) {
42
+ request.headers.set(HEADER_CLIENT_VERSION, clientVersion);
43
+ return request;
44
+ }
45
+ };
46
+ };
47
+ var addApiKeyHeader = (apiKey) => {
48
+ return {
49
+ onRequest({ request }) {
50
+ request.headers.set(HEADER_API_KEY, apiKey);
51
+ return request;
52
+ }
53
+ };
54
+ };
55
+
56
+ // ../../node_modules/.pnpm/@asteasolutions+zod-to-openapi@7.3.2_zod@3.25.76/node_modules/@asteasolutions/zod-to-openapi/dist/index.mjs
57
+ function __rest(s, e) {
58
+ var t = {};
59
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
60
+ t[p] = s[p];
61
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
62
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
63
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
64
+ t[p[i]] = s[p[i]];
65
+ }
66
+ return t;
67
+ }
68
+ function isZodType(schema, typeName) {
69
+ var _a;
70
+ return ((_a = schema === null || schema === void 0 ? void 0 : schema._def) === null || _a === void 0 ? void 0 : _a.typeName) === typeName;
71
+ }
72
+ function preserveMetadataFromModifier(zod, modifier) {
73
+ const zodModifier = zod.ZodType.prototype[modifier];
74
+ zod.ZodType.prototype[modifier] = function(...args) {
75
+ const result = zodModifier.apply(this, args);
76
+ result._def.openapi = this._def.openapi;
77
+ return result;
78
+ };
79
+ }
80
+ function extendZodWithOpenApi(zod) {
81
+ if (typeof zod.ZodType.prototype.openapi !== "undefined") {
82
+ return;
83
+ }
84
+ zod.ZodType.prototype.openapi = function(refOrOpenapi, metadata) {
85
+ var _a, _b, _c, _d, _e, _f;
86
+ const openapi = typeof refOrOpenapi === "string" ? metadata : refOrOpenapi;
87
+ const _g = openapi !== null && openapi !== void 0 ? openapi : {}, { param } = _g, restOfOpenApi = __rest(_g, ["param"]);
88
+ const _internal = Object.assign(Object.assign({}, (_a = this._def.openapi) === null || _a === void 0 ? void 0 : _a._internal), typeof refOrOpenapi === "string" ? { refId: refOrOpenapi } : void 0);
89
+ const resultMetadata = Object.assign(Object.assign(Object.assign({}, (_b = this._def.openapi) === null || _b === void 0 ? void 0 : _b.metadata), restOfOpenApi), ((_d = (_c = this._def.openapi) === null || _c === void 0 ? void 0 : _c.metadata) === null || _d === void 0 ? void 0 : _d.param) || param ? {
90
+ param: Object.assign(Object.assign({}, (_f = (_e = this._def.openapi) === null || _e === void 0 ? void 0 : _e.metadata) === null || _f === void 0 ? void 0 : _f.param), param)
91
+ } : void 0);
92
+ const result = new this.constructor(Object.assign(Object.assign({}, this._def), { openapi: Object.assign(Object.assign({}, Object.keys(_internal).length > 0 ? { _internal } : void 0), Object.keys(resultMetadata).length > 0 ? { metadata: resultMetadata } : void 0) }));
93
+ if (isZodType(this, "ZodObject")) {
94
+ const originalExtend = this.extend;
95
+ result.extend = function(...args) {
96
+ var _a2, _b2, _c2, _d2, _e2, _f2;
97
+ const extendedResult = originalExtend.apply(this, args);
98
+ extendedResult._def.openapi = {
99
+ _internal: {
100
+ extendedFrom: ((_b2 = (_a2 = this._def.openapi) === null || _a2 === void 0 ? void 0 : _a2._internal) === null || _b2 === void 0 ? void 0 : _b2.refId) ? { refId: (_d2 = (_c2 = this._def.openapi) === null || _c2 === void 0 ? void 0 : _c2._internal) === null || _d2 === void 0 ? void 0 : _d2.refId, schema: this } : (_e2 = this._def.openapi) === null || _e2 === void 0 ? void 0 : _e2._internal.extendedFrom
101
+ },
102
+ metadata: (_f2 = extendedResult._def.openapi) === null || _f2 === void 0 ? void 0 : _f2.metadata
103
+ };
104
+ return extendedResult;
105
+ };
106
+ }
107
+ return result;
108
+ };
109
+ preserveMetadataFromModifier(zod, "optional");
110
+ preserveMetadataFromModifier(zod, "nullable");
111
+ preserveMetadataFromModifier(zod, "default");
112
+ preserveMetadataFromModifier(zod, "transform");
113
+ preserveMetadataFromModifier(zod, "refine");
114
+ const zodDeepPartial = zod.ZodObject.prototype.deepPartial;
115
+ zod.ZodObject.prototype.deepPartial = function() {
116
+ const initialShape = this._def.shape();
117
+ const result = zodDeepPartial.apply(this);
118
+ const resultShape = result._def.shape();
119
+ Object.entries(resultShape).forEach(([key, value]) => {
120
+ var _a, _b;
121
+ value._def.openapi = (_b = (_a = initialShape[key]) === null || _a === void 0 ? void 0 : _a._def) === null || _b === void 0 ? void 0 : _b.openapi;
122
+ });
123
+ result._def.openapi = void 0;
124
+ return result;
125
+ };
126
+ const zodPick = zod.ZodObject.prototype.pick;
127
+ zod.ZodObject.prototype.pick = function(...args) {
128
+ const result = zodPick.apply(this, args);
129
+ result._def.openapi = void 0;
130
+ return result;
131
+ };
132
+ const zodOmit = zod.ZodObject.prototype.omit;
133
+ zod.ZodObject.prototype.omit = function(...args) {
134
+ const result = zodOmit.apply(this, args);
135
+ result._def.openapi = void 0;
136
+ return result;
137
+ };
138
+ }
139
+ new Set(".\\+*[^]$()");
140
+ var createRoute = (routeConfig) => {
141
+ const route = {
142
+ ...routeConfig,
143
+ getRoutingPath() {
144
+ return routeConfig.path.replaceAll(/\/{(.+?)}/g, "/:$1");
145
+ }
146
+ };
147
+ return Object.defineProperty(route, "getRoutingPath", { enumerable: false });
148
+ };
149
+ extendZodWithOpenApi(z);
150
+
151
+ // ../shared/dist/src/endpoints/admin-console/sqlPreview.routes.js
152
+ var TanStackColumnSchema = z.object({
153
+ id: z.string(),
154
+ accessorKey: z.string(),
155
+ header: z.string(),
156
+ cell: z.any().optional(),
157
+ meta: z.record(z.any()).optional()
158
+ });
159
+ var SqlPreviewResponseSchema = z.object({
160
+ columns: z.array(TanStackColumnSchema),
161
+ data: z.array(z.record(z.any())),
162
+ metadata: z.object({
163
+ wasSampled: z.boolean(),
164
+ originalCount: z.number(),
165
+ sampledCount: z.number()
166
+ }).optional()
167
+ });
168
+ var SqlPreviewErrorSchema = z.object({
169
+ error: z.string()
170
+ });
171
+ createRoute({
172
+ method: "post",
173
+ path: "/api/v1/admin-console/sql/preview",
174
+ operationId: "sqlPreview",
175
+ request: {
176
+ body: {
177
+ content: {
178
+ "application/json": {
179
+ schema: z.object({
180
+ sql: z.string().min(1, "SQL query is required")
181
+ })
182
+ }
183
+ }
184
+ }
185
+ },
186
+ responses: {
187
+ 200: {
188
+ description: "SQL query executed successfully",
189
+ content: {
190
+ "application/json": {
191
+ schema: SqlPreviewResponseSchema
192
+ }
193
+ }
194
+ },
195
+ 400: {
196
+ description: "Invalid SQL query or request",
197
+ content: {
198
+ "application/json": {
199
+ schema: SqlPreviewErrorSchema
200
+ }
201
+ }
202
+ },
203
+ 500: {
204
+ description: "Internal server error",
205
+ content: {
206
+ "application/json": {
207
+ schema: SqlPreviewErrorSchema
208
+ }
209
+ }
210
+ }
211
+ }
212
+ });
213
+
214
+ // ../shared/dist/src/endpoints/utils.js
215
+ var limitQueryParams = z.string().pipe(z.coerce.number()).optional().openapi({
216
+ param: {
217
+ required: false
218
+ },
219
+ type: "integer"
220
+ });
221
+ var orderQueryParams = z.string().transform((str) => {
222
+ if (!str)
223
+ return [];
224
+ return str.split(",").map((part) => {
225
+ const [column, direction = "ASC"] = part.split(":");
226
+ return {
227
+ column,
228
+ direction: direction.toUpperCase()
229
+ };
230
+ });
231
+ }).pipe(z.array(z.object({
232
+ column: z.string(),
233
+ direction: z.enum(["ASC", "DESC"])
234
+ }))).optional().openapi({
235
+ param: {
236
+ required: false,
237
+ example: "name:asc,date:desc"
238
+ },
239
+ type: "string"
240
+ });
241
+ var cursorParams = z.string().pipe(z.coerce.number()).optional().openapi({
242
+ param: {
243
+ required: false
244
+ },
245
+ type: "number"
246
+ });
247
+ var filterQueryParams = z.string().transform((str) => {
248
+ if (!str)
249
+ return [];
250
+ return str.split(",").map((part) => {
251
+ const [column, value = ""] = part.split(":").map(decodeURIComponent);
252
+ return { column, value };
253
+ });
254
+ }).pipe(z.array(z.object({
255
+ column: z.string(),
256
+ value: z.string()
257
+ }))).optional().openapi({
258
+ param: {
259
+ required: false,
260
+ example: "status:active,name:John%20Doe"
261
+ },
262
+ type: "string"
263
+ });
264
+ var columnsQueryParams = z.string().transform((str) => {
265
+ if (!str)
266
+ return [];
267
+ return str.split(",");
268
+ }).optional().openapi({
269
+ param: {
270
+ required: false,
271
+ example: "name,date"
272
+ },
273
+ type: "string"
274
+ });
275
+ var SupabaseUserHeaderSchema = z.object({
276
+ "sp-access-token": z.string()
277
+ });
278
+ var SupabaseHeaderSchema = SupabaseUserHeaderSchema;
279
+ var FEEDBACK_OPTIONS = [
280
+ { label: "Helpful", value: "helpful" },
281
+ { label: "Partially helpful", value: "partially helpful" },
282
+ { label: "Not helpful", value: "not helpful" },
283
+ { label: "Incorrect", value: "incorrect" }
284
+ ];
285
+ var FeedbackSchema = z.object({
286
+ created_at: z.string(),
287
+ flow_data_id: z.number(),
288
+ helpfulness: z.enum(FEEDBACK_OPTIONS.map((option) => option.value)),
289
+ id: z.number()
290
+ });
291
+ var Node3 = z.object({
292
+ id: z.string(),
293
+ type: z.enum([
294
+ "entity",
295
+ "attribute",
296
+ "filter",
297
+ "process",
298
+ "combine",
299
+ "result"
300
+ ]),
301
+ explanation: z.string()
302
+ });
303
+ var Edge = z.object({
304
+ source: z.string(),
305
+ target: z.string()
306
+ });
307
+ z.object({
308
+ score: z.number(),
309
+ reason: z.string()
310
+ });
311
+ var LLMColumnsLineageResponse = z.record(z.string(), z.object({
312
+ nodes: z.array(Node3),
313
+ edges: z.array(Edge)
314
+ }));
315
+ var SqlAnalysisChunkSchema = z.object({
316
+ chunk_title: z.string(),
317
+ chunk_explanation: z.string(),
318
+ lines: z.array(z.object({
319
+ sql: z.string(),
320
+ explanation: z.string()
321
+ }))
322
+ });
323
+ var BusinessExplanationSchema = z.object({
324
+ summary: z.string(),
325
+ implementation: z.array(z.string()),
326
+ assumptions: z.array(z.object({
327
+ type: z.enum([
328
+ "grain",
329
+ "completeness",
330
+ "transformation",
331
+ "relationship",
332
+ "other"
333
+ ]),
334
+ details: z.string(),
335
+ explanation: z.string()
336
+ }))
337
+ });
338
+
339
+ // ../shared/dist/src/schemas/flows.js
340
+ var FlowStepSchema = z.object({
341
+ name: z.string(),
342
+ status: z.enum(["running", "completed", "failed", "awaiting_input"]),
343
+ output: z.object({}).passthrough().or(z.unknown().array()).nullable()
344
+ });
345
+ var DatabaseFlowSchema = z.object({
346
+ created_at: z.string(),
347
+ id: z.string(),
348
+ request: z.string(),
349
+ user_id: z.string().nullable(),
350
+ flow_steps: z.array(FlowStepSchema),
351
+ flow_chat_messages: z.array(z.object({ count: z.number() }))
352
+ });
353
+ z.object({
354
+ table: z.string(),
355
+ schema: z.string(),
356
+ database: z.string()
357
+ });
358
+ var FrontendFlowSchema = DatabaseFlowSchema.omit({
359
+ flow_chat_messages: true,
360
+ flow_steps: true
361
+ }).extend({
362
+ user_friendly_goal: z.string().optional(),
363
+ has_chat_messages: z.boolean()
364
+ });
365
+ var FrontendRecentFlowsSchema = DatabaseFlowSchema.omit({
366
+ flow_steps: true,
367
+ flow_chat_messages: true
368
+ });
369
+ var ReportColumnSchema = z.object({
370
+ position: z.number().nonnegative().optional(),
371
+ data_type: z.string(),
372
+ null_count: z.number().nullable(),
373
+ unique_count: z.number().nullable(),
374
+ unique_percentage: z.number().nullable()
375
+ }).passthrough();
376
+ var ReportSchema = z.object({
377
+ created_at: z.string(),
378
+ flow_id: z.string(),
379
+ id: z.number(),
380
+ is_sample: z.boolean(),
381
+ schema: z.string(),
382
+ sql: z.string(),
383
+ table: z.string(),
384
+ title: z.string(),
385
+ request: z.string().nullable(),
386
+ data_sample: z.array(z.record(z.unknown())),
387
+ data_summary: z.object({
388
+ columns: z.record(z.string(), ReportColumnSchema)
389
+ }).passthrough(),
390
+ bookmarked: z.boolean(),
391
+ status: z.string().nullable()
392
+ });
393
+ var FrontendReportSchema = ReportSchema.omit({
394
+ sql: true,
395
+ table: true,
396
+ data_sample: true,
397
+ is_sample: true,
398
+ schema: true
399
+ });
400
+ var ReportDataSchema = z.object({}).passthrough().array().openapi("ReportData");
401
+ var ReportColumnsSchema = z.object({
402
+ name: z.string(),
403
+ data_type: z.string()
404
+ }).array();
405
+ z.object({
406
+ render_type: z.string().nullish(),
407
+ unit: z.string().nullish()
408
+ });
409
+ var FrontendReportColumnsSchema = ReportColumnsSchema.element.merge(z.object({
410
+ dataType: z.string(),
411
+ renderType: z.string().optional(),
412
+ unit: z.string().optional()
413
+ })).array().openapi("ReportColumns");
414
+ z.object({
415
+ goal: z.string(),
416
+ user_friendly_goal: z.string().optional()
417
+ });
418
+ var ReportExplainabilitySchema = z.object({
419
+ sql_explanation: z.array(SqlAnalysisChunkSchema).nullish(),
420
+ business_explanation: BusinessExplanationSchema.nullish(),
421
+ columns_lineage: LLMColumnsLineageResponse.nullish(),
422
+ confidence_score: z.number(),
423
+ confidence_score_reason: z.string(),
424
+ assumptions_score: z.number().optional(),
425
+ assumptions_score_reason: z.string().optional(),
426
+ friendliness_score: z.number().optional(),
427
+ friendliness_score_reason: z.string().optional(),
428
+ id: z.number(),
429
+ flow_data_id: z.number(),
430
+ created_at: z.string()
431
+ });
432
+ var FrontendReportExplainabilitySchema = ReportExplainabilitySchema.omit({
433
+ id: true,
434
+ created_at: true
435
+ });
436
+ dayjs.extend(relativeTime);
437
+ dayjs.extend(customParseFormat);
438
+ dayjs.extend(utc);
439
+ dayjs.extend(timezone);
440
+ var daysjs_default = dayjs;
441
+
442
+ // ../shared/dist/src/data/FormattedData.js
443
+ var formatWithAutoPrecision = (value, options = {}) => {
444
+ const { minPrecision = 0, maxPrecision = 6, trimZeros = true, useGrouping = true } = options;
445
+ if (typeof value !== "number" || isNaN(value)) {
446
+ return String(value);
447
+ }
448
+ if (value === 0) {
449
+ return "0";
450
+ }
451
+ const absValue = Math.abs(value);
452
+ let maximumFractionDigits;
453
+ if (absValue >= 1e3) {
454
+ maximumFractionDigits = 0;
455
+ } else if (absValue >= 100) {
456
+ maximumFractionDigits = 1;
457
+ } else if (absValue >= 10) {
458
+ maximumFractionDigits = 2;
459
+ } else if (absValue >= 1) {
460
+ maximumFractionDigits = 3;
461
+ } else if (absValue >= 0.1) {
462
+ maximumFractionDigits = 4;
463
+ } else if (absValue >= 0.01) {
464
+ maximumFractionDigits = 5;
465
+ } else {
466
+ maximumFractionDigits = maxPrecision;
467
+ if (absValue > 0) {
468
+ const exponent = Math.floor(Math.log10(absValue));
469
+ if (exponent < 0) {
470
+ maximumFractionDigits = Math.min(Math.abs(exponent) + 2, maxPrecision);
471
+ }
472
+ }
473
+ }
474
+ maximumFractionDigits = Math.max(maximumFractionDigits, minPrecision);
475
+ const formatter = new Intl.NumberFormat(void 0, {
476
+ minimumFractionDigits: trimZeros ? 0 : maximumFractionDigits,
477
+ maximumFractionDigits,
478
+ useGrouping
479
+ });
480
+ return formatter.format(value);
481
+ };
482
+ var MIN_VALID_YEAR = 1900;
483
+ var MAX_VALID_YEAR = 2200;
484
+ var zonedatetime = (format, zone) => ({ format, type: "zonedatetime", zone });
485
+ var datetime = (format) => ({ format, type: "datetime" });
486
+ var date = (format) => ({ format, type: "date" });
487
+ var DATE_FORMATS = [
488
+ // ISO 8601 formats
489
+ zonedatetime("YYYY-MM-DDTHH:mm:ss.SSSZ", "UTC"),
490
+ zonedatetime("YYYY-MM-DDTHH:mm:ssZ", "UTC"),
491
+ zonedatetime("YYYY-MM-DDTHH:mmZ", "UTC"),
492
+ datetime("YYYY-MM-DDTHH:mm:ss"),
493
+ datetime("YYYY-MM-DDTHH:mm"),
494
+ date("YYYY-MM-DDT"),
495
+ // Standard date formats
496
+ date("YYYY-MM-DD"),
497
+ date("YYYY/MM/DD"),
498
+ date("DD-MM-YYYY"),
499
+ date("DD/MM/YYYY"),
500
+ date("MM-DD-YYYY"),
501
+ date("MM/DD/YYYY"),
502
+ // Date time formats
503
+ datetime("YYYY-MM-DD HH:mm:ss"),
504
+ datetime("YYYY-MM-DD HH:mm"),
505
+ datetime("YYYY/MM/DD HH:mm:ss"),
506
+ datetime("YYYY/MM/DD HH:mm"),
507
+ datetime("DD-MM-YYYY HH:mm:ss"),
508
+ datetime("DD-MM-YYYY HH:mm"),
509
+ datetime("DD/MM/YYYY HH:mm:ss"),
510
+ datetime("DD/MM/YYYY HH:mm"),
511
+ datetime("MM-DD-YYYY HH:mm:ss"),
512
+ datetime("MM-DD-YYYY HH:mm"),
513
+ datetime("MM/DD/YYYY HH:mm:ss"),
514
+ datetime("MM/DD/YYYY HH:mm")
515
+ ];
516
+ var isDateString = (value) => {
517
+ if (typeof value !== "string")
518
+ return { isValid: false };
519
+ const stripped = value.replace(/[-/.:\s]/g, "");
520
+ if (/^\d+$/.test(stripped)) {
521
+ if (stripped.length < 6)
522
+ return { isValid: false };
523
+ if (value.length === stripped.length)
524
+ return { isValid: false };
525
+ }
526
+ if (stripped.length > "YYYY-MM-DDTHH:mm:ss.SSS+00:00".length) {
527
+ return { isValid: false };
528
+ }
529
+ for (const format of DATE_FORMATS) {
530
+ let date2;
531
+ try {
532
+ if (format.type === "zonedatetime") {
533
+ date2 = daysjs_default.tz(value, format.format, format.zone);
534
+ } else {
535
+ date2 = daysjs_default(value, format.format, true);
536
+ }
537
+ } catch {
538
+ continue;
539
+ }
540
+ if (date2.isValid()) {
541
+ const year = date2.year();
542
+ if (year < MIN_VALID_YEAR || year > MAX_VALID_YEAR)
543
+ continue;
544
+ const isDateTime = format.type === "zonedatetime" || format.type == "datetime";
545
+ return {
546
+ isValid: true,
547
+ parsedDate: date2,
548
+ isDateTime
549
+ };
550
+ }
551
+ }
552
+ return { isValid: false };
553
+ };
554
+ var formatDataValue = (value, { replaceNullValue } = {
555
+ replaceNullValue: true
556
+ }) => {
557
+ if (value === null || value === void 0) {
558
+ return {
559
+ display: replaceNullValue ? "empty" : null,
560
+ sortValue: null
561
+ };
562
+ }
563
+ let processedValue = value;
564
+ if (typeof processedValue === "string") {
565
+ try {
566
+ const parsed = JSON.parse(processedValue);
567
+ processedValue = parsed;
568
+ } catch {
569
+ }
570
+ }
571
+ if (processedValue && typeof processedValue === "object" && Object.keys(processedValue).length === 1 && "value" in processedValue) {
572
+ const extractedValue = processedValue.value;
573
+ const dateResult2 = isDateString(extractedValue);
574
+ if (dateResult2.isValid) {
575
+ return {
576
+ display: dateResult2.isDateTime ? dateResult2.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult2.parsedDate.format("YYYY-MM-DD"),
577
+ sortValue: dateResult2.parsedDate.valueOf()
578
+ };
579
+ }
580
+ return {
581
+ display: String(extractedValue),
582
+ sortValue: extractedValue
583
+ };
584
+ }
585
+ const dateResult = isDateString(processedValue);
586
+ if (dateResult.isValid) {
587
+ return {
588
+ display: dateResult.isDateTime ? dateResult.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult.parsedDate.format("YYYY-MM-DD"),
589
+ sortValue: dateResult.parsedDate.valueOf()
590
+ };
591
+ }
592
+ if (typeof processedValue === "object") {
593
+ const stringified = JSON.stringify(processedValue, null, 2);
594
+ return {
595
+ display: stringified,
596
+ sortValue: stringified
597
+ };
598
+ }
599
+ if (typeof processedValue === "boolean") {
600
+ return {
601
+ display: String(processedValue),
602
+ sortValue: processedValue ? 1 : 0
603
+ };
604
+ }
605
+ if (typeof processedValue === "number") {
606
+ return {
607
+ display: processedValue >= MIN_VALID_YEAR && processedValue <= MAX_VALID_YEAR && Number.isInteger(processedValue) ? String(processedValue) : formatWithAutoPrecision(processedValue),
608
+ sortValue: processedValue
609
+ };
610
+ }
611
+ return {
612
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
613
+ display: String(processedValue),
614
+ sortValue: processedValue
615
+ };
616
+ };
617
+
618
+ // ../shared/dist/src/schemas/visualizations.js
619
+ var commonConfigProperties = {
620
+ title: z.string()
621
+ };
622
+ var cartesianConfigProperties = {
623
+ xAxisLabel: z.string(),
624
+ yAxisLabel: z.string(),
625
+ xAxisDataKey: z.string().optional(),
626
+ yAxisDataKey: z.string().optional(),
627
+ dimensionDataKey: z.string().optional(),
628
+ valueColumns: z.array(z.string()).optional()
629
+ };
630
+ var V1VisualizationConfigurationSchema = z.discriminatedUnion("type", [
631
+ // Bar chart
632
+ z.object({
633
+ type: z.literal("bar"),
634
+ ...commonConfigProperties,
635
+ ...cartesianConfigProperties
636
+ }),
637
+ // Line/Area chart
638
+ z.object({
639
+ type: z.literal("line/area"),
640
+ ...commonConfigProperties,
641
+ ...cartesianConfigProperties
642
+ }),
643
+ // Scatter chart
644
+ z.object({
645
+ type: z.literal("scatter"),
646
+ ...commonConfigProperties,
647
+ ...cartesianConfigProperties
648
+ }),
649
+ // Pie chart
650
+ z.object({
651
+ type: z.literal("pie"),
652
+ ...commonConfigProperties,
653
+ nameKey: z.string(),
654
+ dataKey: z.string()
655
+ })
656
+ ]);
657
+ var VisualizationConfigurationSchema = z.discriminatedUnion("type", [
658
+ z.object({
659
+ type: z.literal("bar"),
660
+ ...commonConfigProperties,
661
+ config_version: z.literal(2),
662
+ xAxisLabel: z.string(),
663
+ yAxisLabel: z.string(),
664
+ categoryColumn: z.string(),
665
+ secondaryCategoryColumn: z.string().optional(),
666
+ valueColumn: z.string()
667
+ }),
668
+ // Line/Area chart - version 2: New format
669
+ z.object({
670
+ type: z.literal("line/area"),
671
+ config_version: z.literal(2),
672
+ ...commonConfigProperties,
673
+ xAxisColumn: z.string(),
674
+ valueColumns: z.array(z.string()),
675
+ yAxisLabels: z.array(z.string())
676
+ }),
677
+ // Line/Area chart - categorical format (requires pivoting)
678
+ z.object({
679
+ type: z.literal("line/area-categorical"),
680
+ ...commonConfigProperties,
681
+ config_version: z.literal(2),
682
+ valueColumn: z.string(),
683
+ xAxisColumn: z.string(),
684
+ xAxisLabel: z.string(),
685
+ yAxisLabel: z.string(),
686
+ categoryColumn: z.string()
687
+ }),
688
+ // Scatter chart - new format (v2)
689
+ z.object({
690
+ type: z.literal("scatter"),
691
+ ...commonConfigProperties,
692
+ config_version: z.literal(2),
693
+ xAxisLabel: z.string(),
694
+ yAxisLabel: z.string(),
695
+ xAxisValueColumn: z.string(),
696
+ yAxisValueColumn: z.string()
697
+ }),
698
+ // Pie chart - new format (v2)
699
+ z.object({
700
+ type: z.literal("pie"),
701
+ ...commonConfigProperties,
702
+ config_version: z.literal(2),
703
+ categoryColumn: z.string(),
704
+ valueColumn: z.string()
705
+ })
706
+ ]);
707
+ var BaseVisualizationSchema = z.object({
708
+ id: z.number(),
709
+ flow_data_id: z.number(),
710
+ created_at: z.string(),
711
+ sql: z.string(),
712
+ bookmarked: z.boolean(),
713
+ data_sample: z.array(z.record(z.unknown())),
714
+ is_sample: z.boolean(),
715
+ data_summary: z.record(z.unknown())
716
+ });
717
+ var V1VisualizationSchema = BaseVisualizationSchema.merge(z.object({
718
+ configuration: V1VisualizationConfigurationSchema
719
+ }));
720
+ var VisualizationSchema = BaseVisualizationSchema.merge(z.object({
721
+ configuration: VisualizationConfigurationSchema
722
+ }));
723
+ var VisualizationDataSchema = z.array(z.record(
724
+ z.string(),
725
+ // any key
726
+ z.union([
727
+ // Date objects FIRST
728
+ z.date(),
729
+ z.coerce.number(),
730
+ // Handle various data types including BigQueryDate
731
+ z.unknown().transform((val) => formatDataValue(val).display)
732
+ ])
733
+ )).openapi("VisualizationData");
734
+ var V1FrontendVisualizationSchema = V1VisualizationSchema.omit({
735
+ sql: true,
736
+ data_sample: true,
737
+ is_sample: true,
738
+ data_summary: true
739
+ });
740
+ var FrontendVisualizationSchema = VisualizationSchema.omit({
741
+ sql: true,
742
+ data_sample: true,
743
+ is_sample: true,
744
+ data_summary: true
745
+ });
746
+ var VisualizationMetadataSchema = z.object({
747
+ wasSampled: z.boolean(),
748
+ originalCount: z.number(),
749
+ sampledCount: z.number()
750
+ }).optional();
751
+ V1FrontendVisualizationSchema.extend({
752
+ data: VisualizationDataSchema,
753
+ _metadata: VisualizationMetadataSchema
754
+ });
755
+ FrontendVisualizationSchema.extend({
756
+ data: VisualizationDataSchema,
757
+ _metadata: VisualizationMetadataSchema
758
+ });
759
+
760
+ // ../shared/dist/src/endpoints/companion/flows.routes.js
761
+ var FlowIdParam = z.object({ flowId: z.string().uuid() }).openapi("FlowId", { type: "string" });
762
+ var FlowDataIdParam = z.object({ flowDataId: z.string().pipe(z.coerce.number()) }).openapi("FlowDataId", { type: "integer" });
763
+ var ReportId = z.string().pipe(z.coerce.number());
764
+ var ReportIdParam = z.object({ report_id: ReportId }).openapi("ReportId", { type: "integer" });
765
+ createRoute({
766
+ method: "get",
767
+ path: "/api/v1/flows/{flowId}/data-reports",
768
+ operationId: "retrieveFlowDataReports",
769
+ request: {
770
+ headers: SupabaseHeaderSchema,
771
+ params: FlowIdParam
772
+ },
773
+ responses: {
774
+ 200: {
775
+ description: "The data reports associated with the flow",
776
+ content: {
777
+ "application/json": {
778
+ schema: FrontendReportSchema.array()
779
+ }
780
+ }
781
+ },
782
+ 404: {
783
+ content: {
784
+ "application/json": {
785
+ schema: z.object({ error: z.string() })
786
+ }
787
+ },
788
+ description: "Unable to retrieve flow with this id"
789
+ },
790
+ 500: {
791
+ description: "Something wrong happened",
792
+ content: {
793
+ "application/json": {
794
+ schema: z.object({
795
+ error: z.string()
796
+ })
797
+ }
798
+ }
799
+ }
800
+ }
801
+ });
802
+ createRoute({
803
+ method: "get",
804
+ path: "/api/v1/flows/{flowId}/data-reports/last/status",
805
+ operationId: "retrieveLatestDataReportStatus",
806
+ request: {
807
+ headers: SupabaseHeaderSchema,
808
+ params: FlowIdParam
809
+ },
810
+ responses: {
811
+ 200: {
812
+ description: "The status of the latest flow data for a given flow",
813
+ content: {
814
+ "application/json": {
815
+ schema: z.object({ status: z.string().nullable() })
816
+ }
817
+ }
818
+ },
819
+ 404: {
820
+ content: {
821
+ "application/json": {
822
+ schema: z.object({ error: z.string() })
823
+ }
824
+ },
825
+ description: "Unable to retrieve status for latest flow data of flow with this id"
826
+ },
827
+ 500: {
828
+ description: "Something wrong happened",
829
+ content: {
830
+ "application/json": {
831
+ schema: z.object({
832
+ error: z.string()
833
+ })
834
+ }
835
+ }
836
+ }
837
+ }
838
+ });
839
+ createRoute({
840
+ // this endpoint is deprecated and will be removed in the future
841
+ hide: true,
842
+ method: "get",
843
+ path: "/api/v1/flows/{flowId}/insights",
844
+ operationId: "retrieveInsights",
845
+ request: {
846
+ headers: SupabaseHeaderSchema,
847
+ params: FlowIdParam,
848
+ query: z.object({
849
+ flowDataId: z.string().pipe(z.coerce.number()).optional().openapi({
850
+ param: {
851
+ required: false
852
+ },
853
+ type: "integer"
854
+ })
855
+ })
856
+ },
857
+ responses: {
858
+ 200: {
859
+ description: "The content of the flow",
860
+ content: {
861
+ "application/json": {
862
+ schema: z.object({
863
+ dataReports: FrontendReportSchema.array(),
864
+ visualizations: V1FrontendVisualizationSchema.array()
865
+ })
866
+ }
867
+ }
868
+ },
869
+ 404: {
870
+ content: {
871
+ "application/json": {
872
+ schema: z.object({ error: z.string() })
873
+ }
874
+ },
875
+ description: "Unable to retrieve flow with this id"
876
+ },
877
+ 500: {
878
+ description: "Something wrong happened",
879
+ content: {
880
+ "application/json": {
881
+ schema: z.object({
882
+ error: z.string()
883
+ })
884
+ }
885
+ }
886
+ }
887
+ }
888
+ });
889
+ createRoute({
890
+ // this endpoint is deprecated and will be removed in the future
891
+ hide: true,
892
+ method: "get",
893
+ path: "/api/v1/flows/{flowId}/columns",
894
+ operationId: "retrieveFlowColumns",
895
+ request: {
896
+ headers: SupabaseHeaderSchema,
897
+ params: FlowIdParam,
898
+ query: FlowDataIdParam
899
+ },
900
+ responses: {
901
+ 200: {
902
+ description: "A list containing the columns of the flow",
903
+ content: {
904
+ "application/json": {
905
+ schema: FrontendReportColumnsSchema
906
+ }
907
+ }
908
+ },
909
+ 404: {
910
+ content: {
911
+ "application/json": {
912
+ schema: z.object({ error: z.string() })
913
+ }
914
+ },
915
+ description: "Unable to retrieve flow with this id"
916
+ },
917
+ 500: {
918
+ description: "Something wrong happened",
919
+ content: {
920
+ "application/json": {
921
+ schema: z.object({
922
+ error: z.string()
923
+ })
924
+ }
925
+ }
926
+ }
927
+ }
928
+ });
929
+ createRoute({
930
+ method: "get",
931
+ path: "/api/v1/flows/{flowId}",
932
+ operationId: "retrieveFlow",
933
+ request: {
934
+ headers: SupabaseHeaderSchema,
935
+ params: FlowIdParam
936
+ },
937
+ responses: {
938
+ 200: {
939
+ description: "The flow with its steps",
940
+ content: {
941
+ "application/json": {
942
+ schema: FrontendFlowSchema
943
+ }
944
+ }
945
+ },
946
+ 404: {
947
+ content: {
948
+ "application/json": {
949
+ schema: z.object({ error: z.string() })
950
+ }
951
+ },
952
+ description: "Unable to retrieve flow with this id"
953
+ },
954
+ 500: {
955
+ description: "Something wrong happened",
956
+ content: {
957
+ "application/json": {
958
+ schema: z.object({
959
+ error: z.string()
960
+ })
961
+ }
962
+ }
963
+ }
964
+ }
965
+ });
966
+ var RetrieveRecentFlows = createRoute({
967
+ method: "get",
968
+ path: "/api/v1/recent-flows",
969
+ operationId: "retrieveRecentFlows",
970
+ request: {
971
+ headers: SupabaseHeaderSchema,
972
+ query: z.object({
973
+ limit: limitQueryParams
974
+ })
975
+ },
976
+ responses: {
977
+ 200: {
978
+ description: "A list of recent flows",
979
+ content: {
980
+ "application/json": {
981
+ schema: FrontendRecentFlowsSchema.array()
982
+ }
983
+ }
984
+ },
985
+ 500: {
986
+ description: "Something wrong happened",
987
+ content: {
988
+ "application/json": {
989
+ schema: z.object({
990
+ error: z.string()
991
+ })
992
+ }
993
+ }
994
+ }
995
+ }
996
+ });
997
+ createRoute({
998
+ method: "get",
999
+ path: "/api/v1/data-reports/{report_id}/columns",
1000
+ operationId: "getDataReportColumns",
1001
+ request: {
1002
+ headers: SupabaseHeaderSchema,
1003
+ params: ReportIdParam
1004
+ },
1005
+ responses: {
1006
+ 200: {
1007
+ description: "A list containing the columns of the report",
1008
+ content: {
1009
+ "application/json": {
1010
+ schema: FrontendReportColumnsSchema
1011
+ }
1012
+ }
1013
+ },
1014
+ 404: {
1015
+ content: {
1016
+ "application/json": {
1017
+ schema: z.object({ error: z.string() })
1018
+ }
1019
+ },
1020
+ description: "Unable to retrieve report with this id"
1021
+ },
1022
+ 500: {
1023
+ description: "Something wrong happened",
1024
+ content: {
1025
+ "application/json": {
1026
+ schema: z.object({
1027
+ error: z.string()
1028
+ })
1029
+ }
1030
+ }
1031
+ }
1032
+ }
1033
+ });
1034
+ var ExportReportData = createRoute({
1035
+ method: "get",
1036
+ path: "/api/v1/data-reports/{report_id}/export",
1037
+ operationId: "exportReportData",
1038
+ request: {
1039
+ headers: SupabaseHeaderSchema,
1040
+ params: ReportIdParam
1041
+ },
1042
+ responses: {
1043
+ 200: {
1044
+ description: "The report data exported in CSV format",
1045
+ content: {
1046
+ "text/csv": {
1047
+ schema: z.string().describe("CSV formatted string of report data")
1048
+ }
1049
+ }
1050
+ },
1051
+ 404: {
1052
+ content: {
1053
+ "application/json": {
1054
+ schema: z.object({ error: z.string() })
1055
+ }
1056
+ },
1057
+ description: "Unable to retrieve flow with this id"
1058
+ },
1059
+ 500: {
1060
+ description: "Something wrong happened",
1061
+ content: {
1062
+ "application/json": {
1063
+ schema: z.object({
1064
+ error: z.string()
1065
+ })
1066
+ }
1067
+ }
1068
+ }
1069
+ }
1070
+ });
1071
+ createRoute({
1072
+ // this endpoint is deprecated and will be removed in the future
1073
+ hide: true,
1074
+ method: "get",
1075
+ path: "/api/v1/flows/{flowId}/data",
1076
+ operationId: "retrieveFlowData",
1077
+ request: {
1078
+ headers: SupabaseHeaderSchema,
1079
+ params: FlowIdParam,
1080
+ query: z.object({
1081
+ limit: limitQueryParams,
1082
+ order: orderQueryParams,
1083
+ cursor: cursorParams,
1084
+ filter: filterQueryParams,
1085
+ flowDataId: FlowDataIdParam.shape.flowDataId.openapi({
1086
+ type: "integer",
1087
+ param: { required: true }
1088
+ })
1089
+ })
1090
+ },
1091
+ responses: {
1092
+ 200: {
1093
+ description: "The content of the flow",
1094
+ content: {
1095
+ "application/json": {
1096
+ schema: ReportDataSchema
1097
+ }
1098
+ }
1099
+ },
1100
+ 404: {
1101
+ content: {
1102
+ "application/json": {
1103
+ schema: z.object({ error: z.string() })
1104
+ }
1105
+ },
1106
+ description: "Unable to retrieve flow with this id"
1107
+ },
1108
+ 500: {
1109
+ description: "Something wrong happened",
1110
+ content: {
1111
+ "application/json": {
1112
+ schema: z.object({
1113
+ error: z.string()
1114
+ })
1115
+ }
1116
+ }
1117
+ }
1118
+ }
1119
+ });
1120
+ createRoute({
1121
+ method: "get",
1122
+ path: "/api/v1/data-reports/{report_id}/data",
1123
+ operationId: "getDataReportData",
1124
+ request: {
1125
+ headers: SupabaseHeaderSchema,
1126
+ params: ReportIdParam,
1127
+ query: z.object({
1128
+ columns: columnsQueryParams,
1129
+ limit: limitQueryParams,
1130
+ order: orderQueryParams,
1131
+ cursor: cursorParams,
1132
+ filter: filterQueryParams
1133
+ })
1134
+ },
1135
+ responses: {
1136
+ 200: {
1137
+ description: "The content of the report",
1138
+ content: {
1139
+ "application/json": {
1140
+ schema: ReportDataSchema
1141
+ }
1142
+ }
1143
+ },
1144
+ 404: {
1145
+ content: {
1146
+ "application/json": {
1147
+ schema: z.object({ error: z.string() })
1148
+ }
1149
+ },
1150
+ description: "Unable to retrieve report with this id"
1151
+ },
1152
+ 500: {
1153
+ description: "Something wrong happened",
1154
+ content: {
1155
+ "application/json": {
1156
+ schema: z.object({
1157
+ error: z.string()
1158
+ })
1159
+ }
1160
+ }
1161
+ }
1162
+ }
1163
+ });
1164
+ createRoute({
1165
+ // this endpoint is deprecated and will be removed in the future
1166
+ hide: true,
1167
+ method: "get",
1168
+ path: "/api/v1/flows/{flowId}/count",
1169
+ operationId: "retrieveFlowDataCount",
1170
+ request: {
1171
+ headers: SupabaseHeaderSchema,
1172
+ params: FlowIdParam,
1173
+ query: z.object({
1174
+ flowDataId: z.string().pipe(z.coerce.number()).openapi({
1175
+ param: {
1176
+ required: false
1177
+ },
1178
+ type: "integer"
1179
+ })
1180
+ })
1181
+ },
1182
+ responses: {
1183
+ 200: {
1184
+ description: "The total count of rows in the flow",
1185
+ content: {
1186
+ "application/json": {
1187
+ schema: z.object({
1188
+ count: z.number().int().nonnegative().describe("Total number of rows in the flow")
1189
+ })
1190
+ }
1191
+ }
1192
+ },
1193
+ 404: {
1194
+ content: {
1195
+ "application/json": {
1196
+ schema: z.object({ error: z.string() })
1197
+ }
1198
+ },
1199
+ description: "Unable to retrieve flow with this id"
1200
+ },
1201
+ 500: {
1202
+ description: "Something wrong happened",
1203
+ content: {
1204
+ "application/json": {
1205
+ schema: z.object({
1206
+ error: z.string()
1207
+ })
1208
+ }
1209
+ }
1210
+ }
1211
+ }
1212
+ });
1213
+ createRoute({
1214
+ method: "get",
1215
+ path: "/api/v1/data-reports/{report_id}/count",
1216
+ operationId: "getDataReportRowCount",
1217
+ request: {
1218
+ headers: SupabaseHeaderSchema,
1219
+ params: ReportIdParam
1220
+ },
1221
+ responses: {
1222
+ 200: {
1223
+ description: "The total count of rows in the report",
1224
+ content: {
1225
+ "application/json": {
1226
+ schema: z.object({
1227
+ count: z.number().int().nonnegative().describe("Total number of rows in the report")
1228
+ })
1229
+ }
1230
+ }
1231
+ },
1232
+ 404: {
1233
+ content: {
1234
+ "application/json": {
1235
+ schema: z.object({ error: z.string() })
1236
+ }
1237
+ },
1238
+ description: "Unable to retrieve report with this id"
1239
+ },
1240
+ 500: {
1241
+ description: "Something wrong happened",
1242
+ content: {
1243
+ "application/json": {
1244
+ schema: z.object({
1245
+ error: z.string()
1246
+ })
1247
+ }
1248
+ }
1249
+ }
1250
+ }
1251
+ });
1252
+ createRoute({
1253
+ // this endpoint is deprecated and will be removed in the future
1254
+ hide: true,
1255
+ method: "get",
1256
+ path: "/api/v1/flow-data/{flowDataId}/feedback",
1257
+ operationId: "retrieveFeedback",
1258
+ request: {
1259
+ headers: SupabaseHeaderSchema,
1260
+ params: FlowDataIdParam
1261
+ },
1262
+ responses: {
1263
+ 200: {
1264
+ description: "The feedback for the flow data",
1265
+ content: {
1266
+ "application/json": {
1267
+ schema: FeedbackSchema.nullable()
1268
+ }
1269
+ }
1270
+ },
1271
+ 404: {
1272
+ content: {
1273
+ "application/json": {
1274
+ schema: z.object({ error: z.string() })
1275
+ }
1276
+ },
1277
+ description: "Unable to retrieve feedback"
1278
+ },
1279
+ 500: {
1280
+ description: "Something wrong happened",
1281
+ content: {
1282
+ "application/json": {
1283
+ schema: z.object({
1284
+ error: z.string()
1285
+ })
1286
+ }
1287
+ }
1288
+ }
1289
+ }
1290
+ });
1291
+ createRoute({
1292
+ method: "get",
1293
+ path: "/api/v1/data-reports/{report_id}/feedback",
1294
+ operationId: "getDataReportFeedback",
1295
+ request: {
1296
+ headers: SupabaseHeaderSchema,
1297
+ params: ReportIdParam
1298
+ },
1299
+ responses: {
1300
+ 200: {
1301
+ description: "The feedback for the report",
1302
+ content: {
1303
+ "application/json": {
1304
+ schema: FeedbackSchema.nullable()
1305
+ }
1306
+ }
1307
+ },
1308
+ 404: {
1309
+ content: {
1310
+ "application/json": {
1311
+ schema: z.object({ error: z.string() })
1312
+ }
1313
+ },
1314
+ description: "Unable to retrieve feedback"
1315
+ },
1316
+ 500: {
1317
+ description: "Something wrong happened",
1318
+ content: {
1319
+ "application/json": {
1320
+ schema: z.object({
1321
+ error: z.string()
1322
+ })
1323
+ }
1324
+ }
1325
+ }
1326
+ }
1327
+ });
1328
+ createRoute({
1329
+ // this endpoint is deprecated and will be removed in the future
1330
+ hide: true,
1331
+ method: "post",
1332
+ path: "/api/v1/flow-data/{flowDataId}/feedback",
1333
+ operationId: "upsertFeedback",
1334
+ request: {
1335
+ headers: SupabaseHeaderSchema,
1336
+ params: FlowDataIdParam,
1337
+ body: {
1338
+ description: "The feedback for the flow data",
1339
+ required: true,
1340
+ content: {
1341
+ "application/json": {
1342
+ schema: z.object({
1343
+ helpfulness: FeedbackSchema.shape.helpfulness
1344
+ })
1345
+ }
1346
+ }
1347
+ }
1348
+ },
1349
+ responses: {
1350
+ 200: {
1351
+ description: "Successfully upserted feedback"
1352
+ },
1353
+ 500: {
1354
+ description: "Something wrong happened",
1355
+ content: {
1356
+ "application/json": {
1357
+ schema: z.object({
1358
+ error: z.string()
1359
+ })
1360
+ }
1361
+ }
1362
+ }
1363
+ }
1364
+ });
1365
+ createRoute({
1366
+ method: "post",
1367
+ path: "/api/v1/data-reports/{report_id}/feedback",
1368
+ operationId: "upsertReportFeedback",
1369
+ request: {
1370
+ headers: SupabaseHeaderSchema,
1371
+ params: ReportIdParam,
1372
+ body: {
1373
+ description: "The feedback for the flow data",
1374
+ required: true,
1375
+ content: {
1376
+ "application/json": {
1377
+ schema: z.object({
1378
+ helpfulness: FeedbackSchema.shape.helpfulness
1379
+ })
1380
+ }
1381
+ }
1382
+ }
1383
+ },
1384
+ responses: {
1385
+ 200: {
1386
+ description: "Successfully upserted feedback"
1387
+ },
1388
+ 500: {
1389
+ description: "Something wrong happened",
1390
+ content: {
1391
+ "application/json": {
1392
+ schema: z.object({
1393
+ error: z.string()
1394
+ })
1395
+ }
1396
+ }
1397
+ }
1398
+ }
1399
+ });
1400
+ createRoute({
1401
+ // this endpoint is deprecated and will be removed in the future
1402
+ hide: true,
1403
+ method: "delete",
1404
+ path: "/api/v1/flow-data/{flowDataId}/feedback",
1405
+ operationId: "deleteFeedback",
1406
+ request: {
1407
+ headers: SupabaseHeaderSchema,
1408
+ params: FlowDataIdParam
1409
+ },
1410
+ responses: {
1411
+ 200: {
1412
+ description: "Successfully deleted feedback"
1413
+ },
1414
+ 404: {
1415
+ content: {
1416
+ "application/json": {
1417
+ schema: z.object({ error: z.string() })
1418
+ }
1419
+ },
1420
+ description: "Unable to retrieve feedback"
1421
+ },
1422
+ 500: {
1423
+ description: "Something wrong happened",
1424
+ content: {
1425
+ "application/json": {
1426
+ schema: z.object({
1427
+ error: z.string()
1428
+ })
1429
+ }
1430
+ }
1431
+ }
1432
+ }
1433
+ });
1434
+ createRoute({
1435
+ method: "delete",
1436
+ path: "/api/v1/data-reports/{report_id}/feedback",
1437
+ operationId: "deleteReportFeedback",
1438
+ request: {
1439
+ headers: SupabaseHeaderSchema,
1440
+ params: ReportIdParam
1441
+ },
1442
+ responses: {
1443
+ 200: {
1444
+ description: "Successfully deleted feedback"
1445
+ },
1446
+ 404: {
1447
+ content: {
1448
+ "application/json": {
1449
+ schema: z.object({ error: z.string() })
1450
+ }
1451
+ },
1452
+ description: "Unable to retrieve feedback"
1453
+ },
1454
+ 500: {
1455
+ description: "Something wrong happened",
1456
+ content: {
1457
+ "application/json": {
1458
+ schema: z.object({
1459
+ error: z.string()
1460
+ })
1461
+ }
1462
+ }
1463
+ }
1464
+ }
1465
+ });
1466
+ createRoute({
1467
+ // this endpoint is deprecated and will be removed in the future
1468
+ hide: true,
1469
+ method: "get",
1470
+ path: "/api/v1/flow-data/{flowDataId}/explainability",
1471
+ operationId: "retrieveFlowDataExplainability",
1472
+ request: {
1473
+ headers: SupabaseHeaderSchema,
1474
+ params: FlowDataIdParam
1475
+ },
1476
+ responses: {
1477
+ 200: {
1478
+ description: "The explainability of the flow data",
1479
+ content: {
1480
+ "application/json": {
1481
+ schema: FrontendReportExplainabilitySchema
1482
+ }
1483
+ }
1484
+ },
1485
+ 404: {
1486
+ content: {
1487
+ "application/json": {
1488
+ schema: z.object({ error: z.string() })
1489
+ }
1490
+ },
1491
+ description: "Unable to retrieve flow with this id"
1492
+ },
1493
+ 500: {
1494
+ description: "Something wrong happened",
1495
+ content: {
1496
+ "application/json": {
1497
+ schema: z.object({
1498
+ error: z.string()
1499
+ })
1500
+ }
1501
+ }
1502
+ }
1503
+ }
1504
+ });
1505
+ createRoute({
1506
+ method: "get",
1507
+ path: "/api/v1/data-reports/{report_id}/explainability",
1508
+ operationId: "getDataReportExplainability",
1509
+ request: {
1510
+ headers: SupabaseHeaderSchema,
1511
+ params: ReportIdParam
1512
+ },
1513
+ responses: {
1514
+ 200: {
1515
+ description: "The explainability of the report",
1516
+ content: {
1517
+ "application/json": {
1518
+ schema: FrontendReportExplainabilitySchema
1519
+ }
1520
+ }
1521
+ },
1522
+ 404: {
1523
+ content: {
1524
+ "application/json": {
1525
+ schema: z.object({ error: z.string() })
1526
+ }
1527
+ },
1528
+ description: "Unable to retrieve report with this id"
1529
+ },
1530
+ 500: {
1531
+ description: "Something wrong happened",
1532
+ content: {
1533
+ "application/json": {
1534
+ schema: z.object({
1535
+ error: z.string()
1536
+ })
1537
+ }
1538
+ }
1539
+ }
1540
+ }
1541
+ });
1542
+ createRoute({
1543
+ method: "get",
1544
+ path: "/api/v1/data-reports/{report_id}",
1545
+ operationId: "getDataReport",
1546
+ request: {
1547
+ headers: SupabaseHeaderSchema,
1548
+ params: ReportIdParam
1549
+ },
1550
+ responses: {
1551
+ 200: {
1552
+ description: "The visualizations for the report",
1553
+ content: {
1554
+ "application/json": {
1555
+ schema: FrontendReportSchema
1556
+ }
1557
+ }
1558
+ },
1559
+ 404: {
1560
+ content: {
1561
+ "application/json": {
1562
+ schema: z.object({ error: z.string() })
1563
+ }
1564
+ },
1565
+ description: "Unable to retrieve report with this id"
1566
+ },
1567
+ 500: {
1568
+ description: "Something wrong happened",
1569
+ content: {
1570
+ "application/json": {
1571
+ schema: z.object({
1572
+ error: z.string()
1573
+ })
1574
+ }
1575
+ }
1576
+ }
1577
+ }
1578
+ });
1579
+ createRoute({
1580
+ hide: true,
1581
+ method: "get",
1582
+ path: "/api/v1/data-reports/{report_id}/visualizations",
1583
+ operationId: "getDataReportVisualizations",
1584
+ request: {
1585
+ headers: SupabaseHeaderSchema,
1586
+ params: ReportIdParam
1587
+ },
1588
+ responses: {
1589
+ 200: {
1590
+ description: "The visualizations for the report",
1591
+ content: {
1592
+ "application/json": {
1593
+ schema: FrontendReportSchema.merge(z.object({
1594
+ visualizations: z.union([
1595
+ V1FrontendVisualizationSchema,
1596
+ FrontendVisualizationSchema
1597
+ ]).array()
1598
+ }))
1599
+ }
1600
+ }
1601
+ },
1602
+ 404: {
1603
+ content: {
1604
+ "application/json": {
1605
+ schema: z.object({ error: z.string() })
1606
+ }
1607
+ },
1608
+ description: "Unable to retrieve report with this id"
1609
+ },
1610
+ 500: {
1611
+ description: "Something wrong happened",
1612
+ content: {
1613
+ "application/json": {
1614
+ schema: z.object({
1615
+ error: z.string()
1616
+ })
1617
+ }
1618
+ }
1619
+ }
1620
+ }
1621
+ });
1622
+ var CreateFlow = createRoute({
1623
+ method: "post",
1624
+ path: "/api/v1/flows",
1625
+ operationId: "createFlow",
1626
+ request: {
1627
+ headers: SupabaseHeaderSchema,
1628
+ body: {
1629
+ required: true,
1630
+ content: {
1631
+ "application/json": {
1632
+ schema: z.object({
1633
+ userQuery: z.string()
1634
+ })
1635
+ }
1636
+ }
1637
+ }
1638
+ },
1639
+ responses: {
1640
+ 200: {
1641
+ description: "Create a new flow",
1642
+ content: {
1643
+ "application/json": {
1644
+ schema: z.object({
1645
+ status: z.literal("success"),
1646
+ flowId: z.string()
1647
+ })
1648
+ }
1649
+ }
1650
+ },
1651
+ 500: {
1652
+ description: "Something wrong happened",
1653
+ content: {
1654
+ "application/json": {
1655
+ schema: z.object({
1656
+ error: z.string()
1657
+ })
1658
+ }
1659
+ }
1660
+ }
1661
+ }
1662
+ });
1663
+
1664
+ // ../shared/dist/src/endpoints/admin-console/contextualInsights.routes.js
1665
+ var ExtractInsightResponseSchema = z.object({
1666
+ type: z.literal("text"),
1667
+ insight: z.string()
1668
+ }).or(z.object({
1669
+ type: z.literal("missing")
1670
+ }));
1671
+ createRoute({
1672
+ method: "post",
1673
+ path: "/api/v1/admin-console/contextual-insights/generate-template",
1674
+ operationId: "generateInsightTemplate",
1675
+ request: {
1676
+ body: {
1677
+ content: {
1678
+ "application/json": {
1679
+ schema: z.object({
1680
+ request: z.string(),
1681
+ insight_type: z.string(),
1682
+ additional_context: z.string().optional()
1683
+ })
1684
+ }
1685
+ }
1686
+ }
1687
+ },
1688
+ responses: {
1689
+ 200: {
1690
+ description: "Insight template generated successfully",
1691
+ content: {
1692
+ "application/json": {
1693
+ schema: z.object({
1694
+ expanded_request: z.string()
1695
+ })
1696
+ }
1697
+ }
1698
+ },
1699
+ 500: {
1700
+ description: "Something wrong happened",
1701
+ content: {
1702
+ "application/json": {
1703
+ schema: z.object({
1704
+ error: z.string()
1705
+ })
1706
+ }
1707
+ }
1708
+ }
1709
+ }
1710
+ });
1711
+ createRoute({
1712
+ method: "get",
1713
+ path: "/api/v1/admin-console/contextual-insights/preview/{report_id}/data",
1714
+ operationId: "getContextualInsightPreviewData",
1715
+ request: {
1716
+ params: ReportIdParam,
1717
+ query: z.object({
1718
+ limit: limitQueryParams,
1719
+ order: orderQueryParams,
1720
+ cursor: cursorParams,
1721
+ filter: filterQueryParams
1722
+ })
1723
+ },
1724
+ responses: {
1725
+ 200: {
1726
+ description: "The preview data for the contextual insight",
1727
+ content: {
1728
+ "application/json": {
1729
+ schema: SqlPreviewResponseSchema
1730
+ }
1731
+ }
1732
+ },
1733
+ 404: {
1734
+ content: {
1735
+ "application/json": {
1736
+ schema: z.object({ error: z.string() })
1737
+ }
1738
+ },
1739
+ description: "Unable to retrieve flow data with this id"
1740
+ },
1741
+ 500: {
1742
+ description: "Something wrong happened",
1743
+ content: {
1744
+ "application/json": {
1745
+ schema: z.object({
1746
+ error: z.string()
1747
+ })
1748
+ }
1749
+ }
1750
+ }
1751
+ }
1752
+ });
1753
+ createRoute({
1754
+ method: "get",
1755
+ path: "/api/v1/admin-console/contextual-insights/preview/{report_id}/sample-values",
1756
+ operationId: "getContextualInsightColumnSampleValues",
1757
+ request: {
1758
+ params: ReportIdParam,
1759
+ query: z.object({
1760
+ column_name: z.string().openapi({
1761
+ param: {
1762
+ required: true
1763
+ },
1764
+ type: "string",
1765
+ description: "The column name to get sample values for"
1766
+ })
1767
+ })
1768
+ },
1769
+ responses: {
1770
+ 200: {
1771
+ description: "Sample values for the specified column",
1772
+ content: {
1773
+ "application/json": {
1774
+ schema: z.object({
1775
+ options: z.array(z.unknown())
1776
+ })
1777
+ }
1778
+ }
1779
+ },
1780
+ 404: {
1781
+ content: {
1782
+ "application/json": {
1783
+ schema: z.object({ error: z.string() })
1784
+ }
1785
+ },
1786
+ description: "Unable to retrieve flow data with this id"
1787
+ },
1788
+ 500: {
1789
+ description: "Something wrong happened",
1790
+ content: {
1791
+ "application/json": {
1792
+ schema: z.object({
1793
+ error: z.string()
1794
+ })
1795
+ }
1796
+ }
1797
+ }
1798
+ }
1799
+ });
1800
+ var GenerateInsight = createRoute({
1801
+ method: "post",
1802
+ path: "/api/v1/contextual-insights/generate-insight",
1803
+ operationId: "generateInsight",
1804
+ request: {
1805
+ body: {
1806
+ content: {
1807
+ "application/json": {
1808
+ schema: z.object({
1809
+ selected_filter_value: z.string(),
1810
+ custom_id: z.string()
1811
+ })
1812
+ }
1813
+ }
1814
+ }
1815
+ },
1816
+ responses: {
1817
+ 200: {
1818
+ description: "Insight generated successfully",
1819
+ content: {
1820
+ "application/json": {
1821
+ schema: ExtractInsightResponseSchema
1822
+ }
1823
+ }
1824
+ },
1825
+ 404: {
1826
+ description: "Insight not found",
1827
+ content: {
1828
+ "application/json": {
1829
+ schema: z.object({
1830
+ error: z.string()
1831
+ })
1832
+ }
1833
+ }
1834
+ },
1835
+ 400: {
1836
+ description: "Invalid request",
1837
+ content: {
1838
+ "application/json": {
1839
+ schema: z.object({
1840
+ error: z.string()
1841
+ })
1842
+ }
1843
+ }
1844
+ },
1845
+ 500: {
1846
+ description: "Something wrong happened",
1847
+ content: {
1848
+ "application/json": {
1849
+ schema: z.object({
1850
+ error: z.string()
1851
+ })
1852
+ }
1853
+ }
1854
+ }
1855
+ }
1856
+ });
1857
+ createRoute({
1858
+ method: "post",
1859
+ path: "/api/v1/admin-console/contextual-insights/extract-insight",
1860
+ operationId: "extractInsight",
1861
+ request: {
1862
+ body: {
1863
+ content: {
1864
+ "application/json": {
1865
+ schema: z.object({
1866
+ flow_id: z.string(),
1867
+ report_id: z.number(),
1868
+ topic: z.string(),
1869
+ expanded_request: z.string(),
1870
+ insight_type: z.string(),
1871
+ selected_filter: z.string(),
1872
+ selected_filter_value: z.string(),
1873
+ additional_context: z.string().optional()
1874
+ })
1875
+ }
1876
+ }
1877
+ }
1878
+ },
1879
+ responses: {
1880
+ 200: {
1881
+ description: "Insight extracted successfully",
1882
+ content: {
1883
+ "application/json": {
1884
+ schema: ExtractInsightResponseSchema
1885
+ }
1886
+ }
1887
+ },
1888
+ 500: {
1889
+ description: "Something wrong happened",
1890
+ content: {
1891
+ "application/json": {
1892
+ schema: z.object({
1893
+ error: z.string()
1894
+ })
1895
+ }
1896
+ }
1897
+ }
1898
+ }
1899
+ });
1900
+ createRoute({
1901
+ method: "post",
1902
+ path: "/api/v1/admin-console/contextual-insights/suggest-filter-column",
1903
+ operationId: "suggestFilterColumn",
1904
+ request: {
1905
+ body: {
1906
+ content: {
1907
+ "application/json": {
1908
+ schema: z.object({
1909
+ report_id: z.number(),
1910
+ request: z.string(),
1911
+ insight_type: z.string(),
1912
+ additional_context: z.string().optional()
1913
+ })
1914
+ }
1915
+ }
1916
+ }
1917
+ },
1918
+ responses: {
1919
+ 200: {
1920
+ description: "Filter column suggestion generated successfully",
1921
+ content: {
1922
+ "application/json": {
1923
+ schema: z.object({
1924
+ recommended_column: z.string(),
1925
+ reasoning: z.string()
1926
+ })
1927
+ }
1928
+ }
1929
+ },
1930
+ 404: {
1931
+ description: "Report not found",
1932
+ content: {
1933
+ "application/json": {
1934
+ schema: z.object({
1935
+ error: z.string()
1936
+ })
1937
+ }
1938
+ }
1939
+ },
1940
+ 500: {
1941
+ description: "Something wrong happened",
1942
+ content: {
1943
+ "application/json": {
1944
+ schema: z.object({
1945
+ error: z.string()
1946
+ })
1947
+ }
1948
+ }
1949
+ }
1950
+ }
1951
+ });
1952
+
1953
+ // ../shared/dist/src/endpoints/auth.routes.js
1954
+ var GetApiInformationInputSchema = z.object({
1955
+ apiKey: z.string()
1956
+ });
1957
+ var GetApiInformationOutputSchema = z.object({
1958
+ apiUrl: z.string(),
1959
+ anonKey: z.string()
1960
+ });
1961
+ var GetApiInformation = createRoute({
1962
+ method: "get",
1963
+ path: "/api/v1/auth/apiInformation",
1964
+ operationId: "getApiInformation",
1965
+ request: {
1966
+ query: GetApiInformationInputSchema
1967
+ },
1968
+ responses: {
1969
+ 200: {
1970
+ content: {
1971
+ "application/json": {
1972
+ schema: GetApiInformationOutputSchema
1973
+ }
1974
+ },
1975
+ description: "Retrieve the API URL and anon key"
1976
+ },
1977
+ 400: {
1978
+ content: {
1979
+ "application/json": {
1980
+ schema: z.object({ error: z.string() })
1981
+ }
1982
+ },
1983
+ description: "Invalid input"
1984
+ },
1985
+ 500: {
1986
+ content: {
1987
+ "application/json": {
1988
+ schema: z.object({
1989
+ error: z.string()
1990
+ })
1991
+ }
1992
+ },
1993
+ description: "Unable to retrieve the API URL and anon key"
1994
+ }
1995
+ }
1996
+ });
1997
+ createRoute({
1998
+ hide: true,
1999
+ method: "get",
2000
+ path: "/api/auth/apiInformation",
2001
+ operationId: "getApiInformation",
2002
+ request: {
2003
+ query: GetApiInformationInputSchema
2004
+ },
2005
+ responses: {
2006
+ 200: {
2007
+ content: {
2008
+ "application/json": {
2009
+ schema: GetApiInformationOutputSchema
2010
+ }
2011
+ },
2012
+ description: "Retrieve the API URL and anon key"
2013
+ },
2014
+ 400: {
2015
+ content: {
2016
+ "application/json": {
2017
+ schema: z.object({ error: z.string() })
2018
+ }
2019
+ },
2020
+ description: "Invalid input"
2021
+ },
2022
+ 500: {
2023
+ content: {
2024
+ "application/json": {
2025
+ schema: z.object({
2026
+ error: z.string()
2027
+ })
2028
+ }
2029
+ },
2030
+ description: "Unable to retrieve the API URL and anon key"
2031
+ }
2032
+ }
2033
+ });
2034
+ var ExchangeExternalTokenInputSchema = z.object({
2035
+ apiKey: z.string(),
2036
+ externalJWT: z.string()
2037
+ });
2038
+ var ExchangeExternalTokenOutputSchema = z.object({
2039
+ accessToken: z.string(),
2040
+ refreshToken: z.string()
2041
+ });
2042
+ var ExchangeExternalToken = createRoute({
2043
+ method: "post",
2044
+ path: "/api/v1/auth/exchangeExternalToken",
2045
+ operationId: "exchangeExternalToken",
2046
+ request: {
2047
+ body: {
2048
+ required: true,
2049
+ content: {
2050
+ "application/json": {
2051
+ schema: ExchangeExternalTokenInputSchema
2052
+ }
2053
+ }
2054
+ }
2055
+ },
2056
+ responses: {
2057
+ 200: {
2058
+ content: {
2059
+ "application/json": {
2060
+ schema: ExchangeExternalTokenOutputSchema
2061
+ }
2062
+ },
2063
+ description: "Retrieve a JWT for an external user"
2064
+ },
2065
+ 400: {
2066
+ content: {
2067
+ "application/json": {
2068
+ schema: z.object({ error: z.string() })
2069
+ }
2070
+ },
2071
+ description: "Invalid input"
2072
+ },
2073
+ 500: {
2074
+ content: {
2075
+ "application/json": {
2076
+ schema: z.object({
2077
+ error: z.string()
2078
+ })
2079
+ }
2080
+ },
2081
+ description: "Unable to retrieve a JWT for an external user"
2082
+ }
2083
+ }
2084
+ });
2085
+
2086
+ // ../shared/dist/src/schemas/dashboard.js
2087
+ var DashboardTileSchema = z.discriminatedUnion("type", [
2088
+ z.object({
2089
+ type: z.literal("data-report"),
2090
+ flowId: z.string(),
2091
+ flowDataId: z.number(),
2092
+ title: z.string(),
2093
+ col: z.number(),
2094
+ colSpan: z.number(),
2095
+ rowSpan: z.number()
2096
+ }),
2097
+ z.object({
2098
+ type: z.literal("visualization"),
2099
+ visualizationId: z.number(),
2100
+ title: z.string(),
2101
+ col: z.number(),
2102
+ colSpan: z.number(),
2103
+ rowSpan: z.number()
2104
+ })
2105
+ ]);
2106
+ var DashboardSchema = z.object({
2107
+ company_id: z.number(),
2108
+ created_at: z.string(),
2109
+ description: z.string().nullable(),
2110
+ id: z.string().uuid(),
2111
+ name: z.string(),
2112
+ positions: z.array(DashboardTileSchema),
2113
+ updated_at: z.string(),
2114
+ is_removed: z.boolean(),
2115
+ is_public: z.boolean()
2116
+ });
2117
+ var DashboardIdParam = DashboardSchema.shape.id.openapi("DashboardId", {
2118
+ type: "string",
2119
+ format: "uuid"
2120
+ });
2121
+ var FrontendDashboardSchema = DashboardSchema.omit({
2122
+ company_id: true,
2123
+ created_at: true,
2124
+ updated_at: true,
2125
+ is_removed: true
2126
+ });
2127
+
2128
+ // ../shared/dist/src/endpoints/companion/dashboards.routes.js
2129
+ var RetrieveDashboard = createRoute({
2130
+ method: "get",
2131
+ path: "/api/v1/dashboard/{dashboard_id}",
2132
+ operationId: "retrieveDashboard",
2133
+ request: {
2134
+ headers: SupabaseHeaderSchema,
2135
+ params: z.object({
2136
+ dashboard_id: DashboardIdParam
2137
+ })
2138
+ },
2139
+ responses: {
2140
+ 200: {
2141
+ description: "The dashboard with the given id",
2142
+ content: {
2143
+ "application/json": {
2144
+ schema: FrontendDashboardSchema
2145
+ }
2146
+ }
2147
+ },
2148
+ 404: {
2149
+ content: {
2150
+ "application/json": {
2151
+ schema: z.object({ error: z.string() })
2152
+ }
2153
+ },
2154
+ description: "Unable to retrieve dashboard with this id"
2155
+ },
2156
+ 500: {
2157
+ description: "Something wrong happened",
2158
+ content: {
2159
+ "application/json": {
2160
+ schema: z.object({
2161
+ error: z.string()
2162
+ })
2163
+ }
2164
+ }
2165
+ }
2166
+ }
2167
+ });
2168
+
2169
+ // ../shared/dist/src/endpoints/end2end/run.routes.js
2170
+ var End2EndApiResponseSchema = z.discriminatedUnion("status", [
2171
+ z.object({
2172
+ status: z.literal("error"),
2173
+ error: z.string()
2174
+ }),
2175
+ z.object({
2176
+ status: z.literal("success"),
2177
+ flowId: z.string()
2178
+ })
2179
+ ]);
2180
+ var RunEnd2EndFlowRoute = createRoute({
2181
+ method: "post",
2182
+ path: "/api/v1/end2end",
2183
+ operationId: "runEnd2EndFlow",
2184
+ request: {
2185
+ headers: SupabaseHeaderSchema,
2186
+ body: {
2187
+ required: true,
2188
+ content: {
2189
+ "application/json": {
2190
+ schema: z.object({
2191
+ userQuery: z.string(),
2192
+ isNewAnalysisGoal: z.boolean().default(true),
2193
+ difficultyLevel: z.enum(["simple", "moderate", "complex"]).default("complex")
2194
+ })
2195
+ }
2196
+ }
2197
+ }
2198
+ },
2199
+ responses: {
2200
+ 200: {
2201
+ description: "Run the end2end flow",
2202
+ content: {
2203
+ "application/json": {
2204
+ schema: End2EndApiResponseSchema
2205
+ }
2206
+ }
2207
+ }
2208
+ }
2209
+ });
2210
+
2211
+ // ../shared/dist/src/endpoints/companion/triggers.routes.js
2212
+ var TriggerFlowBody = z5.object({
2213
+ triggerId: z5.string(),
2214
+ variables: z5.record(z5.string(), z5.string())
2215
+ });
2216
+ var TriggerFlow = createRoute({
2217
+ method: "post",
2218
+ path: "/api/v1/trigger-flow/",
2219
+ operationId: "triggerFlow",
2220
+ request: {
2221
+ headers: SupabaseHeaderSchema,
2222
+ body: {
2223
+ required: true,
2224
+ description: "Trigger flow request body",
2225
+ content: {
2226
+ "application/json": {
2227
+ schema: TriggerFlowBody
2228
+ }
2229
+ }
2230
+ }
2231
+ },
2232
+ responses: {
2233
+ 200: {
2234
+ description: "Flow id",
2235
+ content: {
2236
+ "application/json": {
2237
+ schema: End2EndApiResponseSchema
2238
+ }
2239
+ }
2240
+ },
2241
+ 400: {
2242
+ content: {
2243
+ "application/json": {
2244
+ schema: z5.object({ error: z5.string() })
2245
+ }
2246
+ },
2247
+ description: "Invalid template or variable values"
2248
+ },
2249
+ 404: {
2250
+ content: {
2251
+ "application/json": {
2252
+ schema: z5.object({ error: z5.string() })
2253
+ }
2254
+ },
2255
+ description: "Unable to retrieve trigger with this id"
2256
+ },
2257
+ 500: {
2258
+ description: "Something wrong happened",
2259
+ content: {
2260
+ "application/json": {
2261
+ schema: z5.object({
2262
+ error: z5.string()
2263
+ })
2264
+ }
2265
+ }
2266
+ }
2267
+ }
2268
+ });
2269
+
2270
+ // src/utils/platform.ts
2271
+ var isBrowser = () => {
2272
+ return typeof window !== "undefined" && typeof document !== "undefined";
2273
+ };
2274
+ var isNode = () => {
2275
+ return typeof process !== "undefined" && typeof process.versions === "object" && "node" in process.versions;
2276
+ };
2277
+ var isReactNative = () => {
2278
+ return typeof navigator !== "undefined" && navigator.product === "ReactNative";
2279
+ };
2280
+ var getPlatform = () => {
2281
+ if (isReactNative()) return "react-native";
2282
+ if (isBrowser()) return "browser";
2283
+ if (isNode()) return "node";
2284
+ return "unknown";
2285
+ };
2286
+
2287
+ // src/adapters/storage/browser.ts
2288
+ var BrowserStorageAdapter = class {
2289
+ // eslint-disable-next-line @typescript-eslint/require-await
2290
+ async getItem(key) {
2291
+ try {
2292
+ return localStorage.getItem(key);
2293
+ } catch (error) {
2294
+ console.warn(
2295
+ "BrowserStorageAdapter: Failed to get item from localStorage",
2296
+ error
2297
+ );
2298
+ return null;
2299
+ }
2300
+ }
2301
+ // eslint-disable-next-line @typescript-eslint/require-await
2302
+ async setItem(key, value) {
2303
+ try {
2304
+ localStorage.setItem(key, value);
2305
+ } catch (error) {
2306
+ console.warn(
2307
+ "BrowserStorageAdapter: Failed to set item in localStorage",
2308
+ error
2309
+ );
2310
+ throw error;
2311
+ }
2312
+ }
2313
+ // eslint-disable-next-line @typescript-eslint/require-await
2314
+ async removeItem(key) {
2315
+ try {
2316
+ localStorage.removeItem(key);
2317
+ } catch (error) {
2318
+ console.warn(
2319
+ "BrowserStorageAdapter: Failed to remove item from localStorage",
2320
+ error
2321
+ );
2322
+ throw error;
2323
+ }
2324
+ }
2325
+ };
2326
+
2327
+ // src/adapters/storage/memory.ts
2328
+ var MemoryStorageAdapter = class {
2329
+ storage = /* @__PURE__ */ new Map();
2330
+ // eslint-disable-next-line @typescript-eslint/require-await
2331
+ async getItem(key) {
2332
+ const value = this.storage.get(key);
2333
+ return value !== void 0 ? value : null;
2334
+ }
2335
+ // eslint-disable-next-line @typescript-eslint/require-await
2336
+ async setItem(key, value) {
2337
+ this.storage.set(key, value);
2338
+ }
2339
+ // eslint-disable-next-line @typescript-eslint/require-await
2340
+ async removeItem(key) {
2341
+ this.storage.delete(key);
2342
+ }
2343
+ };
2344
+
2345
+ // src/adapters/storage/factory.ts
2346
+ var createStorageAdapter = () => {
2347
+ const platform = getPlatform();
2348
+ switch (platform) {
2349
+ case "browser":
2350
+ return new BrowserStorageAdapter();
2351
+ case "node":
2352
+ return new MemoryStorageAdapter();
2353
+ case "react-native":
2354
+ throw new Error("Please provide AsyncStorage for React Native");
2355
+ case "unknown":
2356
+ default:
2357
+ console.warn(
2358
+ `Unknown platform detected: ${platform}. Defaulting to in memory storage.`
2359
+ );
2360
+ return new MemoryStorageAdapter();
2361
+ }
2362
+ };
2363
+ var hashString = (value) => {
2364
+ const encoder = new TextEncoder();
2365
+ const data = encoder.encode(value);
2366
+ const hash = sha256(data);
2367
+ return Array.from(hash).map((b) => b.toString(16).padStart(2, "0")).join("");
2368
+ };
2369
+
2370
+ // package.json
2371
+ var package_default = {
2372
+ version: "0.0.60"};
2373
+
2374
+ // src/core/MageMetricsEventEmitter.ts
2375
+ var MageMetricsEventEmitter = class {
2376
+ listeners = /* @__PURE__ */ new Map();
2377
+ addEventListener(type, listener, options) {
2378
+ if (!this.listeners.has(type)) {
2379
+ this.listeners.set(type, /* @__PURE__ */ new Set());
2380
+ }
2381
+ if (options?.signal) {
2382
+ if (options.signal.aborted) {
2383
+ return;
2384
+ }
2385
+ const abortHandler = () => {
2386
+ this.removeEventListener(type, listener);
2387
+ };
2388
+ options.signal.addEventListener("abort", abortHandler, { once: true });
2389
+ }
2390
+ this.listeners.get(type).add(listener);
2391
+ }
2392
+ removeEventListener(type, listener) {
2393
+ const typeListeners = this.listeners.get(type);
2394
+ if (typeListeners) {
2395
+ typeListeners.delete(listener);
2396
+ if (typeListeners.size === 0) {
2397
+ this.listeners.delete(type);
2398
+ }
2399
+ }
2400
+ }
2401
+ dispatch(type, detail) {
2402
+ const typeListeners = this.listeners.get(type);
2403
+ if (typeListeners) {
2404
+ const event = { type, detail };
2405
+ typeListeners.forEach((listener) => {
2406
+ try {
2407
+ listener(event);
2408
+ } catch (error) {
2409
+ console.error(`Error in event listener for "${type}":`, error);
2410
+ }
2411
+ });
2412
+ }
2413
+ }
2414
+ };
2415
+
2416
+ // src/core/types.ts
2417
+ var TOKEN_STORAGE_KEY = "mm-ai-sp-token";
2418
+ var CHECK_KEY = "mm-ai-check-key";
2419
+
2420
+ // src/core/MageMetricsClient.ts
2421
+ var MM_CLIENT_VERSION = package_default.version;
2422
+ var getPublicApiClient = (apiUrl, apiKey) => {
2423
+ const client = createApiClient({ baseUrl: apiUrl });
2424
+ client.use(throwOnError);
2425
+ client.use(addVersionHeader(MM_CLIENT_VERSION));
2426
+ client.use(addApiKeyHeader(apiKey));
2427
+ return client;
2428
+ };
2429
+ var MageMetricsClient = class {
2430
+ config;
2431
+ authState = "initializing";
2432
+ supabaseClient = null;
2433
+ internalApiClient = null;
2434
+ noAuthApiClient = null;
2435
+ authApiResponse = null;
2436
+ authPromise = null;
2437
+ processedJwt = Symbol("initial");
2438
+ storageAdapter;
2439
+ events = new MageMetricsEventEmitter();
2440
+ constructor(config) {
2441
+ this.config = config;
2442
+ this.storageAdapter = config.storageAdapter || createStorageAdapter();
2443
+ void this.initializeAuth();
2444
+ }
2445
+ /**
2446
+ * Add an event listener for authentication state changes
2447
+ * @param type the type of the event
2448
+ * @param listener the listener to add
2449
+ * @param options options for the event listener
2450
+ * @param options.signal an optional AbortSignal to abort the event listener
2451
+ */
2452
+ addEventListener(type, listener, options) {
2453
+ this.events.addEventListener(type, listener, options);
2454
+ }
2455
+ /**
2456
+ * Remove an event listener
2457
+ * @param type the type of the event
2458
+ * @param listener the listener to remove
2459
+ */
2460
+ removeEventListener(type, listener) {
2461
+ this.events.removeEventListener(type, listener);
2462
+ }
2463
+ async waitForAuth() {
2464
+ if (this.authState === "ready") {
2465
+ return Promise.resolve();
2466
+ }
2467
+ if (this.authState === "error") {
2468
+ throw new Error("Authentication failed");
2469
+ }
2470
+ if (this.authPromise) {
2471
+ return this.authPromise;
2472
+ }
2473
+ throw new Error("Authentication not initialized");
2474
+ }
2475
+ async updateExternalJwt(jwt) {
2476
+ if (this.config.externalJwt === jwt) return;
2477
+ this.config.externalJwt = jwt;
2478
+ this.processedJwt = Symbol("updating");
2479
+ await this.performAuthFlow();
2480
+ }
2481
+ get state() {
2482
+ return this.authState;
2483
+ }
2484
+ async getAuthHeaders() {
2485
+ await this.waitForAuth();
2486
+ if (!this.supabaseClient) {
2487
+ return {};
2488
+ }
2489
+ const session = await this.supabaseClient.getSession();
2490
+ if (!session.data.session) {
2491
+ return {};
2492
+ }
2493
+ const { access_token } = session.data.session;
2494
+ const headers = {};
2495
+ if (access_token) {
2496
+ headers["sp-access-token"] = access_token;
2497
+ }
2498
+ return headers;
2499
+ }
2500
+ async clearStorage() {
2501
+ try {
2502
+ await this.storageAdapter.removeItem(TOKEN_STORAGE_KEY);
2503
+ await this.storageAdapter.removeItem(CHECK_KEY);
2504
+ } catch {
2505
+ }
2506
+ }
2507
+ async logout() {
2508
+ if (this.supabaseClient) {
2509
+ await this.supabaseClient.signOut({ scope: "local" });
2510
+ }
2511
+ await this.clearStorage();
2512
+ }
2513
+ /**
2514
+ * Public API methods that automatically wait for authentication
2515
+ */
2516
+ api = {
2517
+ getRecentFlows: async (params = {}) => {
2518
+ await this.waitForAuth();
2519
+ if (!this.internalApiClient) throw new Error("API client not ready");
2520
+ const { data, error, response } = await this.internalApiClient.GET(
2521
+ RetrieveRecentFlows.path,
2522
+ {
2523
+ params: {
2524
+ query: {
2525
+ limit: params.limit ?? 10
2526
+ }
2527
+ }
2528
+ }
2529
+ );
2530
+ if (error) {
2531
+ throw new ApiError(error.error, response, {
2532
+ status: response.status,
2533
+ statusText: response.statusText,
2534
+ url: response.url,
2535
+ method: "GET"
2536
+ });
2537
+ }
2538
+ return data;
2539
+ },
2540
+ /**
2541
+ * @deprecated Use `createFlow` instead.
2542
+ * @param request the user request
2543
+ * @returns the id of the created flow
2544
+ */
2545
+ startFlow: async (request) => {
2546
+ await this.waitForAuth();
2547
+ if (!this.internalApiClient) throw new Error("API client not ready");
2548
+ if ("query" in request) {
2549
+ const { data, response } = await this.internalApiClient.POST(
2550
+ RunEnd2EndFlowRoute.path,
2551
+ {
2552
+ body: {
2553
+ userQuery: request.query,
2554
+ isNewAnalysisGoal: true,
2555
+ difficultyLevel: "complex"
2556
+ }
2557
+ }
2558
+ );
2559
+ if (!data || data.status === "error") {
2560
+ throw new ApiError(data?.error ?? "Failed to start flow", response, {
2561
+ status: response.status,
2562
+ statusText: response.statusText,
2563
+ url: response.url,
2564
+ method: "POST"
2565
+ });
2566
+ }
2567
+ return data.flowId;
2568
+ } else {
2569
+ const { triggerId, variables } = request;
2570
+ const { data, response } = await this.internalApiClient.POST(
2571
+ TriggerFlow.path,
2572
+ {
2573
+ body: {
2574
+ triggerId,
2575
+ variables
2576
+ }
2577
+ }
2578
+ );
2579
+ if (!data || data.status === "error") {
2580
+ throw new ApiError(
2581
+ data?.error ?? "Failed to trigger flow",
2582
+ response,
2583
+ {
2584
+ status: response.status,
2585
+ statusText: response.statusText,
2586
+ url: response.url,
2587
+ method: "POST"
2588
+ }
2589
+ );
2590
+ }
2591
+ return data.flowId;
2592
+ }
2593
+ },
2594
+ createFlow: async (request) => {
2595
+ await this.waitForAuth();
2596
+ if (!this.internalApiClient) throw new Error("API client not ready");
2597
+ if ("query" in request) {
2598
+ const { data, error, response } = await this.internalApiClient.POST(
2599
+ CreateFlow.path,
2600
+ {
2601
+ body: {
2602
+ userQuery: request.query
2603
+ }
2604
+ }
2605
+ );
2606
+ if (error) {
2607
+ throw new ApiError(error.error, response, {
2608
+ status: response.status,
2609
+ statusText: response.statusText,
2610
+ url: response.url,
2611
+ method: "POST"
2612
+ });
2613
+ }
2614
+ return { flowId: data.flowId };
2615
+ } else {
2616
+ const { triggerId, variables } = request;
2617
+ const { data, response } = await this.internalApiClient.POST(
2618
+ TriggerFlow.path,
2619
+ {
2620
+ body: {
2621
+ triggerId,
2622
+ variables
2623
+ }
2624
+ }
2625
+ );
2626
+ if (!data || data.status === "error") {
2627
+ throw new ApiError(
2628
+ data?.error ?? "Failed to trigger flow",
2629
+ response,
2630
+ {
2631
+ status: response.status,
2632
+ statusText: response.statusText,
2633
+ url: response.url,
2634
+ method: "POST"
2635
+ }
2636
+ );
2637
+ }
2638
+ return { flowId: data.flowId };
2639
+ }
2640
+ },
2641
+ getDashboard: async (dashboardId) => {
2642
+ await this.waitForAuth();
2643
+ if (!this.internalApiClient) throw new Error("API client not ready");
2644
+ const { data, error, response } = await this.internalApiClient.GET(
2645
+ RetrieveDashboard.path,
2646
+ {
2647
+ params: {
2648
+ path: {
2649
+ dashboard_id: dashboardId
2650
+ }
2651
+ }
2652
+ }
2653
+ );
2654
+ if (error) {
2655
+ throw new ApiError(error.error, response, {
2656
+ status: response.status,
2657
+ statusText: response.statusText,
2658
+ url: response.url,
2659
+ method: "GET"
2660
+ });
2661
+ }
2662
+ return data;
2663
+ },
2664
+ exportReportData: async (reportId, format = "blob") => {
2665
+ await this.waitForAuth();
2666
+ if (!this.internalApiClient) throw new Error("API client not ready");
2667
+ const { data, error, response } = await this.internalApiClient.GET(
2668
+ ExportReportData.path,
2669
+ {
2670
+ params: {
2671
+ path: {
2672
+ report_id: String(reportId)
2673
+ }
2674
+ },
2675
+ parseAs: format
2676
+ }
2677
+ );
2678
+ if (error) {
2679
+ throw new ApiError(error.error, response, {
2680
+ status: response.status,
2681
+ statusText: response.statusText,
2682
+ url: response.url,
2683
+ method: "GET"
2684
+ });
2685
+ }
2686
+ const contentDisposition = response.headers.get("content-disposition");
2687
+ const filename = contentDisposition ? contentDisposition.split("filename=")[1]?.replace(/"/g, "") || `mm-export-${reportId}.csv` : `mm-export-${reportId}.csv`;
2688
+ return { filename, data };
2689
+ },
2690
+ generateContextualInsight: async (payload) => {
2691
+ await this.waitForAuth();
2692
+ if (!this.internalApiClient) throw new Error("API client not ready");
2693
+ const { data, error, response } = await this.internalApiClient.POST(
2694
+ GenerateInsight.path,
2695
+ {
2696
+ body: {
2697
+ selected_filter_value: payload.selectedFilterValue,
2698
+ custom_id: payload.customId
2699
+ }
2700
+ }
2701
+ );
2702
+ if (error) {
2703
+ throw new ApiError(error.error, response, {
2704
+ status: response.status,
2705
+ statusText: response.statusText,
2706
+ url: response.url,
2707
+ method: "POST"
2708
+ });
2709
+ }
2710
+ return data;
2711
+ }
2712
+ };
2713
+ /**
2714
+ * Initialize authentication flow
2715
+ */
2716
+ async initializeAuth() {
2717
+ this.authPromise = this.performAuthFlow();
2718
+ try {
2719
+ await this.authPromise;
2720
+ } catch (error) {
2721
+ console.error("Failed to initialize authentication:", error);
2722
+ }
2723
+ }
2724
+ /**
2725
+ * Perform the complete authentication flow
2726
+ */
2727
+ async performAuthFlow() {
2728
+ try {
2729
+ this.setState("initializing");
2730
+ const apiInfo = await this.getApiInformation();
2731
+ this.initializeSupabaseClient(apiInfo.anonKey, apiInfo.apiUrl);
2732
+ this.initializeApiClient();
2733
+ await this.handleAuthentication();
2734
+ if (this.config.externalJwt) {
2735
+ await this.saveCheckKey(this.config.externalJwt, this.config.apiKey);
2736
+ }
2737
+ this.setState("ready");
2738
+ } catch (error) {
2739
+ console.error("Authentication flow failed:", error);
2740
+ this.setState("error");
2741
+ throw error;
2742
+ }
2743
+ }
2744
+ async getApiInformation() {
2745
+ if (!this.noAuthApiClient || !this.authApiResponse) {
2746
+ this.noAuthApiClient = getPublicApiClient(
2747
+ this.config.apiUrl,
2748
+ this.config.apiKey
2749
+ );
2750
+ const { data } = await this.noAuthApiClient.GET(GetApiInformation.path, {
2751
+ params: {
2752
+ query: {
2753
+ apiKey: this.config.apiKey
2754
+ }
2755
+ }
2756
+ });
2757
+ if (!data) {
2758
+ throw new Error("Failed to fetch API information");
2759
+ }
2760
+ this.authApiResponse = data;
2761
+ }
2762
+ return this.authApiResponse;
2763
+ }
2764
+ initializeSupabaseClient(anonKey, apiUrl) {
2765
+ if (!this.supabaseClient) {
2766
+ this.supabaseClient = new GoTrueClient({
2767
+ url: `${apiUrl}/auth/v1`,
2768
+ storageKey: TOKEN_STORAGE_KEY,
2769
+ headers: {
2770
+ apiKey: anonKey
2771
+ }
2772
+ });
2773
+ this.supabaseClient.onAuthStateChange((event, session) => {
2774
+ console.debug("Supabase auth state change:", event, !!session);
2775
+ if (event === "TOKEN_REFRESHED" && session) {
2776
+ console.debug("Token refreshed successfully");
2777
+ this.setState("ready");
2778
+ } else if (event === "SIGNED_OUT") {
2779
+ console.debug("User signed out");
2780
+ void this.clearStorage();
2781
+ this.setState("initializing");
2782
+ }
2783
+ });
2784
+ }
2785
+ }
2786
+ /* This method always waits for authentication to complete before returning the client */
2787
+ async client() {
2788
+ await this.waitForAuth();
2789
+ if (this.authState === "ready") {
2790
+ if (!this.internalApiClient) {
2791
+ throw new Error(
2792
+ "Client is ready but API client not available. This should never happen"
2793
+ );
2794
+ }
2795
+ return this.internalApiClient;
2796
+ }
2797
+ throw new Error(`Client is not available in auth state: ${this.authState}`);
2798
+ }
2799
+ /**
2800
+ * Initialize the API client with Supabase headers
2801
+ */
2802
+ initializeApiClient() {
2803
+ this.internalApiClient = createApiClient({ baseUrl: this.config.apiUrl });
2804
+ this.internalApiClient.use(throwOnError);
2805
+ this.internalApiClient.use(this.createSupabaseHeaderMiddleware());
2806
+ this.internalApiClient.use(addVersionHeader(MM_CLIENT_VERSION));
2807
+ }
2808
+ /**
2809
+ * Handle the authentication logic (check session or exchange token)
2810
+ */
2811
+ async handleAuthentication() {
2812
+ if (!this.supabaseClient) {
2813
+ throw new Error("Supabase client not initialized");
2814
+ }
2815
+ if (this.processedJwt === this.config.externalJwt) {
2816
+ return;
2817
+ }
2818
+ try {
2819
+ const { data, error } = await this.supabaseClient.getSession();
2820
+ if (error) {
2821
+ console.error("Error getting session:", error);
2822
+ this.processedJwt = this.config.externalJwt || "";
2823
+ return;
2824
+ }
2825
+ const isCheckValid = await this.compareCheckKey(
2826
+ this.config.externalJwt ?? "",
2827
+ this.config.apiKey
2828
+ );
2829
+ if (data.session && this.config.externalJwt && isCheckValid) {
2830
+ console.debug("Session found, authentication ready");
2831
+ this.processedJwt = this.config.externalJwt || "";
2832
+ } else if (this.config.externalJwt) {
2833
+ console.debug("No session found, exchanging external JWT");
2834
+ await this.clearCheckKey();
2835
+ await this.exchangeExternalToken();
2836
+ this.processedJwt = this.config.externalJwt;
2837
+ } else {
2838
+ console.debug("No session and no external JWT provided");
2839
+ this.processedJwt = this.config.externalJwt || "";
2840
+ }
2841
+ } catch (error) {
2842
+ console.error("Unhandled error during authentication:", error);
2843
+ this.processedJwt = this.config.externalJwt || "";
2844
+ throw error;
2845
+ }
2846
+ }
2847
+ /**
2848
+ * Exchange external JWT for Supabase tokens
2849
+ */
2850
+ async exchangeExternalToken() {
2851
+ if (!this.noAuthApiClient || !this.supabaseClient || !this.config.externalJwt) {
2852
+ throw new Error(
2853
+ "Required clients or JWT not available for token exchange"
2854
+ );
2855
+ }
2856
+ const { data } = await this.noAuthApiClient.POST(
2857
+ ExchangeExternalToken.path,
2858
+ {
2859
+ body: {
2860
+ apiKey: this.config.apiKey,
2861
+ externalJWT: this.config.externalJwt
2862
+ },
2863
+ headers: this.config.additionalHeaders || {}
2864
+ }
2865
+ );
2866
+ if (!data) {
2867
+ throw new Error("Failed to exchange tokens");
2868
+ }
2869
+ await this.supabaseClient.setSession({
2870
+ access_token: data.accessToken,
2871
+ refresh_token: data.refreshToken
2872
+ });
2873
+ console.debug("Token exchange successful, session set");
2874
+ }
2875
+ createSupabaseHeaderMiddleware() {
2876
+ const supabaseClient = this.supabaseClient;
2877
+ return {
2878
+ async onRequest({ request }) {
2879
+ if (!supabaseClient) {
2880
+ return request;
2881
+ }
2882
+ const session = await supabaseClient.getSession();
2883
+ if (!session.data.session) {
2884
+ return request;
2885
+ }
2886
+ const { access_token } = session.data.session;
2887
+ if (access_token) {
2888
+ request.headers.set("sp-access-token", access_token);
2889
+ }
2890
+ return request;
2891
+ }
2892
+ };
2893
+ }
2894
+ setState(state) {
2895
+ this.authState = state;
2896
+ this.events.dispatch("authStateChange", state);
2897
+ }
2898
+ encodeCheckKey(externalJwt, apiKey) {
2899
+ return hashString(
2900
+ JSON.stringify({
2901
+ externalJwt,
2902
+ apiKey
2903
+ })
2904
+ );
2905
+ }
2906
+ async saveCheckKey(externalJwt, apiKey) {
2907
+ const encodedKey = this.encodeCheckKey(externalJwt, apiKey);
2908
+ await this.storageAdapter.setItem(CHECK_KEY, encodedKey);
2909
+ }
2910
+ async compareCheckKey(externalJwt, apiKey) {
2911
+ const storedKey = await this.storageAdapter.getItem(CHECK_KEY);
2912
+ if (!storedKey) return false;
2913
+ const newValue = this.encodeCheckKey(externalJwt, apiKey);
2914
+ return storedKey === newValue;
2915
+ }
2916
+ async clearCheckKey() {
2917
+ await this.storageAdapter.removeItem(CHECK_KEY);
2918
+ }
2919
+ };
2920
+
2921
+ export { BrowserStorageAdapter, CHECK_KEY, MageMetricsClient, MageMetricsEventEmitter, MemoryStorageAdapter, TOKEN_STORAGE_KEY, getPublicApiClient };
2922
+ //# sourceMappingURL=index.js.map
2923
+ //# sourceMappingURL=index.js.map