@dashboard-designer/core 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +143 -5
  2. package/dist/index.js +517 -6
  3. package/package.json +29 -24
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /** Supported database providers (Phase 1 includes SQL Server). */
2
2
  type DbProvider = 'sqlite' | 'postgres' | 'mysql' | 'mssql';
3
- type WidgetType = 'bar' | 'line' | 'pie' | 'table' | 'kpi' | 'listbox';
3
+ type WidgetType = 'bar' | 'line' | 'pie' | 'table' | 'kpi' | 'listbox' | 'label' | 'labelContainer';
4
4
  type FilterOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'nin' | 'like' | 'between' | 'is_null' | 'not_null';
5
5
  type JoinType = 'inner' | 'left' | 'right' | 'full';
6
6
  type AuthMode = 'token' | 'anonymous';
@@ -39,6 +39,8 @@ interface FilterDef {
39
39
  * When omitted, inferred from whether the field is an aggregated measure.
40
40
  */
41
41
  clause?: 'where' | 'having';
42
+ /** Preserve an explicitly resolved empty variable value in SQL filters. */
43
+ allowEmptyValue?: boolean;
42
44
  }
43
45
  interface JoinDef {
44
46
  id: string;
@@ -58,6 +60,8 @@ interface QueryDef {
58
60
  connectionId: string;
59
61
  /** When set, runs this SQL (with optional filter injection via {{filters}}) */
60
62
  rawSql?: string;
63
+ /** Named inputs for a bare SQL Server EXEC call. Omitted keys use procedure defaults. */
64
+ procedureParameters?: Record<string, string | number | boolean | null | ProcedureWhereClause>;
61
65
  tables?: string[];
62
66
  joins?: JoinDef[];
63
67
  columns?: QueryColumn[];
@@ -69,6 +73,21 @@ interface QueryDef {
69
73
  }>;
70
74
  limit?: number;
71
75
  }
76
+ interface ProcedureParameter {
77
+ name: string;
78
+ type: string;
79
+ isOutput: boolean;
80
+ }
81
+ interface ProcedureWhereClause {
82
+ kind: 'where';
83
+ filters: FilterDef[];
84
+ /** Set false for procedures that expect predicates without the WHERE keyword. */
85
+ includeWhere?: boolean;
86
+ }
87
+ /** Build SQL Server clause text for a procedure's string parameter, not the EXEC statement. */
88
+ declare function buildProcedureWhereClause(value: ProcedureWhereClause): string;
89
+ /** Only a single, bare EXEC call is eligible for the parameter editor. */
90
+ declare function parseStoredProcedureName(sql?: string): string | undefined;
72
91
  interface DataBinding {
73
92
  dimensions: string[];
74
93
  measures: string[];
@@ -80,6 +99,44 @@ interface DrillDownDef {
80
99
  passFields: string[];
81
100
  title?: string;
82
101
  }
102
+ /** One label inside a labelContainer widget (no per-label header). */
103
+ interface ContainerLabelItem {
104
+ id: string;
105
+ text: string;
106
+ color?: string;
107
+ backgroundColor?: string;
108
+ fontSize?: number;
109
+ targetDashboardId?: string;
110
+ drillTitle?: string;
111
+ }
112
+ /** Styles and drill target applied to every label generated from a query column. */
113
+ interface ContainerLabelTemplate {
114
+ color?: string;
115
+ backgroundColor?: string;
116
+ fontSize?: number;
117
+ targetDashboardId?: string;
118
+ drillTitle?: string;
119
+ }
120
+ type LabelContainerSource = 'static' | 'query';
121
+ interface QueryLabelDrillDown {
122
+ field: string;
123
+ value: string;
124
+ action: 'none' | 'dashboard';
125
+ targetDashboardId?: string;
126
+ drillTitle?: string;
127
+ }
128
+ declare function normalizeQueryLabelDrillDowns(raw: unknown): QueryLabelDrillDown[];
129
+ type ContainerLabelLayout = 'vertical' | 'horizontal';
130
+ type ChartGuidelineAxis = 'x' | 'y';
131
+ /** Reference line on a bar or line chart axis. */
132
+ interface ChartAxisGuideline {
133
+ id: string;
134
+ axis: ChartGuidelineAxis;
135
+ /** Category label for X, numeric value for Y (stored as string). */
136
+ value: string;
137
+ label?: string;
138
+ color?: string;
139
+ }
83
140
  interface Widget {
84
141
  id: string;
85
142
  type: WidgetType;
@@ -88,12 +145,17 @@ interface Widget {
88
145
  binding: DataBinding;
89
146
  chartOptions: Record<string, unknown>;
90
147
  filters: FilterDef[];
148
+ /** Applied in the React client to returned rows, never sent as SQL conditions. */
149
+ frontendFilters?: FilterDef[];
91
150
  drillDown?: DrillDownDef;
92
151
  }
93
152
  interface Dashboard {
94
153
  id: string;
95
154
  title: string;
96
155
  description?: string;
156
+ variables?: DashboardVariable[];
157
+ /** Report-specific preview defaults for developer-defined variables. */
158
+ variableDefaults?: Record<string, VariableValue>;
97
159
  locale?: string;
98
160
  /** ISO 4217 currency code for number formatting (default USD). */
99
161
  currency?: string;
@@ -104,11 +166,13 @@ interface Dashboard {
104
166
  /** Optional visual theme (accent + chart palette). Omit / reset for defaults. */
105
167
  theme?: DashboardTheme;
106
168
  /**
107
- * Toolbar export actions. When omitted, print and PDF are enabled; email is off.
108
- * Set `print: false` / `pdf: false` to hide each action; set `email: true` to show Send email.
169
+ * Toolbar export actions. When omitted, print, PDF, and JSON export are enabled; email is off.
170
+ * Set `print: false` / `pdf: false` / `json: false` to hide each action; set `email: true` to show Send email.
109
171
  * Use `emailOptions` to control dashboard PDF and extra file attachments.
110
172
  */
111
173
  exportOptions?: DashboardExportOptions;
174
+ /** View-mode display preferences (widget chrome, etc.). */
175
+ displayOptions?: DashboardDisplayOptions;
112
176
  layout: GridItem[];
113
177
  globalFilters: FilterDef[];
114
178
  widgets: Widget[];
@@ -129,13 +193,38 @@ interface DashboardExportOptions {
129
193
  print?: boolean;
130
194
  /** Show Export PDF in the toolbar (default true). */
131
195
  pdf?: boolean;
196
+ /** Show Export JSON in the toolbar (default true). */
197
+ json?: boolean;
132
198
  /** Show Send email in the toolbar (default false; requires SMTP on the API). */
133
199
  email?: boolean;
134
200
  /** Attachment behavior for Send email (ignored when email is off). */
135
201
  emailOptions?: DashboardEmailOptions;
136
202
  }
137
- declare function resolveExportOptions(options?: DashboardExportOptions | null): Required<Pick<DashboardExportOptions, 'print' | 'pdf' | 'email'>>;
203
+ interface DashboardDisplayOptions {
204
+ /** Show chart-type badge on widget headers in view / readonly mode (default false). */
205
+ showWidgetTypeBadge?: boolean;
206
+ }
207
+ declare function resolveDisplayOptions(options?: DashboardDisplayOptions | null): Required<DashboardDisplayOptions>;
208
+ declare function resolveExportOptions(options?: DashboardExportOptions | null): Required<Pick<DashboardExportOptions, 'print' | 'pdf' | 'json' | 'email'>>;
138
209
  declare function resolveEmailOptions(options?: DashboardExportOptions | null): Required<DashboardEmailOptions>;
210
+ /** Marker written into exported dashboard JSON files. */
211
+ declare const DASHBOARD_FILE_FORMAT: "dashboard-designer";
212
+ declare const DASHBOARD_FILE_VERSION = 1;
213
+ interface DashboardFileEnvelope {
214
+ format: typeof DASHBOARD_FILE_FORMAT;
215
+ version: number;
216
+ exportedAt: string;
217
+ dashboard: Dashboard;
218
+ }
219
+ /** Build a portable JSON document for download (keeps current IDs). */
220
+ declare function buildDashboardExportFile(dashboard: Dashboard): DashboardFileEnvelope;
221
+ /**
222
+ * Clone a dashboard for import: new dashboard/widget/layout/filter IDs.
223
+ * Connection IDs and cross-dashboard drill targets are preserved.
224
+ */
225
+ declare function cloneDashboardForImport(source: Dashboard, titleSuffix?: string): Dashboard;
226
+ /** Parse JSON text from an export file (or a bare Dashboard object). */
227
+ declare function parseDashboardImport(raw: unknown): Dashboard;
139
228
  interface DashboardTheme {
140
229
  /** UI accent used for buttons, links, KPI emphasis. */
141
230
  accent?: string;
@@ -198,6 +287,8 @@ interface ConnectionConfig {
198
287
  /** File path for SQLite */
199
288
  filename?: string;
200
289
  ssl?: boolean;
290
+ /** SQL Server Windows authentication (Integrated Security) */
291
+ integratedSecurity?: boolean;
201
292
  /** Allow anonymous embed to use this connection */
202
293
  allowAnonymous?: boolean;
203
294
  }
@@ -214,22 +305,69 @@ interface AuthConfig {
214
305
  token?: string;
215
306
  }
216
307
  interface QueryResult {
308
+ /** Server timestamp of the database fetch, preserved on cache hits. */
309
+ fetchedAt?: string;
217
310
  columns: string[];
218
311
  rows: Record<string, unknown>[];
219
312
  rowCount: number;
220
313
  durationMs: number;
221
314
  }
222
315
  interface ExecuteQueryRequest {
316
+ /** Bypass and replace the cached result for this query. */
317
+ refresh?: boolean;
318
+ dashboardId?: string;
223
319
  query: QueryDef;
224
320
  chartFilters?: FilterDef[];
225
321
  globalFilters?: FilterDef[];
322
+ variables?: Record<string, VariableValue>;
323
+ }
324
+ type VariableValue = string | number | boolean | null;
325
+ interface DashboardVariable {
326
+ name: string;
327
+ type: 'string' | 'number' | 'boolean';
328
+ description?: string;
329
+ defaultValue?: VariableValue;
226
330
  }
331
+ declare function resolveVariableValue(value: unknown, variables?: Record<string, VariableValue>): unknown;
332
+ declare function resolveFilterVariables(filters?: FilterDef[], variables?: Record<string, VariableValue>): FilterDef[];
333
+ /** Preserve ordinary parameter values; quote tokens embedded in SQL WHERE text. */
334
+ declare function resolveProcedureParameterValue(name: string, value: VariableValue, variables: Record<string, VariableValue>): VariableValue;
335
+ declare function resolveRequestVariables(body: ExecuteQueryRequest): ExecuteQueryRequest;
336
+ declare function resolveDashboardVariables(dashboard: Pick<Dashboard, 'variables' | 'variableDefaults'>, predefined?: DashboardVariable[], runtime?: Record<string, VariableValue>): Record<string, VariableValue>;
227
337
  declare const WIDGET_TYPES: WidgetType[];
228
338
  declare const DB_PROVIDERS: DbProvider[];
229
339
  /** Locales that default to RTL when dashboard.dir is unset. */
230
340
  declare const RTL_LOCALES: Set<string>;
231
341
  declare function resolveDashboardDir(dashboard: Pick<Dashboard, 'dir' | 'locale'>): 'ltr' | 'rtl';
342
+ /** Legacy hardcoded label foreground from early defaults; treat as theme default. */
343
+ declare const LEGACY_LABEL_FOREGROUND = "#1a2b2b";
344
+ declare function sanitizeLabelStyleColor(color: string | undefined): string | undefined;
345
+ declare function sanitizeLabelStyleBackground(bg: string | undefined): string | undefined;
346
+ declare function normalizeContainerLabels(raw: unknown): ContainerLabelItem[];
347
+ declare function createContainerLabelItem(text?: string): ContainerLabelItem;
348
+ declare function hasContainerLabelCustomStyles(item: ContainerLabelItem): boolean;
349
+ /** Remove per-label color, background, and font size so theme defaults apply. */
350
+ declare function resetContainerLabelItemStyles(item: ContainerLabelItem): ContainerLabelItem;
351
+ declare function normalizeContainerLabelTemplate(raw: unknown): ContainerLabelTemplate;
352
+ declare function hasContainerLabelTemplateCustomStyles(template: ContainerLabelTemplate): boolean;
353
+ declare function resetContainerLabelTemplateStyles(template: ContainerLabelTemplate): ContainerLabelTemplate;
354
+ declare function resolveLabelContainerSource(chartOptions: Record<string, unknown>): LabelContainerSource;
355
+ /** Build label items from distinct values in a query result column, applying a shared template. */
356
+ declare function buildContainerLabelsFromQuery(rows: Record<string, unknown>[], columns: string[], dimensionField: string | undefined, template: ContainerLabelTemplate, drillDowns?: QueryLabelDrillDown[]): ContainerLabelItem[];
357
+ /** Whether label / labelContainer widgets show the widget title bar on the canvas (default true). */
358
+ declare function labelWidgetShowsHeader(chartOptions: Record<string, unknown>): boolean;
359
+ type LabelClickAction = 'none' | 'dashboard' | 'url';
360
+ /** Resolved click behavior for a label widget (dashboard drill-down or external URL). */
361
+ declare function resolveLabelClickAction(chartOptions: Record<string, unknown>, drillDown?: DrillDownDef): LabelClickAction;
362
+ declare function getLabelClickUrl(chartOptions: Record<string, unknown>): string | undefined;
363
+ /** Whether a label URL click opens a new browser tab (default true). */
364
+ declare function labelClickOpensNewTab(chartOptions: Record<string, unknown>): boolean;
365
+ /** Parsed KPI default when query returns no rows or an empty value. */
366
+ declare function getKpiDefaultValue(chartOptions: Record<string, unknown>): unknown | undefined;
367
+ declare function createChartAxisGuideline(axis?: ChartGuidelineAxis, value?: string): ChartAxisGuideline;
368
+ declare function normalizeChartAxisGuidelines(raw: unknown): ChartAxisGuideline[];
232
369
  declare function createEmptyDashboard(partial?: Partial<Dashboard>): Dashboard;
233
370
  declare function createEmptyWidget(type?: WidgetType): Widget;
371
+ declare function createId(): string;
234
372
 
235
- export { type AuthConfig, type AuthMode, type ConnectionConfig, DB_PROVIDERS, DEFAULT_CHART_COLORS, DEFAULT_THEME_ACCENT, type Dashboard, type DashboardAclEntry, type DashboardEmailOptions, type DashboardExportOptions, type DashboardPermission, type DashboardTheme, type DashboardVersion, type DashboardVersionMeta, type DataBinding, type DbProvider, type DrillDownDef, type EmbedTokenRequest, type EmbedTokenResponse, type ExecuteQueryRequest, type FilterDef, type FilterOperator, type GridItem, type JoinDef, type JoinType, type QueryColumn, type QueryDef, type QueryResult, RTL_LOCALES, THEME_PRESETS, type User, type UserRole, WIDGET_TYPES, type Widget, type WidgetType, createEmptyDashboard, createEmptyWidget, isDefaultDashboardTheme, matchThemePreset, resolveDashboardDir, resolveDashboardTheme, resolveEmailOptions, resolveExportOptions };
373
+ export { type AuthConfig, type AuthMode, type ChartAxisGuideline, type ChartGuidelineAxis, type ConnectionConfig, type ContainerLabelItem, type ContainerLabelLayout, type ContainerLabelTemplate, DASHBOARD_FILE_FORMAT, DASHBOARD_FILE_VERSION, DB_PROVIDERS, DEFAULT_CHART_COLORS, DEFAULT_THEME_ACCENT, type Dashboard, type DashboardAclEntry, type DashboardDisplayOptions, type DashboardEmailOptions, type DashboardExportOptions, type DashboardFileEnvelope, type DashboardPermission, type DashboardTheme, type DashboardVariable, type DashboardVersion, type DashboardVersionMeta, type DataBinding, type DbProvider, type DrillDownDef, type EmbedTokenRequest, type EmbedTokenResponse, type ExecuteQueryRequest, type FilterDef, type FilterOperator, type GridItem, type JoinDef, type JoinType, LEGACY_LABEL_FOREGROUND, type LabelClickAction, type LabelContainerSource, type ProcedureParameter, type ProcedureWhereClause, type QueryColumn, type QueryDef, type QueryLabelDrillDown, type QueryResult, RTL_LOCALES, THEME_PRESETS, type User, type UserRole, type VariableValue, WIDGET_TYPES, type Widget, type WidgetType, buildContainerLabelsFromQuery, buildDashboardExportFile, buildProcedureWhereClause, cloneDashboardForImport, createChartAxisGuideline, createContainerLabelItem, createEmptyDashboard, createEmptyWidget, createId, getKpiDefaultValue, getLabelClickUrl, hasContainerLabelCustomStyles, hasContainerLabelTemplateCustomStyles, isDefaultDashboardTheme, labelClickOpensNewTab, labelWidgetShowsHeader, matchThemePreset, normalizeChartAxisGuidelines, normalizeContainerLabelTemplate, normalizeContainerLabels, normalizeQueryLabelDrillDowns, parseDashboardImport, parseStoredProcedureName, resetContainerLabelItemStyles, resetContainerLabelTemplateStyles, resolveDashboardDir, resolveDashboardTheme, resolveDashboardVariables, resolveDisplayOptions, resolveEmailOptions, resolveExportOptions, resolveFilterVariables, resolveLabelClickAction, resolveLabelContainerSource, resolveProcedureParameterValue, resolveRequestVariables, resolveVariableValue, sanitizeLabelStyleBackground, sanitizeLabelStyleColor };
package/dist/index.js CHANGED
@@ -1,8 +1,67 @@
1
1
  // src/index.ts
2
+ function buildProcedureWhereClause(value) {
3
+ if (value.kind !== "where" || !Array.isArray(value.filters) || !value.filters.length) {
4
+ throw new Error("Add at least one condition to the WHERE clause.");
5
+ }
6
+ const literal = (input) => {
7
+ if (typeof input === "string") return `N'${input.replace(/'/g, "''")}'`;
8
+ if (typeof input === "number" && Number.isFinite(input)) return String(input);
9
+ if (typeof input === "boolean") return input ? "1" : "0";
10
+ throw new Error("Enter a value for each WHERE condition.");
11
+ };
12
+ const operators = { eq: "=", neq: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=", like: "LIKE" };
13
+ const conditions = value.filters.map((filter) => {
14
+ if (!filter || typeof filter.field !== "string" || !filter.field.trim()) {
15
+ throw new Error("Select a field for each WHERE condition.");
16
+ }
17
+ const parts = filter.field.split(".");
18
+ if (parts.some((part) => !part.trim())) throw new Error("Invalid WHERE field.");
19
+ const field = parts.map((part) => `[${part.replace(/]/g, "]]")}]`).join(".");
20
+ if (filter.operator === "is_null") return `${field} IS NULL`;
21
+ if (filter.operator === "not_null") return `${field} IS NOT NULL`;
22
+ if (filter.operator === "in" || filter.operator === "nin") {
23
+ const values = Array.isArray(filter.value) ? filter.value : typeof filter.value === "string" ? filter.value.split(",").map((item) => item.trim()) : [];
24
+ if (!values.length || values.some((item) => item === "")) throw new Error("Enter values for the IN condition.");
25
+ return `${field} ${filter.operator === "nin" ? "NOT IN" : "IN"} (${values.map(literal).join(", ")})`;
26
+ }
27
+ if (filter.operator === "between") {
28
+ if (filter.value === "" || filter.valueTo === "") throw new Error("Enter both values for BETWEEN.");
29
+ return `${field} BETWEEN ${literal(filter.value)} AND ${literal(filter.valueTo)}`;
30
+ }
31
+ if (!Object.prototype.hasOwnProperty.call(operators, filter.operator)) throw new Error("Invalid WHERE operator.");
32
+ return `${field} ${operators[filter.operator]} ${literal(filter.value)}`;
33
+ });
34
+ return `${value.includeWhere === false ? "" : "WHERE "}${conditions.map((condition) => `(${condition})`).join(" AND ")}`;
35
+ }
36
+ function parseStoredProcedureName(sql) {
37
+ const identifier = "(?:\\[[^\\]\\r\\n]+\\]|[A-Za-z_][A-Za-z0-9_$#]*)";
38
+ return sql?.match(new RegExp(`^\\s*EXEC(?:UTE)?\\s+(${identifier}(?:\\s*\\.\\s*${identifier})?)\\s*;?\\s*$`, "i"))?.[1];
39
+ }
40
+ function normalizeQueryLabelDrillDowns(raw) {
41
+ if (!Array.isArray(raw)) return [];
42
+ return raw.flatMap((item) => {
43
+ if (!item || typeof item !== "object") return [];
44
+ const rule = item;
45
+ if (typeof rule.field !== "string" || typeof rule.value !== "string" || rule.action !== "none" && rule.action !== "dashboard") return [];
46
+ return [{
47
+ field: rule.field,
48
+ value: rule.value,
49
+ action: rule.action,
50
+ targetDashboardId: typeof rule.targetDashboardId === "string" ? rule.targetDashboardId : void 0,
51
+ drillTitle: typeof rule.drillTitle === "string" ? rule.drillTitle : void 0
52
+ }];
53
+ });
54
+ }
55
+ function resolveDisplayOptions(options) {
56
+ return {
57
+ showWidgetTypeBadge: options?.showWidgetTypeBadge === true
58
+ };
59
+ }
2
60
  function resolveExportOptions(options) {
3
61
  return {
4
62
  print: options?.print !== false,
5
63
  pdf: options?.pdf !== false,
64
+ json: options?.json !== false,
6
65
  email: options?.email === true
7
66
  };
8
67
  }
@@ -16,6 +75,97 @@ function resolveEmailOptions(options) {
16
75
  maxExtraAttachments
17
76
  };
18
77
  }
78
+ var DASHBOARD_FILE_FORMAT = "dashboard-designer";
79
+ var DASHBOARD_FILE_VERSION = 1;
80
+ function buildDashboardExportFile(dashboard) {
81
+ return {
82
+ format: DASHBOARD_FILE_FORMAT,
83
+ version: DASHBOARD_FILE_VERSION,
84
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
85
+ dashboard: structuredClone(dashboard)
86
+ };
87
+ }
88
+ function remapFilterIds(filters, idMap) {
89
+ return filters.map((f) => {
90
+ const nextId = idMap.get(f.id) || createId();
91
+ idMap.set(f.id, nextId);
92
+ const bind = f.bindToGlobalId && idMap.has(f.bindToGlobalId) ? idMap.get(f.bindToGlobalId) : f.bindToGlobalId;
93
+ return { ...f, id: nextId, bindToGlobalId: bind };
94
+ });
95
+ }
96
+ function cloneDashboardForImport(source, titleSuffix = " (imported)") {
97
+ const idMap = /* @__PURE__ */ new Map();
98
+ const widgetIdMap = /* @__PURE__ */ new Map();
99
+ for (const w of source.widgets ?? []) {
100
+ widgetIdMap.set(w.id, createId());
101
+ }
102
+ const globalFilters = remapFilterIds(
103
+ (source.globalFilters ?? []).map((f) => ({ ...f })),
104
+ idMap
105
+ );
106
+ const widgets = (source.widgets ?? []).map((w) => {
107
+ const nextId = widgetIdMap.get(w.id) || createId();
108
+ const chartOptions = structuredClone(w.chartOptions ?? {});
109
+ const labels = normalizeContainerLabels(chartOptions.labels);
110
+ if (labels.length) {
111
+ chartOptions.labels = labels.map((item) => ({
112
+ ...item,
113
+ id: createId()
114
+ }));
115
+ }
116
+ const guidelines = normalizeChartAxisGuidelines(chartOptions.axisGuidelines);
117
+ if (guidelines.length) {
118
+ chartOptions.axisGuidelines = guidelines.map((g) => ({
119
+ ...g,
120
+ id: createId()
121
+ }));
122
+ }
123
+ const joins = (w.query.joins ?? []).map((j) => ({ ...j, id: createId() }));
124
+ return {
125
+ ...w,
126
+ id: nextId,
127
+ filters: remapFilterIds((w.filters ?? []).map((f) => ({ ...f })), idMap),
128
+ frontendFilters: w.frontendFilters?.map((f) => ({ ...f, id: createId() })),
129
+ chartOptions,
130
+ query: {
131
+ ...w.query,
132
+ joins
133
+ }
134
+ };
135
+ });
136
+ const layout = (source.layout ?? []).map((item) => ({
137
+ ...item,
138
+ i: widgetIdMap.get(item.i) || createId()
139
+ }));
140
+ const now = (/* @__PURE__ */ new Date()).toISOString();
141
+ return {
142
+ ...source,
143
+ id: createId(),
144
+ title: `${source.title || "Dashboard"}${titleSuffix}`,
145
+ widgets,
146
+ layout,
147
+ globalFilters,
148
+ ownerId: void 0,
149
+ createdAt: now,
150
+ updatedAt: now
151
+ };
152
+ }
153
+ function parseDashboardImport(raw) {
154
+ if (!raw || typeof raw !== "object") {
155
+ throw new Error("Invalid dashboard file");
156
+ }
157
+ const obj = raw;
158
+ let dashboardRaw = obj;
159
+ if (obj.format === DASHBOARD_FILE_FORMAT && obj.dashboard && typeof obj.dashboard === "object") {
160
+ dashboardRaw = obj.dashboard;
161
+ }
162
+ const d = dashboardRaw;
163
+ if (!d || typeof d !== "object") throw new Error("Invalid dashboard file");
164
+ if (!Array.isArray(d.widgets) || !Array.isArray(d.layout)) {
165
+ throw new Error("Dashboard file must include widgets and layout arrays");
166
+ }
167
+ return cloneDashboardForImport(d);
168
+ }
19
169
  var DEFAULT_THEME_ACCENT = "#0d6b54";
20
170
  var DEFAULT_CHART_COLORS = [
21
171
  "#0f6e56",
@@ -77,7 +227,98 @@ function matchThemePreset(theme) {
77
227
  }
78
228
  return "custom";
79
229
  }
80
- var WIDGET_TYPES = ["bar", "line", "pie", "table", "kpi", "listbox"];
230
+ function resolveVariableValue(value, variables = {}) {
231
+ if (Array.isArray(value)) return value.map((item) => resolveVariableValue(item, variables));
232
+ if (typeof value !== "string") return value;
233
+ const read = (name) => {
234
+ if (!Object.prototype.hasOwnProperty.call(variables, name) || variables[name] === void 0)
235
+ throw new Error(`Variable "${name}" has no value. Set a default or supply it from code.`);
236
+ const resolved = variables[name];
237
+ if (resolved !== null && !["string", "number", "boolean"].includes(typeof resolved)) throw new Error(`Invalid variable value: ${name}`);
238
+ return resolved;
239
+ };
240
+ const exact = value.match(/^\{\{var:([A-Za-z_][A-Za-z0-9_]*)\}\}$/);
241
+ if (exact) return read(exact[1]);
242
+ return value.replace(/\{\{var:([A-Za-z_][A-Za-z0-9_]*)\}\}/g, (_, name) => String(read(name) ?? ""));
243
+ }
244
+ function resolveFilterVariables(filters = [], variables = {}) {
245
+ return filters.map((filter) => {
246
+ if (filter.operator === "is_null" || filter.operator === "not_null") return filter;
247
+ const dynamic = typeof filter.value === "string" && filter.value.includes("{{var:");
248
+ const value = resolveVariableValue(filter.value, variables);
249
+ const valueTo = filter.operator === "between" ? resolveVariableValue(filter.valueTo, variables) : filter.valueTo;
250
+ if (dynamic && value === null) {
251
+ if (filter.operator === "eq" || filter.operator === "neq") return { ...filter, operator: filter.operator === "eq" ? "is_null" : "not_null" };
252
+ throw new Error("NULL variables require an equality or null-check filter.");
253
+ }
254
+ return { ...filter, value, valueTo, ...dynamic ? { allowEmptyValue: true } : {} };
255
+ });
256
+ }
257
+ function resolveProcedureParameterValue(name, value, variables) {
258
+ if (typeof value !== "string" || /^\{\{var:[A-Za-z_][A-Za-z0-9_]*\}\}$/.test(value) || !/^\s*WHERE\b/i.test(value) && !/^@where(?:clause|condition|filter)?$/i.test(name)) {
259
+ return resolveVariableValue(value, variables);
260
+ }
261
+ const literal = (resolved) => resolved === null ? "NULL" : typeof resolved === "string" ? `N'${resolved.replace(/'/g, "''")}'` : typeof resolved === "boolean" ? resolved ? "1" : "0" : String(resolved);
262
+ return value.replace(/--[^\r\n]*|\/\*[\s\S]*?\*\/|N?'(?:''|[^'])*'|\[(?:\]\]|[^\]])*\]|\{\{var:[A-Za-z_][A-Za-z0-9_]*\}\}/g, (token) => {
263
+ if (token.startsWith("--") || token.startsWith("/*")) return token;
264
+ if (token.startsWith("{{var:")) return literal(resolveVariableValue(token, variables));
265
+ if (token.startsWith("[")) {
266
+ if (token.includes("{{var:")) throw new Error("Variables cannot replace SQL field names.");
267
+ return token;
268
+ }
269
+ return token.replace(/\{\{var:[A-Za-z_][A-Za-z0-9_]*\}\}/g, (reference) => String(resolveVariableValue(reference, variables) ?? "").replace(/'/g, "''"));
270
+ });
271
+ }
272
+ function resolveRequestVariables(body) {
273
+ const values = body.variables ?? {};
274
+ return {
275
+ ...body,
276
+ chartFilters: resolveFilterVariables(body.chartFilters?.map((filter) => {
277
+ const global = filter.bindToGlobalId && body.globalFilters?.find((g) => g.id === filter.bindToGlobalId);
278
+ return global ? { ...filter, value: global.value, valueTo: global.valueTo, operator: global.operator } : filter;
279
+ }), values),
280
+ globalFilters: resolveFilterVariables(body.globalFilters, values),
281
+ query: {
282
+ ...body.query,
283
+ where: resolveFilterVariables(body.query.where, values),
284
+ procedureParameters: body.query.procedureParameters && Object.fromEntries(
285
+ Object.entries(body.query.procedureParameters).map(([name, value]) => [
286
+ name,
287
+ value && typeof value === "object" && value.kind === "where" ? { ...value, filters: resolveFilterVariables(value.filters, values) } : resolveProcedureParameterValue(name, value, values)
288
+ ])
289
+ )
290
+ }
291
+ };
292
+ }
293
+ function resolveDashboardVariables(dashboard, predefined = [], runtime = {}) {
294
+ const result = {};
295
+ const definitions = [...(dashboard.variables ?? []).filter((v) => !predefined.some((p) => p.name === v.name)), ...predefined];
296
+ const seen = /* @__PURE__ */ new Set();
297
+ for (const variable of definitions) {
298
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(variable.name)) throw new Error(`Invalid variable name: ${variable.name}`);
299
+ if (seen.has(variable.name)) throw new Error(`Duplicate variable name: ${variable.name}`);
300
+ seen.add(variable.name);
301
+ let value = variable.defaultValue;
302
+ if (predefined.some((p) => p.name === variable.name) && Object.prototype.hasOwnProperty.call(dashboard.variableDefaults ?? {}, variable.name))
303
+ value = dashboard.variableDefaults[variable.name];
304
+ if (Object.prototype.hasOwnProperty.call(runtime, variable.name)) value = runtime[variable.name];
305
+ if (value === void 0) continue;
306
+ if (value !== null && typeof value !== variable.type) throw new Error(`Variable "${variable.name}" must be ${variable.type}.`);
307
+ if (typeof value === "number" && !Number.isFinite(value)) throw new Error(`Variable "${variable.name}" must be a finite number.`);
308
+ Object.defineProperty(result, variable.name, { value, enumerable: true, configurable: true });
309
+ }
310
+ return result;
311
+ }
312
+ var WIDGET_TYPES = [
313
+ "bar",
314
+ "line",
315
+ "pie",
316
+ "table",
317
+ "kpi",
318
+ "listbox",
319
+ "label",
320
+ "labelContainer"
321
+ ];
81
322
  var DB_PROVIDERS = ["sqlite", "postgres", "mysql", "mssql"];
82
323
  var RTL_LOCALES = /* @__PURE__ */ new Set(["ar", "he", "fa", "ur"]);
83
324
  function resolveDashboardDir(dashboard) {
@@ -85,6 +326,181 @@ function resolveDashboardDir(dashboard) {
85
326
  const lang = (dashboard.locale || "en").split("-")[0]?.toLowerCase() || "en";
86
327
  return RTL_LOCALES.has(lang) ? "rtl" : "ltr";
87
328
  }
329
+ var LEGACY_LABEL_FOREGROUND = "#1a2b2b";
330
+ function sanitizeLabelStyleColor(color) {
331
+ if (!color?.trim()) return void 0;
332
+ if (color.trim().toLowerCase() === LEGACY_LABEL_FOREGROUND) return void 0;
333
+ return color;
334
+ }
335
+ function sanitizeLabelStyleBackground(bg) {
336
+ if (!bg?.trim()) return void 0;
337
+ const v = bg.trim().toLowerCase();
338
+ if (v === "transparent") return void 0;
339
+ return bg.trim();
340
+ }
341
+ function normalizeContainerLabels(raw) {
342
+ if (!Array.isArray(raw)) return [];
343
+ const out = [];
344
+ for (const item of raw) {
345
+ if (!item || typeof item !== "object") continue;
346
+ const o = item;
347
+ const text = typeof o.text === "string" ? o.text : "";
348
+ const id = typeof o.id === "string" && o.id.trim() ? o.id : cryptoRandomId();
349
+ out.push({
350
+ id,
351
+ text,
352
+ color: sanitizeLabelStyleColor(typeof o.color === "string" ? o.color : void 0),
353
+ backgroundColor: sanitizeLabelStyleBackground(
354
+ typeof o.backgroundColor === "string" ? o.backgroundColor : void 0
355
+ ),
356
+ fontSize: typeof o.fontSize === "number" ? o.fontSize : void 0,
357
+ targetDashboardId: typeof o.targetDashboardId === "string" ? o.targetDashboardId : void 0,
358
+ drillTitle: typeof o.drillTitle === "string" ? o.drillTitle : void 0
359
+ });
360
+ }
361
+ return out;
362
+ }
363
+ function createContainerLabelItem(text = "Label") {
364
+ return {
365
+ id: cryptoRandomId(),
366
+ text
367
+ };
368
+ }
369
+ function hasContainerLabelCustomStyles(item) {
370
+ return Boolean(
371
+ sanitizeLabelStyleColor(item.color) || sanitizeLabelStyleBackground(item.backgroundColor) || typeof item.fontSize === "number"
372
+ );
373
+ }
374
+ function resetContainerLabelItemStyles(item) {
375
+ const next = { id: item.id, text: item.text };
376
+ if (item.targetDashboardId) next.targetDashboardId = item.targetDashboardId;
377
+ if (item.drillTitle) next.drillTitle = item.drillTitle;
378
+ return next;
379
+ }
380
+ function normalizeContainerLabelTemplate(raw) {
381
+ if (!raw || typeof raw !== "object") return {};
382
+ const o = raw;
383
+ return {
384
+ color: sanitizeLabelStyleColor(typeof o.color === "string" ? o.color : void 0),
385
+ backgroundColor: sanitizeLabelStyleBackground(
386
+ typeof o.backgroundColor === "string" ? o.backgroundColor : void 0
387
+ ),
388
+ fontSize: typeof o.fontSize === "number" ? o.fontSize : void 0,
389
+ targetDashboardId: typeof o.targetDashboardId === "string" ? o.targetDashboardId : void 0,
390
+ drillTitle: typeof o.drillTitle === "string" ? o.drillTitle : void 0
391
+ };
392
+ }
393
+ function hasContainerLabelTemplateCustomStyles(template) {
394
+ return Boolean(
395
+ sanitizeLabelStyleColor(template.color) || sanitizeLabelStyleBackground(template.backgroundColor) || typeof template.fontSize === "number"
396
+ );
397
+ }
398
+ function resetContainerLabelTemplateStyles(template) {
399
+ const next = {};
400
+ if (template.targetDashboardId) next.targetDashboardId = template.targetDashboardId;
401
+ if (template.drillTitle) next.drillTitle = template.drillTitle;
402
+ return next;
403
+ }
404
+ function resolveLabelContainerSource(chartOptions) {
405
+ return chartOptions.labelSource === "query" ? "query" : "static";
406
+ }
407
+ function resolveLabelColumnKey(field, columns) {
408
+ if (!columns.length) return field || "";
409
+ if (field && columns.includes(field)) return field;
410
+ if (field?.includes(".")) {
411
+ const bare = field.slice(field.lastIndexOf(".") + 1);
412
+ if (columns.includes(bare)) return bare;
413
+ }
414
+ if (field) {
415
+ const match = columns.find(
416
+ (c) => c === field || c.endsWith(`.${field}`) || field.endsWith(`.${c}`)
417
+ );
418
+ if (match) return match;
419
+ }
420
+ return columns[0] || field || "";
421
+ }
422
+ function buildContainerLabelsFromQuery(rows, columns, dimensionField, template, drillDowns = []) {
423
+ const dim = resolveLabelColumnKey(dimensionField, columns);
424
+ if (!dim) return [];
425
+ const seen = /* @__PURE__ */ new Set();
426
+ const labels = [];
427
+ for (const row of rows) {
428
+ const raw = row[dim];
429
+ if (raw == null || raw === "") continue;
430
+ const text = String(raw);
431
+ if (seen.has(text)) continue;
432
+ seen.add(text);
433
+ const override = drillDowns.find((rule) => rule.value === text && (rule.field === dimensionField || rule.field === dim));
434
+ const targetDashboardId = override ? override.action === "dashboard" ? override.targetDashboardId : void 0 : template.targetDashboardId;
435
+ const titleTemplate = override ? override.drillTitle : template.drillTitle;
436
+ const drillTitle = titleTemplate ? titleTemplate.replace(/\{\{value\}\}/g, text) : text;
437
+ labels.push({
438
+ id: `query-${labels.length}-${text}`,
439
+ text,
440
+ color: template.color,
441
+ backgroundColor: template.backgroundColor,
442
+ fontSize: template.fontSize,
443
+ targetDashboardId,
444
+ drillTitle
445
+ });
446
+ }
447
+ return labels;
448
+ }
449
+ function labelWidgetShowsHeader(chartOptions) {
450
+ return chartOptions.showHeader !== false;
451
+ }
452
+ function resolveLabelClickAction(chartOptions, drillDown) {
453
+ const raw = chartOptions.clickAction;
454
+ if (raw === "url" || raw === "dashboard" || raw === "none") return raw;
455
+ if (drillDown?.targetDashboardId) return "dashboard";
456
+ return "none";
457
+ }
458
+ function getLabelClickUrl(chartOptions) {
459
+ const url = typeof chartOptions.clickUrl === "string" ? chartOptions.clickUrl.trim() : "";
460
+ return url || void 0;
461
+ }
462
+ function labelClickOpensNewTab(chartOptions) {
463
+ return chartOptions.clickUrlNewTab !== false;
464
+ }
465
+ function getKpiDefaultValue(chartOptions) {
466
+ const raw = chartOptions.defaultValue;
467
+ if (raw == null) return void 0;
468
+ if (typeof raw === "number" && Number.isFinite(raw)) return raw;
469
+ if (typeof raw === "string") {
470
+ const trimmed = raw.trim();
471
+ if (!trimmed) return void 0;
472
+ const n = Number(trimmed);
473
+ if (Number.isFinite(n)) return n;
474
+ return trimmed;
475
+ }
476
+ return void 0;
477
+ }
478
+ function createChartAxisGuideline(axis = "y", value = "") {
479
+ return {
480
+ id: cryptoRandomId(),
481
+ axis,
482
+ value
483
+ };
484
+ }
485
+ function normalizeChartAxisGuidelines(raw) {
486
+ if (!Array.isArray(raw)) return [];
487
+ const out = [];
488
+ for (const item of raw) {
489
+ if (!item || typeof item !== "object") continue;
490
+ const o = item;
491
+ const id = typeof o.id === "string" && o.id.trim() ? o.id : cryptoRandomId();
492
+ const axis = o.axis === "x" ? "x" : "y";
493
+ const value = typeof o.value === "number" && Number.isFinite(o.value) ? String(o.value) : typeof o.value === "string" ? o.value : "";
494
+ out.push({
495
+ id,
496
+ axis,
497
+ value,
498
+ label: typeof o.label === "string" ? o.label : void 0,
499
+ color: typeof o.color === "string" ? o.color : void 0
500
+ });
501
+ }
502
+ return out;
503
+ }
88
504
  function createEmptyDashboard(partial) {
89
505
  const id = partial?.id ?? cryptoRandomId();
90
506
  return {
@@ -97,6 +513,7 @@ function createEmptyDashboard(partial) {
97
513
  dir: partial?.dir,
98
514
  theme: partial?.theme,
99
515
  exportOptions: partial?.exportOptions,
516
+ displayOptions: partial?.displayOptions,
100
517
  layout: partial?.layout ?? [],
101
518
  globalFilters: partial?.globalFilters ?? [],
102
519
  widgets: partial?.widgets ?? [],
@@ -107,6 +524,52 @@ function createEmptyDashboard(partial) {
107
524
  }
108
525
  function createEmptyWidget(type = "bar") {
109
526
  const id = cryptoRandomId();
527
+ if (type === "label") {
528
+ return {
529
+ id,
530
+ type: "label",
531
+ title: "Label",
532
+ query: {
533
+ connectionId: "",
534
+ tables: [],
535
+ columns: [],
536
+ joins: [],
537
+ where: [],
538
+ limit: 0
539
+ },
540
+ binding: { dimensions: [], measures: [] },
541
+ chartOptions: {
542
+ text: "Your text here",
543
+ fontSize: 16
544
+ },
545
+ filters: []
546
+ };
547
+ }
548
+ if (type === "labelContainer") {
549
+ return {
550
+ id,
551
+ type: "labelContainer",
552
+ title: "Label container",
553
+ query: {
554
+ connectionId: "",
555
+ tables: [],
556
+ columns: [],
557
+ joins: [],
558
+ where: [],
559
+ limit: 0
560
+ },
561
+ binding: { dimensions: [], measures: [] },
562
+ chartOptions: {
563
+ layout: "vertical",
564
+ gap: 8,
565
+ padding: 12,
566
+ labelSource: "static",
567
+ labelTemplate: {},
568
+ labels: [createContainerLabelItem("First label"), createContainerLabelItem("Second label")]
569
+ },
570
+ filters: []
571
+ };
572
+ }
110
573
  return {
111
574
  id,
112
575
  type,
@@ -124,25 +587,73 @@ function createEmptyWidget(type = "bar") {
124
587
  filters: []
125
588
  };
126
589
  }
127
- function cryptoRandomId() {
128
- if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
129
- return crypto.randomUUID();
590
+ function createId() {
591
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
592
+ try {
593
+ return crypto.randomUUID();
594
+ } catch {
595
+ }
596
+ }
597
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
598
+ const bytes = new Uint8Array(16);
599
+ crypto.getRandomValues(bytes);
600
+ bytes[6] = bytes[6] & 15 | 64;
601
+ bytes[8] = bytes[8] & 63 | 128;
602
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
603
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
130
604
  }
131
- return `id_${Math.random().toString(36).slice(2, 11)}`;
605
+ return `id_${Math.random().toString(36).slice(2, 11)}${Date.now().toString(36)}`;
606
+ }
607
+ function cryptoRandomId() {
608
+ return createId();
132
609
  }
133
610
  export {
611
+ DASHBOARD_FILE_FORMAT,
612
+ DASHBOARD_FILE_VERSION,
134
613
  DB_PROVIDERS,
135
614
  DEFAULT_CHART_COLORS,
136
615
  DEFAULT_THEME_ACCENT,
616
+ LEGACY_LABEL_FOREGROUND,
137
617
  RTL_LOCALES,
138
618
  THEME_PRESETS,
139
619
  WIDGET_TYPES,
620
+ buildContainerLabelsFromQuery,
621
+ buildDashboardExportFile,
622
+ buildProcedureWhereClause,
623
+ cloneDashboardForImport,
624
+ createChartAxisGuideline,
625
+ createContainerLabelItem,
140
626
  createEmptyDashboard,
141
627
  createEmptyWidget,
628
+ createId,
629
+ getKpiDefaultValue,
630
+ getLabelClickUrl,
631
+ hasContainerLabelCustomStyles,
632
+ hasContainerLabelTemplateCustomStyles,
142
633
  isDefaultDashboardTheme,
634
+ labelClickOpensNewTab,
635
+ labelWidgetShowsHeader,
143
636
  matchThemePreset,
637
+ normalizeChartAxisGuidelines,
638
+ normalizeContainerLabelTemplate,
639
+ normalizeContainerLabels,
640
+ normalizeQueryLabelDrillDowns,
641
+ parseDashboardImport,
642
+ parseStoredProcedureName,
643
+ resetContainerLabelItemStyles,
644
+ resetContainerLabelTemplateStyles,
144
645
  resolveDashboardDir,
145
646
  resolveDashboardTheme,
647
+ resolveDashboardVariables,
648
+ resolveDisplayOptions,
146
649
  resolveEmailOptions,
147
- resolveExportOptions
650
+ resolveExportOptions,
651
+ resolveFilterVariables,
652
+ resolveLabelClickAction,
653
+ resolveLabelContainerSource,
654
+ resolveProcedureParameterValue,
655
+ resolveRequestVariables,
656
+ resolveVariableValue,
657
+ sanitizeLabelStyleBackground,
658
+ sanitizeLabelStyleColor
148
659
  };
package/package.json CHANGED
@@ -1,24 +1,29 @@
1
- {
2
- "name": "@dashboard-designer/core",
3
- "version": "0.1.1",
4
- "type": "module",
5
- "main": "./dist/index.js",
6
- "module": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
12
- }
13
- },
14
- "files": ["dist"],
15
- "scripts": {
16
- "build": "tsup src/index.ts --format esm --dts --clean",
17
- "typecheck": "tsc --noEmit",
18
- "dev": "tsup src/index.ts --format esm --dts --watch"
19
- },
20
- "devDependencies": {
21
- "tsup": "^8.4.0",
22
- "typescript": "^5.8.2"
23
- }
24
- }
1
+ {
2
+ "name": "@dashboard-designer/core",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "devDependencies": {
21
+ "tsup": "^8.4.0",
22
+ "typescript": "^5.8.2"
23
+ },
24
+ "scripts": {
25
+ "build": "tsup src/index.ts --format esm --dts --clean",
26
+ "typecheck": "tsc --noEmit",
27
+ "dev": "tsup src/index.ts --format esm --dts --watch"
28
+ }
29
+ }