@masterteam/components 0.0.205 → 0.0.207

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.
@@ -247,7 +247,9 @@ function isValidDropPosition(tokens, dropIndex, draggedTokens) {
247
247
  return true;
248
248
  }
249
249
  /**
250
- * Serialize tokens to formula string
250
+ * Serialize tokens to the canonical, executable formula string.
251
+ * Uses each token's `value` (e.g. `@Current::startdate`) — never `display` —
252
+ * so the produced expression is stable and engine/back-end compatible.
251
253
  */
252
254
  function serializeTokens(tokens) {
253
255
  const parts = [];
@@ -263,6 +265,29 @@ function serializeTokens(tokens) {
263
265
  }
264
266
  return parts.join('');
265
267
  }
268
+ /**
269
+ * Serialize tokens to a human-readable preview string using each token's
270
+ * `display` label (the friendly property name) when present, falling back to
271
+ * its `value`. Spacing is computed from the canonical `value`/`type` so that a
272
+ * friendly name containing spaces (e.g. "Start Date") does not corrupt
273
+ * function/paren/separator spacing. This output is for display/preview ONLY
274
+ * (e.g. `formulaText`) — never feed it to the validator or persist it as the
275
+ * executable expression.
276
+ */
277
+ function serializeTokensForDisplay(tokens) {
278
+ const parts = [];
279
+ let lastType = null;
280
+ let lastValue = '';
281
+ for (const token of tokens) {
282
+ if (shouldInsertSpace(lastType, lastValue, token)) {
283
+ parts.push(' ');
284
+ }
285
+ parts.push(token.display ?? token.value);
286
+ lastType = token.type;
287
+ lastValue = token.value;
288
+ }
289
+ return parts.join('');
290
+ }
266
291
  function shouldInsertSpace(previousType, previousValue, current) {
267
292
  if (!previousType)
268
293
  return false;
@@ -1100,6 +1125,103 @@ function getReferenceCompletionBounds(lineContent, column, suggestion) {
1100
1125
  };
1101
1126
  }
1102
1127
 
1128
+ /** Path (relative to the document base) where the host copies monaco `min/vs`. */
1129
+ const MONACO_ASSET_DIR = 'assets/monaco/vs';
1130
+ /**
1131
+ * Shared, lazily-resolved Monaco loader promise (module scope so every editor
1132
+ * instance reuses a single load).
1133
+ */
1134
+ let monacoLoadPromise = null;
1135
+ /** Absolute URL to the copied Monaco `vs` folder, with no trailing slash. */
1136
+ function resolveMonacoAssetBase(doc) {
1137
+ return new URL(`${MONACO_ASSET_DIR}/`, doc.baseURI)
1138
+ .toString()
1139
+ .replace(/\/$/, '');
1140
+ }
1141
+ /**
1142
+ * Point Monaco's web workers at the copied assets via a tiny same-origin proxy
1143
+ * worker. Loading workers from `/assets/monaco/vs` (instead of node_modules)
1144
+ * avoids the Vite `@fs` serving-allow-list 403 and the "define
1145
+ * MonacoEnvironment.getWorkerUrl" warning. Set once; respects a host-provided
1146
+ * MonacoEnvironment if one already exists.
1147
+ */
1148
+ function configureMonacoWorker(base) {
1149
+ const globalScope = self;
1150
+ if (globalScope.MonacoEnvironment) {
1151
+ return;
1152
+ }
1153
+ globalScope.MonacoEnvironment = {
1154
+ getWorkerUrl: () => {
1155
+ const proxy = `self.MonacoEnvironment={baseUrl:'${base}/'};` +
1156
+ `importScripts('${base}/base/worker/workerMain.js');`;
1157
+ return `data:text/javascript;charset=utf-8,${encodeURIComponent(proxy)}`;
1158
+ },
1159
+ };
1160
+ }
1161
+ /**
1162
+ * Load Monaco via its own AMD loader from `/assets/monaco/vs`. This is fully
1163
+ * self-contained: `editor.main` injects its CSS and the codicon font from the
1164
+ * same folder, and workers resolve from there too — so no editor CSS/font is
1165
+ * pulled into the app bundle and there is no node_modules/`@fs` access at all.
1166
+ */
1167
+ function loadMonacoFromAssets(doc, base) {
1168
+ return new Promise((resolve, reject) => {
1169
+ const globalScope = window;
1170
+ if (globalScope.monaco) {
1171
+ resolve({ monaco: globalScope.monaco, fromAssets: true });
1172
+ return;
1173
+ }
1174
+ const startRequire = () => {
1175
+ const amdRequire = globalScope.require;
1176
+ if (!amdRequire?.config) {
1177
+ reject(new Error('Monaco AMD loader is unavailable'));
1178
+ return;
1179
+ }
1180
+ configureMonacoWorker(base);
1181
+ amdRequire.config({ paths: { vs: base } });
1182
+ amdRequire(['vs/editor/editor.main'], () => globalScope.monaco
1183
+ ? resolve({ monaco: globalScope.monaco, fromAssets: true })
1184
+ : reject(new Error('Monaco did not initialize')), (error) => reject(error));
1185
+ };
1186
+ if (globalScope.require?.config) {
1187
+ startRequire();
1188
+ return;
1189
+ }
1190
+ const existing = doc.querySelector('script[data-mt-monaco-loader]');
1191
+ if (existing) {
1192
+ existing.addEventListener('load', startRequire, { once: true });
1193
+ existing.addEventListener('error', () => reject(new Error('Monaco loader failed to load')), { once: true });
1194
+ return;
1195
+ }
1196
+ const script = doc.createElement('script');
1197
+ script.src = `${base}/loader.js`;
1198
+ script.async = true;
1199
+ script.dataset['mtMonacoLoader'] = 'true';
1200
+ script.addEventListener('load', startRequire, { once: true });
1201
+ script.addEventListener('error', () => reject(new Error('Monaco loader failed to load')), { once: true });
1202
+ doc.head.appendChild(script);
1203
+ });
1204
+ }
1205
+ /**
1206
+ * Resolve Monaco once, preferring the self-contained assets loader and falling
1207
+ * back to the bundled ESM build if `/assets/monaco/vs` is unavailable (so hosts
1208
+ * that do not copy `min/vs` keep working, just without the asset-served CSS).
1209
+ */
1210
+ function loadMonaco(doc) {
1211
+ if (monacoLoadPromise) {
1212
+ return monacoLoadPromise;
1213
+ }
1214
+ const base = resolveMonacoAssetBase(doc);
1215
+ monacoLoadPromise = loadMonacoFromAssets(doc, base).catch(async (error) => {
1216
+ console.warn(`[mt-formula-editor-code] Could not load Monaco from ${base}; falling back ` +
1217
+ `to the bundled monaco-editor. Copy "node_modules/monaco-editor/min/vs/" ` +
1218
+ `to "/assets/monaco/vs/" in the host app's angular.json for the ` +
1219
+ `self-contained loader (CSS, codicon font, and workers from assets).`, error);
1220
+ const monaco = (await import('monaco-editor'));
1221
+ return { monaco, fromAssets: false };
1222
+ });
1223
+ return monacoLoadPromise;
1224
+ }
1103
1225
  class FormulaEditorCode {
1104
1226
  placeholder = input('Enter formula...', ...(ngDevMode ? [{ debugName: "placeholder" }] : /* istanbul ignore next */ []));
1105
1227
  initialFormula = input('', ...(ngDevMode ? [{ debugName: "initialFormula" }] : /* istanbul ignore next */ []));
@@ -1251,15 +1373,20 @@ class FormulaEditorCode {
1251
1373
  const host = this.editorHost()?.nativeElement;
1252
1374
  if (!host)
1253
1375
  return;
1254
- this.ensureMonacoStylesLoaded();
1255
- let monaco;
1376
+ let loaded;
1256
1377
  try {
1257
- monaco = await import('monaco-editor');
1378
+ loaded = await loadMonaco(this.document);
1258
1379
  }
1259
1380
  catch (error) {
1260
1381
  console.warn('Failed to load Monaco editor:', error);
1261
1382
  return;
1262
1383
  }
1384
+ const monaco = loaded.monaco;
1385
+ // The assets (AMD) path injects its own CSS + codicon font from
1386
+ // /assets/monaco/vs. Only the bundled ESM fallback needs the manual link.
1387
+ if (!loaded.fromAssets) {
1388
+ this.ensureMonacoStylesLoaded();
1389
+ }
1263
1390
  this.monaco = monaco;
1264
1391
  this.ensureFormulaAssets(monaco);
1265
1392
  const model = monaco.editor.createModel(this.value(), this.language());
@@ -3351,17 +3478,29 @@ class FormulaRuntimeEngine {
3351
3478
  return compiled;
3352
3479
  }
3353
3480
  deserializeFormulaTokens(formulaTokens) {
3354
- let parsed;
3355
- try {
3356
- parsed = JSON.parse(formulaTokens);
3357
- }
3358
- catch {
3359
- throw new Error('Formula tokens JSON is invalid');
3360
- }
3361
- if (!Array.isArray(parsed)) {
3362
- throw new Error('Formula tokens must be an array');
3481
+ const trimmed = formulaTokens.trim();
3482
+ // `formulaTokens` may be persisted in two equivalent encodings:
3483
+ // - the canonical executable EXPRESSION string (e.g.
3484
+ // "OR(ISNULL(@Current::x), ...)") — what the back-end stores; or
3485
+ // - a JSON token array (legacy / inline-form snapshots).
3486
+ // Accept both: a value that parses to an array of token objects is used
3487
+ // directly; anything else is tokenized from the expression string.
3488
+ if (trimmed.startsWith('[')) {
3489
+ try {
3490
+ const parsed = JSON.parse(trimmed);
3491
+ if (Array.isArray(parsed) &&
3492
+ (parsed.length === 0 ||
3493
+ (typeof parsed[0] === 'object' &&
3494
+ parsed[0] !== null &&
3495
+ 'type' in parsed[0]))) {
3496
+ return parsed;
3497
+ }
3498
+ }
3499
+ catch {
3500
+ // Not valid JSON — fall through and treat it as an expression string.
3501
+ }
3363
3502
  }
3364
- return parsed;
3503
+ return tokenizeFormulaTemplate(trimmed);
3365
3504
  }
3366
3505
  toLexTokens(tokens) {
3367
3506
  if (!tokens.length) {
@@ -3664,5 +3803,5 @@ function createRuntimeError(code, error) {
3664
3803
  * Generated bundle index. Do not edit.
3665
3804
  */
3666
3805
 
3667
- export { CONDITION_FUNCTION_CATEGORIES, CONDITION_OPERATORS, CONDITION_RUNTIME_CATALOG, DEFAULT_OPERATORS, FormulaEditor, FormulaEditorCode, FormulaRuntimeEngine, FormulaStatusBar, FormulaToolbar, FormulaToolbarItem, OPERATOR_SYMBOL_TO_TRANSLATION_KEY, VALIDATION_FUNCTION_CATEGORIES, VALIDATION_OPERATORS, VALIDATION_RUNTIME_CATALOG, cloneBlock, cloneToken, cloneTokens, createFunctionBlock, createFunctionTokens, createLiteralBlock, createLiteralToken, createOperatorBlock, createOperatorToken, createPropertyBlock, createPropertyToken, createTextToken, findFunctionRange, generateFunctionId, generateSmartBlockId, generateTokenId, getArgumentIndexAtPosition, getFunctionTokens, isValidDropPosition, parseSignature, recalculateDepths, serializeTokens, tokenizeFormulaTemplate };
3806
+ export { CONDITION_FUNCTION_CATEGORIES, CONDITION_OPERATORS, CONDITION_RUNTIME_CATALOG, DEFAULT_OPERATORS, FormulaEditor, FormulaEditorCode, FormulaRuntimeEngine, FormulaStatusBar, FormulaToolbar, FormulaToolbarItem, OPERATOR_SYMBOL_TO_TRANSLATION_KEY, VALIDATION_FUNCTION_CATEGORIES, VALIDATION_OPERATORS, VALIDATION_RUNTIME_CATALOG, cloneBlock, cloneToken, cloneTokens, createFunctionBlock, createFunctionTokens, createLiteralBlock, createLiteralToken, createOperatorBlock, createOperatorToken, createPropertyBlock, createPropertyToken, createTextToken, findFunctionRange, generateFunctionId, generateSmartBlockId, generateTokenId, getArgumentIndexAtPosition, getFunctionTokens, isValidDropPosition, parseSignature, recalculateDepths, serializeTokens, serializeTokensForDisplay, shouldInsertSpace, tokenizeFormulaTemplate };
3668
3807
  //# sourceMappingURL=masterteam-components-formula.mjs.map