@bino-bi/bn-template-engine 1.0.0-alpha.11 → 1.0.0-alpha.13

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 (127) hide show
  1. package/dist/bn-template-engine/bn-template-engine.esm.js +1 -1
  2. package/dist/bn-template-engine/p-3c827826.entry.js +1 -0
  3. package/dist/bn-template-engine/p-46699464.entry.js +1 -0
  4. package/dist/bn-template-engine/{p-e783733e.entry.js → p-52097456.entry.js} +1 -1
  5. package/dist/bn-template-engine/p-637e3b8f.entry.js +1 -0
  6. package/dist/bn-template-engine/{p-c2cbb8ea.entry.js → p-67eae33e.entry.js} +1 -1
  7. package/dist/bn-template-engine/{p-fdb3e99a.entry.js → p-82023539.entry.js} +1 -1
  8. package/dist/bn-template-engine/p-BVFHvEXF.js +1 -0
  9. package/dist/bn-template-engine/p-BjBz5cSL.js +1 -0
  10. package/dist/bn-template-engine/p-CQnZV3JG.js +1 -0
  11. package/dist/bn-template-engine/p-DHheVOfP.js +1 -0
  12. package/dist/bn-template-engine/{p-e94b4e31.entry.js → p-ab3ea8cf.entry.js} +1 -1
  13. package/dist/cjs/bn-asset_21.cjs.entry.js +576 -730
  14. package/dist/cjs/bn-grid.cjs.entry.js +2 -2
  15. package/dist/cjs/bn-image.cjs.entry.js +2 -2
  16. package/dist/cjs/bn-internationalization.cjs.entry.js +2 -2
  17. package/dist/cjs/bn-template-engine.cjs.js +1 -1
  18. package/dist/cjs/bn-text.cjs.entry.js +3 -3
  19. package/dist/cjs/bn-tree.cjs.entry.js +2 -2
  20. package/dist/cjs/context-protocol-Op7uUwN3.js +9214 -0
  21. package/dist/cjs/editor-companion.cjs.entry.js +13 -6
  22. package/dist/cjs/loader.cjs.js +1 -1
  23. package/dist/cjs/{scaling-eyzCrFB8.js → scaling-57N4Cxb_.js} +44 -40
  24. package/dist/cjs/{withBodyObserver-D7BKWN2N.js → withBodyObserver-BKUE_ypL.js} +12 -7
  25. package/dist/cjs/withStyled-C2kmGAK3.js +1405 -0
  26. package/dist/collection/components/bn-chart-structure/bn-chart-structure.js +11 -6
  27. package/dist/collection/components/bn-chart-structure/ibcs-chart-structure.js +50 -22
  28. package/dist/collection/components/bn-chart-structure/utils/StructureChart.js +51 -48
  29. package/dist/collection/components/bn-chart-structure/utils/model/StructureChartComponentConfig.js +5 -4
  30. package/dist/collection/components/bn-chart-time/bn-chart-time.js +11 -6
  31. package/dist/collection/components/bn-chart-time/ibcs-chart-time.js +47 -22
  32. package/dist/collection/components/bn-chart-time/utils/TimeChart.js +76 -60
  33. package/dist/collection/components/bn-chart-time/utils/model/TimeChartComponentConfig.js +5 -4
  34. package/dist/collection/components/bn-chart-time/utils/model/TimeChartDataRow.js +2 -0
  35. package/dist/collection/components/bn-dataset/bn-dataset.js +214 -23
  36. package/dist/collection/components/bn-datasource/bn-datasource.js +27 -9
  37. package/dist/collection/components/bn-table/bn-table.js +13 -5
  38. package/dist/collection/components/bn-table/ibcs-table.js +52 -25
  39. package/dist/collection/components/bn-table/utils/Table.js +27 -21
  40. package/dist/collection/components/bn-table/utils/factories/tableDataSetFactory.js +2 -2
  41. package/dist/collection/components/bn-table/utils/helper/DataQuery.js +52 -43
  42. package/dist/collection/components/bn-table/utils/helper/QueryGroup.js +4 -9
  43. package/dist/collection/components/bn-table/utils/model/TableComponentConfig.js +5 -4
  44. package/dist/collection/components/editor-companion/editor-companion.js +12 -5
  45. package/dist/collection/context/scopedDb.js +113 -0
  46. package/dist/collection/stores/createScopedStores.js +3 -4
  47. package/dist/collection/utils/dataAnalyzer.js +14 -8
  48. package/dist/collection/utils/withBodyObserver.js +12 -7
  49. package/dist/collection/utils/withDataset.js +43 -39
  50. package/dist/collection/utils/withDatasource.js +28 -18
  51. package/dist/components/DataFormatDigits.js +1 -1
  52. package/dist/components/DateStringFactory.js +1 -1
  53. package/dist/components/Order.js +1 -1
  54. package/dist/components/SVGVariancesStyleGroup.js +1 -1
  55. package/dist/components/bn-chart-structure.js +1 -1
  56. package/dist/components/bn-chart-time.js +1 -1
  57. package/dist/components/bn-dataset.js +1 -1
  58. package/dist/components/bn-datasource.js +1 -1
  59. package/dist/components/bn-table.js +1 -1
  60. package/dist/components/bn-title2.js +1 -1
  61. package/dist/components/context-protocol.js +1 -1
  62. package/dist/components/editor-companion.js +1 -1
  63. package/dist/components/ibcs-chart-structure2.js +1 -1
  64. package/dist/components/ibcs-chart-time2.js +1 -1
  65. package/dist/components/ibcs-table2.js +1 -1
  66. package/dist/components/ibcs-title2.js +1 -1
  67. package/dist/components/ibcsRuleSet.js +1 -1
  68. package/dist/components/luxon.js +1 -0
  69. package/dist/components/scaling.js +1 -1
  70. package/dist/components/withBodyObserver.js +1 -1
  71. package/dist/esm/bn-asset_21.entry.js +571 -725
  72. package/dist/esm/bn-grid.entry.js +2 -2
  73. package/dist/esm/bn-image.entry.js +2 -2
  74. package/dist/esm/bn-internationalization.entry.js +2 -2
  75. package/dist/esm/bn-template-engine.js +1 -1
  76. package/dist/esm/bn-text.entry.js +3 -3
  77. package/dist/esm/bn-tree.entry.js +2 -2
  78. package/dist/esm/context-protocol-BDhzNbeD.js +9204 -0
  79. package/dist/esm/editor-companion.entry.js +13 -6
  80. package/dist/esm/loader.js +1 -1
  81. package/dist/esm/{scaling-BzbiBnuN.js → scaling-La1Ow72h.js} +44 -40
  82. package/dist/esm/{withBodyObserver-AFk2wwHT.js → withBodyObserver-IokS6fHD.js} +12 -7
  83. package/dist/esm/withStyled-Bl9cSoRW.js +1372 -0
  84. package/dist/types/components/bn-chart-structure/bn-chart-structure.d.ts +4 -2
  85. package/dist/types/components/bn-chart-structure/ibcs-chart-structure.d.ts +7 -3
  86. package/dist/types/components/bn-chart-structure/utils/StructureChart.d.ts +11 -12
  87. package/dist/types/components/bn-chart-structure/utils/model/StructureChartComponentConfig.d.ts +5 -3
  88. package/dist/types/components/bn-chart-time/bn-chart-time.d.ts +4 -2
  89. package/dist/types/components/bn-chart-time/ibcs-chart-time.d.ts +7 -3
  90. package/dist/types/components/bn-chart-time/utils/TimeChart.d.ts +11 -12
  91. package/dist/types/components/bn-chart-time/utils/model/TimeChartComponentConfig.d.ts +5 -3
  92. package/dist/types/components/bn-dataset/bn-dataset.d.ts +39 -5
  93. package/dist/types/components/bn-datasource/bn-datasource.d.ts +5 -0
  94. package/dist/types/components/bn-table/bn-table.d.ts +4 -2
  95. package/dist/types/components/bn-table/ibcs-table.d.ts +11 -3
  96. package/dist/types/components/bn-table/utils/Table.d.ts +8 -6
  97. package/dist/types/components/bn-table/utils/factories/tableDataSetFactory.d.ts +2 -2
  98. package/dist/types/components/bn-table/utils/helper/DataQuery.d.ts +7 -3
  99. package/dist/types/components/bn-table/utils/helper/QueryGroup.d.ts +4 -5
  100. package/dist/types/components/bn-table/utils/model/TableComponentConfig.d.ts +5 -3
  101. package/dist/types/components/editor-companion/editor-companion.d.ts +2 -0
  102. package/dist/types/components.d.ts +105 -46
  103. package/dist/types/context/context-protocol.d.ts +4 -3
  104. package/dist/types/context/scopedDb.d.ts +37 -0
  105. package/dist/types/stores/createScopedStores.d.ts +1 -2
  106. package/dist/types/utils/DateStringFactory.d.ts +1 -1
  107. package/dist/types/utils/dataAnalyzer.d.ts +2 -1
  108. package/dist/types/utils/withDataset.d.ts +6 -2
  109. package/dist/types/utils/withDatasource.d.ts +3 -3
  110. package/package.json +2 -1
  111. package/dist/bn-template-engine/p-095f74d7.entry.js +0 -1
  112. package/dist/bn-template-engine/p-14318b0d.entry.js +0 -1
  113. package/dist/bn-template-engine/p-2133e02b.entry.js +0 -1
  114. package/dist/bn-template-engine/p-7HSTE79g.js +0 -1
  115. package/dist/bn-template-engine/p-Bi2wx-el.js +0 -1
  116. package/dist/bn-template-engine/p-CWiZks2h.js +0 -1
  117. package/dist/bn-template-engine/p-DSXNgKLa.js +0 -1
  118. package/dist/cjs/context-protocol-B_jipZpJ.js +0 -665
  119. package/dist/cjs/withStyled-V7xz_x1c.js +0 -9535
  120. package/dist/collection/stores/datasets.js +0 -14
  121. package/dist/collection/stores/datasources.js +0 -14
  122. package/dist/components/_commonjsHelpers.js +0 -1
  123. package/dist/components/alasql.min.js +0 -1
  124. package/dist/esm/context-protocol-D-o_UZ33.js +0 -658
  125. package/dist/esm/withStyled-5RqF8WBL.js +0 -9501
  126. package/dist/types/stores/datasets.d.ts +0 -14
  127. package/dist/types/stores/datasources.d.ts +0 -14
@@ -4,10 +4,10 @@ import { DataPoint, Scenario } from "./model";
4
4
  import { AreaFill, Axis, HookLocation, Label, StackedColumn, } from "./elements";
5
5
  import { ScenarioFactory } from "./factories";
6
6
  import { LabelCollisionManager, SCENARIO_PRIORITY } from "./helper";
7
- import alasql from "alasql";
8
7
  import CalculateSize from "calculate-size";
9
8
  import { ScaleFactorsTimeChart } from "./model/styles/ScaleFactorsTimeChart";
10
9
  import { DateTime } from "luxon";
10
+ import { buildFromExpr } from "../../../context/scopedDb";
11
11
  import { DateDistance, DateStringFactory } from "../../../utils/DateStringFactory";
12
12
  import { AxisLabelsMode, ChartMode, StackBy, StackMode } from "../../../utils/constants";
13
13
  import { getScenarioPrefix, IBCS_LAYER_ORDER } from "../../../utils/stackColors";
@@ -50,7 +50,7 @@ var VarianceType;
50
50
  * Auto chart mode: when dataModel.length exceeds maxBars, switches from bar to line.
51
51
  */
52
52
  export class TimeChart {
53
- constructor(ruleSet, config, styles, availableWidth = 0) {
53
+ constructor(ruleSet, db, tableName, config, styles, availableWidth = 0) {
54
54
  this.CSS_CATEGORIES = "categories";
55
55
  this.dataModel = [];
56
56
  this.variancesDataModel = [];
@@ -63,7 +63,8 @@ export class TimeChart {
63
63
  this.pixelPerPercentage = 1;
64
64
  this.hideAxisLabels = false;
65
65
  this.axisScenario = Scenario.AC1;
66
- this.preparedDataSet = [];
66
+ this.fromExpr = "";
67
+ this.rowCount = 0;
67
68
  this.axisCategoryArea = { width: 0, height: 0 };
68
69
  this.scenariosArea = { width: 0, height: 0 };
69
70
  this.state = FactoryState.DIRTY;
@@ -85,7 +86,8 @@ export class TimeChart {
85
86
  this.availableWidth = 0;
86
87
  this.overflowConfig = null;
87
88
  this.lastScenarios = [];
88
- this.initSQLFunctions();
89
+ this.db = db;
90
+ this.tableName = tableName;
89
91
  this.ruleSet = ruleSet || new IBCSRuleSet();
90
92
  this.i18n = this.createI18n(new Map());
91
93
  this.styles = styles;
@@ -96,18 +98,6 @@ export class TimeChart {
96
98
  updatePosition(scenarios) {
97
99
  this.position = this.createElementPosition(scenarios);
98
100
  }
99
- initSQLFunctions() {
100
- alasql.fn.transformOperator = function (a) {
101
- return a === "-" ? -1 : 1;
102
- };
103
- // @ts-ignore
104
- alasql.fn.normalizeDate = function (date, normalizationLevel, _locale) {
105
- if (date === undefined || !date.isValid) {
106
- return undefined;
107
- }
108
- return date.startOf(normalizationLevel);
109
- };
110
- }
111
101
  setStyles(newStyle) {
112
102
  this.styles = newStyle;
113
103
  }
@@ -174,7 +164,7 @@ export class TimeChart {
174
164
  var _a;
175
165
  this.state = FactoryState.DIRTY;
176
166
  this.sortScenariosbyVisualisationRules(config);
177
- this.setData([...config.data], config.filter);
167
+ this.setSource(config.filter);
178
168
  this.hideAxisLabels = config.hideAxisLabels || false;
179
169
  this.pixelPerUnit = config.pixelPerUnit;
180
170
  this.pixelPerPercentage = config.pixelPerPercentage;
@@ -233,31 +223,25 @@ export class TimeChart {
233
223
  this.i18n = this.createI18n(i18n);
234
224
  }
235
225
  /**
236
- * Init load raw datasets the loaded dataset is
237
- * the base on which the filters defined in the config
238
- * are apllied on internaly it is called prepared DataSet
239
- *
240
- * @param data
241
- * @param filter - data filter
242
- * @param customColumnNameMap Custon ColumnNameMap can be used if data uses non standard columnames
226
+ * Resolves the dataset (a table or view in the shared alasql database) and
227
+ * caches its row count. Subsequent queries reference the source by name —
228
+ * alasql doesn't have to ingest a fresh array per call.
243
229
  */
244
- setData(data, filter) {
245
- if (data == null) {
230
+ setSource(filter) {
231
+ var _a, _b;
232
+ this.state = FactoryState.DIRTY;
233
+ if (!this.tableName) {
234
+ this.fromExpr = "";
235
+ this.rowCount = 0;
246
236
  return;
247
237
  }
248
- this.state = FactoryState.DIRTY; // mark dataSet for update
249
- this.preparedDataSet.length = 0; // cleans formerly loaded and prepared dataset
250
- if (filter != null && filter.length > 0) {
251
- try {
252
- this.preparedDataSet = alasql(`SELECT * FROM ? WHERE ${filter}`, [data]);
253
- }
254
- catch (e) {
255
- console.error("TimeChart: filter query failed, using unfiltered data", filter, e);
256
- this.preparedDataSet = data;
257
- }
238
+ this.fromExpr = buildFromExpr(this.tableName, filter);
239
+ try {
240
+ const r = this.db.exec(`SELECT COUNT(*) AS cnt FROM ${this.fromExpr}`);
241
+ this.rowCount = ((_b = (_a = r[0]) === null || _a === void 0 ? void 0 : _a.cnt) !== null && _b !== void 0 ? _b : 0);
258
242
  }
259
- else {
260
- this.preparedDataSet = data;
243
+ catch (_e) {
244
+ this.rowCount = 0;
261
245
  }
262
246
  }
263
247
  getAllocatedCanvasWidth() {
@@ -516,8 +500,7 @@ export class TimeChart {
516
500
  return result;
517
501
  }
518
502
  populateModel(selectedScenarios, dateInterval, _level, _sortOrder) {
519
- var _a;
520
- if (((_a = this.preparedDataSet) === null || _a === void 0 ? void 0 : _a.length) === 0) {
503
+ if (this.rowCount === 0 || !this.fromExpr) {
521
504
  return [];
522
505
  }
523
506
  const select = ``;
@@ -559,17 +542,41 @@ export class TimeChart {
559
542
  return localDateInterval;
560
543
  }
561
544
  queryMinMaxDates() {
562
- var _a, _b, _c, _d;
563
- //let result: any[] = [];
564
- const result = alasql(`SELECT MAX(${"date"}) as maxdate, MIN(${"date"}) as mindate FROM ?`, [this.preparedDataSet]);
545
+ var _a, _b;
546
+ let result;
547
+ try {
548
+ result = this.db.exec(`SELECT MAX(${"date"}) as maxdate, MIN(${"date"}) as mindate FROM ${this.fromExpr}`);
549
+ }
550
+ catch (e) {
551
+ console.error("TimeChart: min/max date query failed", e);
552
+ return [{}];
553
+ }
554
+ // `date` rows in the shared db are typically ISO strings (raw JSON) or millis;
555
+ // accept both so existing fixtures and live JSON data both work.
565
556
  if (((_a = result[0]) === null || _a === void 0 ? void 0 : _a.mindate) != null) {
566
- result[0].mindate = DateTime.fromMillis((_b = result[0]) === null || _b === void 0 ? void 0 : _b.mindate);
557
+ result[0].mindate = TimeChart.coerceDateTime(result[0].mindate);
567
558
  }
568
- if (((_c = result[0]) === null || _c === void 0 ? void 0 : _c.maxdate) != null) {
569
- result[0].maxdate = DateTime.fromMillis((_d = result[0]) === null || _d === void 0 ? void 0 : _d.maxdate);
559
+ if (((_b = result[0]) === null || _b === void 0 ? void 0 : _b.maxdate) != null) {
560
+ result[0].maxdate = TimeChart.coerceDateTime(result[0].maxdate);
570
561
  }
571
562
  return result;
572
563
  }
564
+ static coerceDateTime(v) {
565
+ if (v == null)
566
+ return undefined;
567
+ if (typeof v === "string") {
568
+ const dt = DateTime.fromISO(v);
569
+ return dt.isValid ? dt : undefined;
570
+ }
571
+ if (typeof v === "number") {
572
+ const dt = DateTime.fromMillis(v);
573
+ return dt.isValid ? dt : undefined;
574
+ }
575
+ if (typeof v.isValid === "boolean") {
576
+ return v;
577
+ }
578
+ return undefined;
579
+ }
573
580
  queryDataSet(dateInterval, select, order) {
574
581
  const scenarios = [
575
582
  "ac1",
@@ -590,13 +597,15 @@ export class TimeChart {
590
597
  "pl4",
591
598
  ];
592
599
  const dateSelect = `normalizeDate([date], '${dateInterval}' , '${this.locale}') as calcdate`;
593
- const result = alasql(`SELECT ${"p.calcdate"} ${select},
600
+ let result;
601
+ try {
602
+ result = this.db.exec(`SELECT ${"p.calcdate"} ${select},
594
603
  ${scenarios
595
- .map((scenario) => {
596
- return `SUM(${scenario} * transformOperator(operation)) as ${scenario}, COUNT(ISNULL(${scenario})) as ${scenario}_cnt`;
597
- })
598
- .join(",")}
599
-
604
+ .map((scenario) => {
605
+ return `SUM(${scenario} * transformOperator(operation)) as ${scenario}, COUNT(ISNULL(${scenario})) as ${scenario}_cnt`;
606
+ })
607
+ .join(",")}
608
+
600
609
  FROM (SELECT ${dateSelect} ${select},
601
610
  ac1,
602
611
  ac2,
@@ -614,9 +623,14 @@ export class TimeChart {
614
623
  pl2,
615
624
  pl3,
616
625
  pl4
617
- FROM ?) as p
626
+ FROM ${this.fromExpr}) as p
618
627
  GROUP BY ${"calcdate"} ${order}
619
- ORDER BY ${"calcdate asc"}`, [this.preparedDataSet]);
628
+ ORDER BY ${"calcdate asc"}`);
629
+ }
630
+ catch (e) {
631
+ console.error("TimeChart: queryDataSet failed", e);
632
+ return [];
633
+ }
620
634
  return result;
621
635
  }
622
636
  createDataRows(result, selectedScenarios) {
@@ -1281,12 +1295,14 @@ export class TimeChart {
1281
1295
  }
1282
1296
  }
1283
1297
  leftOuterJoinDates(result, dateInterval) {
1284
- const to = DateTime.max(...result.map(function (e) {
1285
- return e.calcdate;
1286
- }));
1287
- const from = DateTime.min(...result.map(function (e) {
1288
- return e.calcdate;
1289
- }));
1298
+ const validDates = result
1299
+ .map((e) => e.calcdate)
1300
+ .filter((d) => d != null && typeof d.isValid === "boolean" && d.isValid);
1301
+ if (validDates.length === 0) {
1302
+ return result;
1303
+ }
1304
+ const to = DateTime.max(...validDates);
1305
+ const from = DateTime.min(...validDates);
1290
1306
  const dateRange = new DateStringFactory().datesBetween(from, to, dateInterval, this.intervalSpanLimit);
1291
1307
  const dateRangeEntries = new Map();
1292
1308
  dateRange.forEach((element, idx) => {
@@ -59,15 +59,16 @@ export class TimeChartComponentConfig {
59
59
  /**
60
60
  * Converts untyped JSON into a validated {@link TimeChartComponentConfig}.
61
61
  *
62
- * Requires the raw dataset for measure scale auto-calculation.
62
+ * Reads from the shared alasql database for measure-scale auto-calculation.
63
63
  */
64
64
  export class TimeChartComponentConfigAdapter {
65
- constructor(dataRowAdapter, orderAdapter, stringAdapter, dataFormatDigitsAdapter, dataSet) {
65
+ constructor(dataRowAdapter, orderAdapter, stringAdapter, dataFormatDigitsAdapter, db, fromExpr) {
66
66
  this.dataRowAdapter = dataRowAdapter;
67
67
  this.orderAdapter = orderAdapter;
68
68
  this.stringAdapter = stringAdapter;
69
69
  this.dataFormatDigitsAdapter = dataFormatDigitsAdapter;
70
- this.dataSet = dataSet;
70
+ this.db = db;
71
+ this.fromExpr = fromExpr;
71
72
  }
72
73
  adapt(data) {
73
74
  const dataSet = AdapterUtils.adaptArray(data.data, this.dataRowAdapter);
@@ -113,7 +114,7 @@ export class TimeChartComponentConfigAdapter {
113
114
  config.filter = data.filter;
114
115
  }
115
116
  if (CompareUtil.isExisting(data.measureScale)) {
116
- config.measureScale = DataAnalyzer.calculateMeasureScale(this.dataSet, config.scenarios, data.measureScale);
117
+ config.measureScale = DataAnalyzer.calculateMeasureScale(this.db, this.fromExpr, config.scenarios, data.measureScale);
117
118
  }
118
119
  if (CompareUtil.isString(data.measureUnit)) {
119
120
  config.measureUnit = data.measureUnit;
@@ -77,6 +77,8 @@ export class TimeChartDataRowAdapter {
77
77
  return dataRow;
78
78
  }
79
79
  parseDateString(date) {
80
+ if (typeof date !== "string")
81
+ return undefined;
80
82
  const timestamp = DateTime.fromISO(date);
81
83
  if (timestamp.isValid) {
82
84
  return timestamp;
@@ -3,7 +3,6 @@ import withDatasource from "../../utils/withDatasource";
3
3
  import withBodyObserver from "../../utils/withBodyObserver";
4
4
  import { getStores } from "../../context/context-protocol";
5
5
  import { calculateDatasetMeta } from "../../utils/datasetMetaCalculator";
6
- import alasql from "alasql";
7
6
  import withComponentStatus from "../../utils/withComponentStatus";
8
7
  import withHasError from "../../utils/withHasError";
9
8
  import { computeContentHash, decodeCompressedContent } from "../../utils/contentDecoder";
@@ -11,10 +10,13 @@ import { computeContentHash, decodeCompressedContent } from "../../utils/content
11
10
  * Queries data from one or more `bn-datasource` entries via AlaSQL and
12
11
  * writes the result to the `datasets` store (+ computed `DatasetMeta`).
13
12
  *
14
- * The SQL query is provided as text inside the element body (observed via
15
- * `withBodyObserver`). When any referenced datasource changes, the query
16
- * is re-executed automatically. Set `static="true"` to bypass the SQL
17
- * engine and treat the body content as raw JSON data directly.
13
+ * The body content is observed via `withBodyObserver` and may be:
14
+ * 1. **SQL** (default) — AlaSQL query against referenced `datasources`.
15
+ * 2. **Static JSON** — set `static="true"` to bypass SQL and write the
16
+ * parsed body directly to the `datasets` store.
17
+ * 3. **URL** — place an `http://` or `https://` URL in the body to fetch
18
+ * JSON from a remote endpoint and write it to the `datasets` store.
19
+ * Set the `interval` prop (in seconds) to enable periodic re-fetching.
18
20
  */
19
21
  export class Dataset {
20
22
  constructor() {
@@ -36,16 +38,45 @@ export class Dataset {
36
38
  * When false, body content is a compressed payload (`<hash>:<base64_gzip>`).
37
39
  */
38
40
  this.raw = true;
41
+ /**
42
+ * Polling interval in **seconds** for URL mode.
43
+ * When set and the body content is a URL, the component re-fetches
44
+ * data at this interval. Has no effect for SQL, inline JSON or
45
+ * compressed content. Set to `0` or leave unset to disable polling.
46
+ */
47
+ this.interval = 0;
39
48
  this.lastBodyHash = null;
49
+ /** The query text last used to (re)create the SQL view, so we only `CREATE VIEW` when it actually changes. */
50
+ this.lastViewQuery = null;
51
+ /** The currently active URL (`null` when not in URL mode). */
52
+ this.currentUrl = null;
53
+ /** Timer ID for the polling interval. */
54
+ this.pollTimerId = null;
55
+ /** AbortController for cancelling in-flight fetch requests. */
56
+ this.abortController = null;
40
57
  withComponentStatus(this);
41
58
  this.errors = withHasError(this);
42
- // @ts-ignore
43
- this.database = new alasql.Database();
44
- withDatasource(this, (name, data) => {
45
- this.database.tables[name] = { data };
59
+ // Datasources already live in the shared db; just re-execute when any upstream notifies.
60
+ withDatasource(this, () => {
46
61
  this.executeQuery();
47
62
  });
48
63
  withBodyObserver(this, (data) => {
64
+ const trimmed = data.trim();
65
+ // --- URL mode ---
66
+ if (this.isUrl(trimmed)) {
67
+ if (trimmed === this.currentUrl)
68
+ return;
69
+ this.currentUrl = trimmed;
70
+ this.lastBodyHash = null;
71
+ this.fetchAndStore(trimmed);
72
+ this.startPolling();
73
+ return;
74
+ }
75
+ // --- Leaving URL mode → clean up ---
76
+ if (this.currentUrl !== null) {
77
+ this.clearPolling();
78
+ this.currentUrl = null;
79
+ }
49
80
  let contentHash;
50
81
  let body;
51
82
  if (!this.raw && this.static) {
@@ -73,34 +104,171 @@ export class Dataset {
73
104
  executeQuery() {
74
105
  if (!this.stores)
75
106
  this.stores = getStores(this.element);
76
- if (!!this.query && !!this.name) {
77
- let result;
78
- if (this.static) {
107
+ if (!this.query || !this.name)
108
+ return;
109
+ const db = this.stores.db.db;
110
+ let result;
111
+ if (this.static) {
112
+ // Static JSON: parse and register as a table in the shared db.
113
+ try {
114
+ result = JSON.parse(this.query);
115
+ }
116
+ catch (e) {
117
+ console.error("Failed to parse static dataset", e);
118
+ result = [];
119
+ }
120
+ db.tables[this.name] = { data: Array.isArray(result) ? result : [] };
121
+ this.lastViewQuery = null;
122
+ }
123
+ else {
124
+ // SQL: register the dataset as a view in the shared db. Recreate only when the
125
+ // query text changes; otherwise we just re-materialize so upstream data updates
126
+ // flow through.
127
+ if (this.lastViewQuery !== this.query) {
128
+ // alasql tracks names in BOTH `db.tables` and `db.views`, and its
129
+ // CREATE-conflict check looks at `db.tables`. Clean both locations
130
+ // before creating so devtools "Edit as HTML" (which destroys the old
131
+ // element and creates a new one without giving us a clean slate)
132
+ // doesn't trip the "already exists" guard.
133
+ try {
134
+ db.exec(`DROP VIEW \`${this.name}\``);
135
+ }
136
+ catch (_e) {
137
+ /* not registered as a view — fine */
138
+ }
139
+ if (db.tables[this.name] != null) {
140
+ delete db.tables[this.name];
141
+ }
142
+ // @ts-ignore - views typing is loose
143
+ if (db.views && db.views[this.name] != null) {
144
+ // @ts-ignore
145
+ delete db.views[this.name];
146
+ }
79
147
  try {
80
- result = JSON.parse(this.query);
148
+ db.exec(`CREATE VIEW \`${this.name}\` AS ${this.query}`);
149
+ this.lastViewQuery = this.query;
81
150
  }
82
151
  catch (e) {
83
- console.error("Failed to parse static dataset", e);
152
+ console.error("bn-dataset: failed to register SQL view", e, this.query);
153
+ this.lastViewQuery = null;
84
154
  result = [];
155
+ this.publish(result);
156
+ return;
85
157
  }
86
158
  }
87
- else {
88
- result = this.database.exec(this.query);
159
+ try {
160
+ result = db.exec(`SELECT * FROM \`${this.name}\``);
89
161
  }
90
- if (this.latestResult !== result) {
91
- this.latestResult = result;
92
- // @ts-ignore
93
- this.stores.datasets.set(this.name, result);
94
- // @ts-ignore
95
- this.stores.datasetsMeta.set(this.name, calculateDatasetMeta(result));
162
+ catch (_e) {
163
+ // Most common cause: an upstream datasource referenced by the view hasn't
164
+ // been registered yet (HTML parse/connectedCallback race). `withDatasource`
165
+ // re-fires executeQuery on every upstream notify, so we'll retry then.
166
+ // Skip publish so we don't clobber datasetsMeta with empty data.
167
+ return;
96
168
  }
97
169
  }
170
+ this.publish(result);
171
+ }
172
+ /** Notifies db subscribers and updates the derived `datasetsMeta` store. */
173
+ publish(result) {
174
+ if (this.latestResult === result) {
175
+ // Even if the materialized object reference is unchanged, upstream data may have moved
176
+ // (notably for views) — fire notify so consumers re-render against the fresh table state.
177
+ this.stores.db.notify(this.name);
178
+ return;
179
+ }
180
+ this.latestResult = result;
181
+ this.stores.db.notify(this.name);
182
+ // @ts-ignore - DatasetMeta is small derived metadata; kept as a @stencil/store per the plan.
183
+ this.stores.datasetsMeta.set(this.name, calculateDatasetMeta(result));
98
184
  }
99
185
  nameUpdated() {
100
186
  this.executeQuery();
101
187
  }
188
+ onIntervalChange() {
189
+ if (this.currentUrl) {
190
+ this.startPolling();
191
+ }
192
+ }
193
+ disconnectedCallback() {
194
+ var _a, _b;
195
+ this.clearPolling();
196
+ if (((_b = (_a = this.stores) === null || _a === void 0 ? void 0 : _a.db) === null || _b === void 0 ? void 0 : _b.db) && this.name) {
197
+ const db = this.stores.db.db;
198
+ try {
199
+ db.exec(`DROP VIEW \`${this.name}\``);
200
+ }
201
+ catch (_e) {
202
+ // not registered as a view — fine
203
+ }
204
+ if (db.tables[this.name] != null) {
205
+ delete db.tables[this.name];
206
+ }
207
+ // @ts-ignore - views typing is loose
208
+ if (db.views && db.views[this.name] != null) {
209
+ // @ts-ignore
210
+ delete db.views[this.name];
211
+ }
212
+ this.stores.db.notify(this.name);
213
+ }
214
+ }
215
+ /**
216
+ * Returns `true` if the text starts with `http://` or `https://`.
217
+ */
218
+ isUrl(text) {
219
+ return text.startsWith("http://") || text.startsWith("https://");
220
+ }
221
+ /**
222
+ * Fetches JSON from the given URL and stores the result as the dataset.
223
+ * Cancels any in-flight request before starting a new one.
224
+ */
225
+ async fetchAndStore(url) {
226
+ var _a;
227
+ (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
228
+ this.abortController = new AbortController();
229
+ if (!this.stores)
230
+ this.stores = getStores(this.element);
231
+ try {
232
+ const response = await fetch(url, { signal: this.abortController.signal });
233
+ const json = await response.json();
234
+ const db = this.stores.db.db;
235
+ db.tables[this.name] = { data: Array.isArray(json) ? json : [] };
236
+ this.lastViewQuery = null;
237
+ this.publish(json);
238
+ }
239
+ catch (e) {
240
+ if (e instanceof DOMException && e.name === "AbortError")
241
+ return;
242
+ console.error("bn-dataset: error fetching URL", e, url);
243
+ const db = this.stores.db.db;
244
+ db.tables[this.name] = { data: [] };
245
+ this.lastViewQuery = null;
246
+ this.publish([]);
247
+ }
248
+ }
249
+ /** Stops the polling timer and cancels any in-flight fetch. */
250
+ clearPolling() {
251
+ var _a;
252
+ if (this.pollTimerId !== null) {
253
+ clearInterval(this.pollTimerId);
254
+ this.pollTimerId = null;
255
+ }
256
+ (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
257
+ this.abortController = null;
258
+ }
259
+ /** Starts (or restarts) the polling timer if in URL mode with a positive interval. */
260
+ startPolling() {
261
+ this.clearPolling();
262
+ if (this.currentUrl && this.interval > 0) {
263
+ this.pollTimerId = setInterval(() => {
264
+ if (this.currentUrl) {
265
+ this.fetchAndStore(this.currentUrl);
266
+ }
267
+ }, this.interval * 1000);
268
+ }
269
+ }
102
270
  render() {
103
- return h(Host, { key: '3e8b6fbc52b5b5cbe0ae88d7aa1d259f86d63e1b' });
271
+ return h(Host, { key: 'fa02248ff99fc299f0ed7c7feae63063d071685a' });
104
272
  }
105
273
  static get is() { return "bn-dataset"; }
106
274
  static get originalStyleUrls() {
@@ -193,6 +361,26 @@ export class Dataset {
193
361
  "reflect": false,
194
362
  "attribute": "raw",
195
363
  "defaultValue": "true"
364
+ },
365
+ "interval": {
366
+ "type": "number",
367
+ "mutable": false,
368
+ "complexType": {
369
+ "original": "number",
370
+ "resolved": "number",
371
+ "references": {}
372
+ },
373
+ "required": false,
374
+ "optional": false,
375
+ "docs": {
376
+ "tags": [],
377
+ "text": "Polling interval in **seconds** for URL mode.\nWhen set and the body content is a URL, the component re-fetches\ndata at this interval. Has no effect for SQL, inline JSON or\ncompressed content. Set to `0` or leave unset to disable polling."
378
+ },
379
+ "getter": false,
380
+ "setter": false,
381
+ "reflect": false,
382
+ "attribute": "interval",
383
+ "defaultValue": "0"
196
384
  }
197
385
  };
198
386
  }
@@ -201,6 +389,9 @@ export class Dataset {
201
389
  return [{
202
390
  "propName": "name",
203
391
  "methodName": "nameUpdated"
392
+ }, {
393
+ "propName": "interval",
394
+ "methodName": "onIntervalChange"
204
395
  }];
205
396
  }
206
397
  }
@@ -79,23 +79,43 @@ export class Datasource {
79
79
  return;
80
80
  this.lastHash = contentHash;
81
81
  const json = JSON.parse(jsonString);
82
- // @ts-ignore
83
- this.stores.datasources.set(this.name, json);
82
+ this.publish(json);
84
83
  }
85
84
  catch (e) {
86
85
  console.error("Error parsing datasource", e, String(data).slice(0, 200));
87
- // @ts-ignore
88
- this.stores.datasources.set(this.name, []);
86
+ this.publish([]);
89
87
  }
90
88
  });
91
89
  }
90
+ /**
91
+ * Writes the parsed data into the shared alasql database (as a table named
92
+ * after this datasource) and notifies subscribers.
93
+ */
94
+ publish(json) {
95
+ const db = this.stores.db.db;
96
+ db.tables[this.name] = { data: Array.isArray(json) ? json : [] };
97
+ this.stores.db.notify(this.name);
98
+ }
92
99
  onIntervalChange() {
93
100
  if (this.currentUrl) {
94
101
  this.startPolling();
95
102
  }
96
103
  }
97
104
  disconnectedCallback() {
105
+ var _a, _b;
98
106
  this.clearPolling();
107
+ const db = (_b = (_a = this.stores) === null || _a === void 0 ? void 0 : _a.db) === null || _b === void 0 ? void 0 : _b.db;
108
+ if (db && this.name) {
109
+ if (db.tables[this.name] != null) {
110
+ delete db.tables[this.name];
111
+ }
112
+ // @ts-ignore - views typing is loose
113
+ if (db.views && db.views[this.name] != null) {
114
+ // @ts-ignore
115
+ delete db.views[this.name];
116
+ }
117
+ this.stores.db.notify(this.name);
118
+ }
99
119
  }
100
120
  /**
101
121
  * Returns `true` if the text starts with `http://` or `https://`.
@@ -116,15 +136,13 @@ export class Datasource {
116
136
  try {
117
137
  const response = await fetch(url, { signal: this.abortController.signal });
118
138
  const json = await response.json();
119
- // @ts-ignore
120
- this.stores.datasources.set(this.name, json);
139
+ this.publish(json);
121
140
  }
122
141
  catch (e) {
123
142
  if (e instanceof DOMException && e.name === "AbortError")
124
143
  return;
125
144
  console.error("bn-datasource: error fetching URL", e, url);
126
- // @ts-ignore
127
- this.stores.datasources.set(this.name, []);
145
+ this.publish([]);
128
146
  }
129
147
  }
130
148
  /** Stops the polling timer and cancels any in-flight fetch. */
@@ -149,7 +167,7 @@ export class Datasource {
149
167
  }
150
168
  }
151
169
  render() {
152
- return h(Host, { key: 'ca9f70b8f570c1b3ec94c800cd63baa4a0733d07' });
170
+ return h(Host, { key: '4c79b32d893865fe7c62118d4186b8175294636f' });
153
171
  }
154
172
  static get is() { return "bn-datasource"; }
155
173
  static get originalStyleUrls() {