@atscript/ui 0.1.151 → 0.1.153

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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Validator, createDataFromAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType } from "@atscript/typescript/utils";
2
- import { Client, actionIdentifier, encodeNavigateId } from "@atscript/db-client";
2
+ import { Client, actionIdentifier, clearMetaStore, encodeNavigateId } from "@atscript/db-client";
3
3
  import { createDbValidatorPlugin } from "@atscript/db/validator";
4
4
  //#region src/shared/annotation-keys.ts
5
5
  const UI_TYPE = "ui.type";
@@ -1013,7 +1013,7 @@ async function fetchDistinctValues(client, field, opts = {}) {
1013
1013
  }
1014
1014
  //#endregion
1015
1015
  //#region src/client-factory.ts
1016
- const builtin = (url) => new Client(url);
1016
+ const builtin = (url, options) => new Client(url, options);
1017
1017
  let _default = builtin;
1018
1018
  /**
1019
1019
  * Override the app-wide default factory. Call once at startup (e.g. in
@@ -1023,7 +1023,7 @@ let _default = builtin;
1023
1023
  function setDefaultClientFactory(factory) {
1024
1024
  _default = factory;
1025
1025
  }
1026
- /** Current app-wide default factory. Falls back to `new Client(url)`. */
1026
+ /** Current app-wide default factory. Falls back to `new Client(url, options)`. */
1027
1027
  function getDefaultClientFactory() {
1028
1028
  return _default;
1029
1029
  }
@@ -1032,43 +1032,346 @@ function resetDefaultClientFactory() {
1032
1032
  _default = builtin;
1033
1033
  }
1034
1034
  //#endregion
1035
+ //#region src/form/measurement.ts
1036
+ /**
1037
+ * Read measurement annotations off a single field prop. Returns `undefined`
1038
+ * for any annotation that's absent — callers can spread the result into a
1039
+ * larger record.
1040
+ */
1041
+ function extractMeasurement(prop) {
1042
+ const precisionMeta = getFieldMeta(prop, DB_COLUMN_PRECISION);
1043
+ return {
1044
+ currencyCode: getFieldMeta(prop, DB_AMOUNT_CURRENCY),
1045
+ currencyRefField: getFieldMeta(prop, DB_AMOUNT_CURRENCY_REF),
1046
+ unitCode: getFieldMeta(prop, DB_UNIT),
1047
+ unitRefField: getFieldMeta(prop, DB_UNIT_REF),
1048
+ precisionScale: precisionMeta?.scale
1049
+ };
1050
+ }
1051
+ //#endregion
1052
+ //#region src/table/create-table-def.ts
1053
+ /**
1054
+ * Builds a TableDef from a moost-db MetaResponse.
1055
+ *
1056
+ * 1. Deserializes `meta.type` into a live TAtscriptAnnotatedType
1057
+ * 2. Flattens to discover all field paths
1058
+ * 3. Builds ColumnDef per field using annotations + meta.fields capabilities
1059
+ * 4. Sorts by @ui.table.order
1060
+ */
1061
+ function createTableDef(meta, preDeserializedType) {
1062
+ const type = preDeserializedType ?? deserializeAnnotatedType(meta.type);
1063
+ const flatMap = type.type.kind === "object" ? flattenAnnotatedType(type, { excludePhantomTypes: true }) : /* @__PURE__ */ new Map();
1064
+ const columns = [];
1065
+ for (const [path, prop] of flatMap.entries()) {
1066
+ if (path === "") continue;
1067
+ if (path === meta.versionColumn) continue;
1068
+ const fieldMeta = meta.fields[path];
1069
+ if (!isReadable(fieldMeta)) continue;
1070
+ if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
1071
+ const options = extractFieldLiteralOptions(prop);
1072
+ const valueHelpInfo = extractValueHelp(prop);
1073
+ let distinct;
1074
+ if (!valueHelpInfo && !options && fieldMeta.groupable && fieldMeta.filterable) {
1075
+ const url = type.metadata.get(DB_HTTP_PATH);
1076
+ if (url && getFieldMeta(prop, "ui.valueHelp.distinct") !== void 0) distinct = {
1077
+ url,
1078
+ field: path
1079
+ };
1080
+ }
1081
+ columns.push(buildColumn(path, prop, fieldMeta, {
1082
+ options,
1083
+ valueHelpInfo,
1084
+ distinct
1085
+ }));
1086
+ }
1087
+ if (meta.decorations) {
1088
+ const decoType = deserializeAnnotatedType(meta.decorations);
1089
+ if (decoType.type.kind === "object") for (const [path, prop] of decoType.type.props) {
1090
+ const fieldMeta = meta.fields[path];
1091
+ if (!fieldMeta?.decoration || flatMap.has(path)) continue;
1092
+ if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
1093
+ flatMap.set(path, prop);
1094
+ columns.push(buildColumn(path, prop, fieldMeta, { options: extractFieldLiteralOptions(prop) }));
1095
+ }
1096
+ }
1097
+ columns.sort((a, b) => a.order - b.order);
1098
+ const actions = groupActions(meta.actions ?? []);
1099
+ const crud = meta.crud ?? {};
1100
+ const preferredId = meta.preferredId ?? meta.primaryKeys;
1101
+ return {
1102
+ type,
1103
+ columns,
1104
+ flatMap,
1105
+ fetchableFields: new Set(Object.keys(meta.fields).filter((p) => isReadable(meta.fields[p]))),
1106
+ primaryKeys: meta.primaryKeys,
1107
+ preferredId,
1108
+ identifierFields: identifierFieldsOf(preferredId, meta.actions ?? []),
1109
+ versionColumn: meta.versionColumn,
1110
+ crud,
1111
+ canRemove: "remove" in crud,
1112
+ actions,
1113
+ searchable: meta.searchable,
1114
+ vectorSearchable: meta.vectorSearchable,
1115
+ searchIndexes: meta.searchIndexes,
1116
+ relations: meta.relations
1117
+ };
1118
+ }
1119
+ /**
1120
+ * One column. A server-declared display-only column (`fieldMeta.decoration`)
1121
+ * is never sortable, filterable or groupable and always nullable (a decoration
1122
+ * can be absent); an ordinary one takes its capabilities from `/meta`.
1123
+ */
1124
+ function buildColumn(path, prop, fieldMeta, resolved) {
1125
+ const { options, valueHelpInfo, distinct } = resolved;
1126
+ const maxLengthMeta = getFieldMeta(prop, EXPECT_MAX_LENGTH);
1127
+ const tableType = getFieldMeta(prop, UI_TABLE_TYPE);
1128
+ const sharedType = getFieldMeta(prop, UI_TYPE);
1129
+ const tableComponent = getFieldMeta(prop, UI_TABLE_COMPONENT);
1130
+ const decoration = fieldMeta.decoration === true;
1131
+ const filterOps = decoration ? void 0 : fieldMeta.filterOps;
1132
+ return {
1133
+ path,
1134
+ label: getFieldMeta(prop, "meta.label") ?? humanizePath(path),
1135
+ type: tableType ?? sharedType ?? (valueHelpInfo ? "ref" : inferDisplayType(prop, options)),
1136
+ valueKind: inferValueKind(prop),
1137
+ component: tableComponent,
1138
+ selectWith: getFieldMeta(prop, UI_TABLE_SELECT_WITH),
1139
+ sortable: !decoration && (fieldMeta.sortable ?? false),
1140
+ filterable: !decoration && (fieldMeta.filterable ?? false),
1141
+ ...filterOps && { filterOps: [...filterOps] },
1142
+ nullable: decoration || prop.optional === true,
1143
+ width: getFieldMeta(prop, UI_TABLE_WIDTH),
1144
+ maxLen: maxLengthMeta?.length,
1145
+ order: getFieldMeta(prop, "ui.table.order") ?? Infinity,
1146
+ options,
1147
+ valueHelpInfo,
1148
+ ...distinct && { distinct },
1149
+ ...extractMeasurement(prop)
1150
+ };
1151
+ }
1152
+ /**
1153
+ * `preferredId` ∪ every delegated action's `idMap` paths, in that order —
1154
+ * the same array when no action carries an `idMap`.
1155
+ */
1156
+ function identifierFieldsOf(preferredId, actions) {
1157
+ let out;
1158
+ for (const a of actions) {
1159
+ if (!a.idMap) continue;
1160
+ for (const path of Object.values(a.idMap)) {
1161
+ if (preferredId.includes(path) || out?.includes(path)) continue;
1162
+ (out ??= [...preferredId]).push(path);
1163
+ }
1164
+ }
1165
+ return out ?? preferredId;
1166
+ }
1167
+ /** A field the caller may read: listed in `meta.fields` and not write-only. */
1168
+ function isReadable(field) {
1169
+ return field !== void 0 && field.writeOnly !== true;
1170
+ }
1171
+ /** Sort by (order ?? 0). `toSorted` is stable per spec, so ties preserve declaration order. */
1172
+ function byOrder(xs) {
1173
+ return xs.toSorted((x, y) => (x.order ?? 0) - (y.order ?? 0));
1174
+ }
1175
+ /**
1176
+ * Partition actions by `level`, sort each group by `(order ?? 0)` then
1177
+ * declaration order, and pick the first `default: true` entry per level.
1178
+ * The synthesised `__remove` UI action lives outside this set and is never
1179
+ * a candidate for `default.row`.
1180
+ */
1181
+ function groupActions(actions) {
1182
+ const table = [];
1183
+ const row = [];
1184
+ const rows = [];
1185
+ for (const a of actions) if (a.level === "table") table.push(a);
1186
+ else if (a.level === "row") row.push(a);
1187
+ else if (a.level === "rows") rows.push(a);
1188
+ const tableSorted = byOrder(table);
1189
+ const rowSorted = byOrder(row);
1190
+ const rowsSorted = byOrder(rows);
1191
+ return {
1192
+ table: tableSorted,
1193
+ row: rowSorted,
1194
+ rows: rowsSorted,
1195
+ default: {
1196
+ table: tableSorted.find((a) => a.default === true),
1197
+ row: rowSorted.find((a) => a.default === true),
1198
+ rows: rowsSorted.find((a) => a.default === true)
1199
+ }
1200
+ };
1201
+ }
1202
+ /** Infers a display type string from the annotated type's kind and designType. */
1203
+ function inferDisplayType(prop, literalOpts) {
1204
+ const kind = prop.type.kind;
1205
+ if (kind === "array") return "array";
1206
+ if (kind === "object") return "object";
1207
+ if (kind === "union") return literalOpts !== void 0 ? "enum" : "union";
1208
+ if (kind === "") {
1209
+ const final = prop.type;
1210
+ const dt = final.designType;
1211
+ if (dt === "number") return final.tags?.has("timestamp") ? "datetime" : "number";
1212
+ if (dt === "decimal") return "number";
1213
+ if (dt === "boolean") return "boolean";
1214
+ return "text";
1215
+ }
1216
+ return "text";
1217
+ }
1218
+ /**
1219
+ * Number metadata that makes the server treat a plain `number` column as an
1220
+ * integer (mirrors the db layer's `valueTypeOf`), beside the `int` / `expect.int` tags.
1221
+ */
1222
+ const INTEGER_NUMBER_META = [
1223
+ "expect.int",
1224
+ "db.default.increment",
1225
+ "db.default.now",
1226
+ "db.agg.count",
1227
+ "db.agg.countDistinct"
1228
+ ];
1229
+ /** The kind of one scalar leaf, or `undefined` for a non-scalar / unknown design type. */
1230
+ function scalarValueKind(prop) {
1231
+ const final = prop.type;
1232
+ const tags = final.tags;
1233
+ switch (final.designType) {
1234
+ case "string": return tags?.has("isoDate") ? "isoDate" : tags?.has("date") ? "date" : "string";
1235
+ case "number":
1236
+ if (tags?.has("timestamp")) return "timestamp";
1237
+ if (tags?.has("int") || INTEGER_NUMBER_META.some((k) => prop.metadata.has(k))) return "integer";
1238
+ return "number";
1239
+ case "decimal": return "decimal";
1240
+ case "boolean": return "boolean";
1241
+ default: return;
1242
+ }
1243
+ }
1244
+ /** Kinds of every non-null leaf of a (possibly nested) union; `null` when one is not a scalar. */
1245
+ function collectUnionKinds(items, out) {
1246
+ for (const item of items) {
1247
+ if (item.type.kind === "union") {
1248
+ collectUnionKinds(item.type.items, out);
1249
+ continue;
1250
+ }
1251
+ if (item.type.kind === "") {
1252
+ const dt = item.type.designType;
1253
+ if (dt === "null" || dt === "undefined") continue;
1254
+ out.add(scalarValueKind(item));
1255
+ continue;
1256
+ }
1257
+ out.add(void 0);
1258
+ }
1259
+ }
1260
+ /**
1261
+ * Scalar storage kind of the column's value — what the server's filter guard
1262
+ * checks. A scalar maps to its kind; a union that agrees on one kind across
1263
+ * its non-null members (`'a' | 'b'`, `1 | 2`, `number.timestamp | null`)
1264
+ * takes it; arrays, objects, JSON and mixed unions have none (`undefined`),
1265
+ * which means no value coercion.
1266
+ */
1267
+ function inferValueKind(prop) {
1268
+ const kind = prop.type.kind;
1269
+ if (kind === "") return scalarValueKind(prop);
1270
+ if (kind !== "union") return void 0;
1271
+ const kinds = /* @__PURE__ */ new Set();
1272
+ collectUnionKinds(prop.type.items, kinds);
1273
+ if (kinds.size !== 1) return void 0;
1274
+ return [...kinds][0];
1275
+ }
1276
+ //#endregion
1035
1277
  //#region src/shared/meta-cache.ts
1036
1278
  const cache = /* @__PURE__ */ new Map();
1279
+ /** Derived shapes per `ETag`, least recently used first. Browser only. */
1280
+ const derivedByEtag = /* @__PURE__ */ new Map();
1281
+ const MAX_DERIVED = 50;
1282
+ /** The `Derived` promise behind each handed-out entry (kept off the public shape). */
1283
+ const derivedOf = /* @__PURE__ */ new WeakMap();
1284
+ /** Custom `/meta` stores of clients this cache created in the browser. */
1285
+ const customStores = /* @__PURE__ */ new Set();
1037
1286
  /** `undefined` until the first `setMetaCacheIdentity` call; `null` = anonymous. */
1038
1287
  let identity;
1288
+ const resetListeners = /* @__PURE__ */ new Set();
1039
1289
  /**
1040
- * Get or create the cache entry for `url`. First caller's `factory` seeds the
1041
- * `Client`; subsequent callers reuse it. On `meta` rejection, the entry is
1042
- * evicted so the next call retries. Without a browser `window` nothing is
1043
- * cached.
1290
+ * Get or create the cache entry for `url`. First caller's `factory` (and
1291
+ * `options.metaKey`) seeds the `Client`; subsequent callers reuse it. On
1292
+ * `meta` rejection, the entry is evicted so the next call retries. Without a
1293
+ * browser `window` nothing is cached and the client is asked for
1294
+ * `metaStore: false`.
1044
1295
  */
1045
- function getMetaEntry(url, factory) {
1296
+ function getMetaEntry(url, factory, options) {
1046
1297
  const browser = typeof window !== "undefined";
1047
1298
  const existing = browser ? cache.get(url) : void 0;
1048
1299
  if (existing) return existing;
1049
- const client = (factory ?? getDefaultClientFactory())(url);
1300
+ const f = factory ?? getDefaultClientFactory();
1301
+ let client;
1302
+ if (!browser) client = f(url, { metaStore: false });
1303
+ else if (options?.metaKey) client = f(url, { metaKey: options.metaKey });
1304
+ else client = f(url);
1305
+ if (browser) rememberStore(client);
1050
1306
  const meta = client.meta().catch((err) => {
1051
1307
  if (cache.get(url) === entry) cache.delete(url);
1052
1308
  throw err;
1053
1309
  });
1310
+ const derived = meta.then((m) => derive(client, m, browser));
1311
+ const type = derived.then((d) => d.type);
1312
+ type.catch(() => {});
1054
1313
  const entry = {
1055
1314
  client,
1056
1315
  meta,
1057
- type: meta.then((m) => deserializeAnnotatedType(m.type))
1316
+ type
1058
1317
  };
1318
+ derivedOf.set(entry, derived);
1059
1319
  if (browser) cache.set(url, entry);
1060
1320
  return entry;
1061
1321
  }
1062
1322
  /**
1323
+ * The `TableDef` for a cache entry, built once per entry — and once per
1324
+ * `/meta` `ETag` across entries. Since 0.1.153.
1325
+ */
1326
+ function getMetaTableDef(entry) {
1327
+ if (!entry.tableDef) {
1328
+ const derived = derivedOf.get(entry);
1329
+ entry.tableDef = derived ? Promise.all([entry.meta, derived]).then(([meta, d]) => d.tableDef ??= createTableDef(meta, d.type)) : Promise.all([entry.meta, entry.type]).then(([meta, type]) => createTableDef(meta, type));
1330
+ }
1331
+ return entry.tableDef;
1332
+ }
1333
+ function derive(client, meta, browser) {
1334
+ const etag = browser ? client.metaEtag?.() : void 0;
1335
+ if (etag === void 0) return { type: deserializeAnnotatedType(meta.type) };
1336
+ const hit = derivedByEtag.get(etag);
1337
+ if (hit) {
1338
+ derivedByEtag.delete(etag);
1339
+ derivedByEtag.set(etag, hit);
1340
+ return hit;
1341
+ }
1342
+ const fresh = { type: deserializeAnnotatedType(meta.type) };
1343
+ derivedByEtag.set(etag, fresh);
1344
+ if (derivedByEtag.size > MAX_DERIVED) derivedByEtag.delete(derivedByEtag.keys().next().value);
1345
+ return fresh;
1346
+ }
1347
+ /**
1348
+ * Remember a custom `/meta` store a factory gave `client`, so a reset can
1349
+ * clear it. The store is a private field of `Client`, read defensively: the
1350
+ * default store is cleared through `clearMetaStore()`, and a store-less
1351
+ * client or a test double is skipped.
1352
+ */
1353
+ function rememberStore(client) {
1354
+ const store = client._metaStore;
1355
+ if (typeof store?.clear === "function") customStores.add(store);
1356
+ }
1357
+ /**
1063
1358
  * Drop every cached `/meta` — including the copy each cached `Client`
1064
- * memoizes — and the value-help searches shared under them. Entries already
1359
+ * memoizes and the `@atscript/db-client` meta stores used to revalidate it
1360
+ * (the shared default one and any custom one a factory supplied) — the
1361
+ * value-help searches shared under them, and everything registered through
1362
+ * {@link onMetaCacheReset} (e.g. the table-presets cache). Entries already
1065
1363
  * handed out keep working; the next `getMetaEntry` refetches.
1066
1364
  */
1067
1365
  function resetMetaCache() {
1068
1366
  const entries = [...cache.values()];
1069
1367
  cache.clear();
1368
+ derivedByEtag.clear();
1070
1369
  for (const entry of entries) entry.client.invalidateMeta?.();
1370
+ clearMetaStore();
1371
+ for (const store of customStores) store.clear();
1372
+ customStores.clear();
1071
1373
  invalidateValueHelpCache();
1374
+ for (const listener of resetListeners) listener();
1072
1375
  }
1073
1376
  /**
1074
1377
  * Bind the meta cache to the current viewer. Call it whenever the signed-in
@@ -1076,6 +1379,9 @@ function resetMetaCache() {
1076
1379
  * every reload of the current user. A key that differs from the previous
1077
1380
  * one resets the cache (`resetMetaCache`); the same key keeps it. `null` /
1078
1381
  * `undefined` = anonymous.
1382
+ *
1383
+ * Binding an identity also turns on caches that are only safe when the app
1384
+ * reports sign-in changes, such as the table-presets cache.
1079
1385
  */
1080
1386
  function setMetaCacheIdentity(key) {
1081
1387
  const next = key ?? null;
@@ -1083,6 +1389,24 @@ function setMetaCacheIdentity(key) {
1083
1389
  identity = next;
1084
1390
  resetMetaCache();
1085
1391
  }
1392
+ /**
1393
+ * The identity last passed to {@link setMetaCacheIdentity}: `undefined` when
1394
+ * the app never bound one, `null` for anonymous. Since 0.1.153.
1395
+ */
1396
+ function getMetaCacheIdentity() {
1397
+ return identity;
1398
+ }
1399
+ /**
1400
+ * Run `listener` on every {@link resetMetaCache} (and so on every identity
1401
+ * change). For caches that belong to the signed-in viewer. Returns an
1402
+ * unsubscribe function. Since 0.1.153.
1403
+ */
1404
+ function onMetaCacheReset(listener) {
1405
+ resetListeners.add(listener);
1406
+ return () => {
1407
+ resetListeners.delete(listener);
1408
+ };
1409
+ }
1086
1410
  //#endregion
1087
1411
  //#region src/value-help/resolve.ts
1088
1412
  /**
@@ -2226,23 +2550,6 @@ function resolveSingularLabel(meta) {
2226
2550
  return getFieldMeta(meta, "ui.form.label.singular") || "item";
2227
2551
  }
2228
2552
  //#endregion
2229
- //#region src/form/measurement.ts
2230
- /**
2231
- * Read measurement annotations off a single field prop. Returns `undefined`
2232
- * for any annotation that's absent — callers can spread the result into a
2233
- * larger record.
2234
- */
2235
- function extractMeasurement(prop) {
2236
- const precisionMeta = getFieldMeta(prop, DB_COLUMN_PRECISION);
2237
- return {
2238
- currencyCode: getFieldMeta(prop, DB_AMOUNT_CURRENCY),
2239
- currencyRefField: getFieldMeta(prop, DB_AMOUNT_CURRENCY_REF),
2240
- unitCode: getFieldMeta(prop, DB_UNIT),
2241
- unitRefField: getFieldMeta(prop, DB_UNIT_REF),
2242
- precisionScale: precisionMeta?.scale
2243
- };
2244
- }
2245
- //#endregion
2246
2553
  //#region src/form/decimal-format.ts
2247
2554
  const WHITESPACE_GROUP_RE = /[   ]/g;
2248
2555
  const numberFormatCache = /* @__PURE__ */ new Map();
@@ -2557,231 +2864,6 @@ function groupInteger(integer, locale) {
2557
2864
  return out.join(sep);
2558
2865
  }
2559
2866
  //#endregion
2560
- //#region src/table/create-table-def.ts
2561
- /**
2562
- * Builds a TableDef from a moost-db MetaResponse.
2563
- *
2564
- * 1. Deserializes `meta.type` into a live TAtscriptAnnotatedType
2565
- * 2. Flattens to discover all field paths
2566
- * 3. Builds ColumnDef per field using annotations + meta.fields capabilities
2567
- * 4. Sorts by @ui.table.order
2568
- */
2569
- function createTableDef(meta, preDeserializedType) {
2570
- const type = preDeserializedType ?? deserializeAnnotatedType(meta.type);
2571
- const flatMap = type.type.kind === "object" ? flattenAnnotatedType(type, { excludePhantomTypes: true }) : /* @__PURE__ */ new Map();
2572
- const columns = [];
2573
- for (const [path, prop] of flatMap.entries()) {
2574
- if (path === "") continue;
2575
- if (path === meta.versionColumn) continue;
2576
- const fieldMeta = meta.fields[path];
2577
- if (!isReadable(fieldMeta)) continue;
2578
- if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
2579
- const options = extractFieldLiteralOptions(prop);
2580
- const valueHelpInfo = extractValueHelp(prop);
2581
- let distinct;
2582
- if (!valueHelpInfo && !options && fieldMeta.groupable && fieldMeta.filterable) {
2583
- const url = type.metadata.get(DB_HTTP_PATH);
2584
- if (url && getFieldMeta(prop, "ui.valueHelp.distinct") !== void 0) distinct = {
2585
- url,
2586
- field: path
2587
- };
2588
- }
2589
- columns.push(buildColumn(path, prop, fieldMeta, {
2590
- options,
2591
- valueHelpInfo,
2592
- distinct
2593
- }));
2594
- }
2595
- if (meta.decorations) {
2596
- const decoType = deserializeAnnotatedType(meta.decorations);
2597
- if (decoType.type.kind === "object") for (const [path, prop] of decoType.type.props) {
2598
- const fieldMeta = meta.fields[path];
2599
- if (!fieldMeta?.decoration || flatMap.has(path)) continue;
2600
- if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
2601
- flatMap.set(path, prop);
2602
- columns.push(buildColumn(path, prop, fieldMeta, { options: extractFieldLiteralOptions(prop) }));
2603
- }
2604
- }
2605
- columns.sort((a, b) => a.order - b.order);
2606
- const actions = groupActions(meta.actions ?? []);
2607
- const crud = meta.crud ?? {};
2608
- const preferredId = meta.preferredId ?? meta.primaryKeys;
2609
- return {
2610
- type,
2611
- columns,
2612
- flatMap,
2613
- fetchableFields: new Set(Object.keys(meta.fields).filter((p) => isReadable(meta.fields[p]))),
2614
- primaryKeys: meta.primaryKeys,
2615
- preferredId,
2616
- identifierFields: identifierFieldsOf(preferredId, meta.actions ?? []),
2617
- versionColumn: meta.versionColumn,
2618
- crud,
2619
- canRemove: "remove" in crud,
2620
- actions,
2621
- searchable: meta.searchable,
2622
- vectorSearchable: meta.vectorSearchable,
2623
- searchIndexes: meta.searchIndexes,
2624
- relations: meta.relations
2625
- };
2626
- }
2627
- /**
2628
- * One column. A server-declared display-only column (`fieldMeta.decoration`)
2629
- * is never sortable, filterable or groupable and always nullable (a decoration
2630
- * can be absent); an ordinary one takes its capabilities from `/meta`.
2631
- */
2632
- function buildColumn(path, prop, fieldMeta, resolved) {
2633
- const { options, valueHelpInfo, distinct } = resolved;
2634
- const maxLengthMeta = getFieldMeta(prop, EXPECT_MAX_LENGTH);
2635
- const tableType = getFieldMeta(prop, UI_TABLE_TYPE);
2636
- const sharedType = getFieldMeta(prop, UI_TYPE);
2637
- const tableComponent = getFieldMeta(prop, UI_TABLE_COMPONENT);
2638
- const decoration = fieldMeta.decoration === true;
2639
- const filterOps = decoration ? void 0 : fieldMeta.filterOps;
2640
- return {
2641
- path,
2642
- label: getFieldMeta(prop, "meta.label") ?? humanizePath(path),
2643
- type: tableType ?? sharedType ?? (valueHelpInfo ? "ref" : inferDisplayType(prop, options)),
2644
- valueKind: inferValueKind(prop),
2645
- component: tableComponent,
2646
- selectWith: getFieldMeta(prop, UI_TABLE_SELECT_WITH),
2647
- sortable: !decoration && (fieldMeta.sortable ?? false),
2648
- filterable: !decoration && (fieldMeta.filterable ?? false),
2649
- ...filterOps && { filterOps: [...filterOps] },
2650
- nullable: decoration || prop.optional === true,
2651
- width: getFieldMeta(prop, UI_TABLE_WIDTH),
2652
- maxLen: maxLengthMeta?.length,
2653
- order: getFieldMeta(prop, "ui.table.order") ?? Infinity,
2654
- options,
2655
- valueHelpInfo,
2656
- ...distinct && { distinct },
2657
- ...extractMeasurement(prop)
2658
- };
2659
- }
2660
- /**
2661
- * `preferredId` ∪ every delegated action's `idMap` paths, in that order —
2662
- * the same array when no action carries an `idMap`.
2663
- */
2664
- function identifierFieldsOf(preferredId, actions) {
2665
- let out;
2666
- for (const a of actions) {
2667
- if (!a.idMap) continue;
2668
- for (const path of Object.values(a.idMap)) {
2669
- if (preferredId.includes(path) || out?.includes(path)) continue;
2670
- (out ??= [...preferredId]).push(path);
2671
- }
2672
- }
2673
- return out ?? preferredId;
2674
- }
2675
- /** A field the caller may read: listed in `meta.fields` and not write-only. */
2676
- function isReadable(field) {
2677
- return field !== void 0 && field.writeOnly !== true;
2678
- }
2679
- /** Sort by (order ?? 0). `toSorted` is stable per spec, so ties preserve declaration order. */
2680
- function byOrder(xs) {
2681
- return xs.toSorted((x, y) => (x.order ?? 0) - (y.order ?? 0));
2682
- }
2683
- /**
2684
- * Partition actions by `level`, sort each group by `(order ?? 0)` then
2685
- * declaration order, and pick the first `default: true` entry per level.
2686
- * The synthesised `__remove` UI action lives outside this set and is never
2687
- * a candidate for `default.row`.
2688
- */
2689
- function groupActions(actions) {
2690
- const table = [];
2691
- const row = [];
2692
- const rows = [];
2693
- for (const a of actions) if (a.level === "table") table.push(a);
2694
- else if (a.level === "row") row.push(a);
2695
- else if (a.level === "rows") rows.push(a);
2696
- const tableSorted = byOrder(table);
2697
- const rowSorted = byOrder(row);
2698
- const rowsSorted = byOrder(rows);
2699
- return {
2700
- table: tableSorted,
2701
- row: rowSorted,
2702
- rows: rowsSorted,
2703
- default: {
2704
- table: tableSorted.find((a) => a.default === true),
2705
- row: rowSorted.find((a) => a.default === true),
2706
- rows: rowsSorted.find((a) => a.default === true)
2707
- }
2708
- };
2709
- }
2710
- /** Infers a display type string from the annotated type's kind and designType. */
2711
- function inferDisplayType(prop, literalOpts) {
2712
- const kind = prop.type.kind;
2713
- if (kind === "array") return "array";
2714
- if (kind === "object") return "object";
2715
- if (kind === "union") return literalOpts !== void 0 ? "enum" : "union";
2716
- if (kind === "") {
2717
- const final = prop.type;
2718
- const dt = final.designType;
2719
- if (dt === "number") return final.tags?.has("timestamp") ? "datetime" : "number";
2720
- if (dt === "decimal") return "number";
2721
- if (dt === "boolean") return "boolean";
2722
- return "text";
2723
- }
2724
- return "text";
2725
- }
2726
- /**
2727
- * Number metadata that makes the server treat a plain `number` column as an
2728
- * integer (mirrors the db layer's `valueTypeOf`), beside the `int` / `expect.int` tags.
2729
- */
2730
- const INTEGER_NUMBER_META = [
2731
- "expect.int",
2732
- "db.default.increment",
2733
- "db.default.now",
2734
- "db.agg.count",
2735
- "db.agg.countDistinct"
2736
- ];
2737
- /** The kind of one scalar leaf, or `undefined` for a non-scalar / unknown design type. */
2738
- function scalarValueKind(prop) {
2739
- const final = prop.type;
2740
- const tags = final.tags;
2741
- switch (final.designType) {
2742
- case "string": return tags?.has("isoDate") ? "isoDate" : tags?.has("date") ? "date" : "string";
2743
- case "number":
2744
- if (tags?.has("timestamp")) return "timestamp";
2745
- if (tags?.has("int") || INTEGER_NUMBER_META.some((k) => prop.metadata.has(k))) return "integer";
2746
- return "number";
2747
- case "decimal": return "decimal";
2748
- case "boolean": return "boolean";
2749
- default: return;
2750
- }
2751
- }
2752
- /** Kinds of every non-null leaf of a (possibly nested) union; `null` when one is not a scalar. */
2753
- function collectUnionKinds(items, out) {
2754
- for (const item of items) {
2755
- if (item.type.kind === "union") {
2756
- collectUnionKinds(item.type.items, out);
2757
- continue;
2758
- }
2759
- if (item.type.kind === "") {
2760
- const dt = item.type.designType;
2761
- if (dt === "null" || dt === "undefined") continue;
2762
- out.add(scalarValueKind(item));
2763
- continue;
2764
- }
2765
- out.add(void 0);
2766
- }
2767
- }
2768
- /**
2769
- * Scalar storage kind of the column's value — what the server's filter guard
2770
- * checks. A scalar maps to its kind; a union that agrees on one kind across
2771
- * its non-null members (`'a' | 'b'`, `1 | 2`, `number.timestamp | null`)
2772
- * takes it; arrays, objects, JSON and mixed unions have none (`undefined`),
2773
- * which means no value coercion.
2774
- */
2775
- function inferValueKind(prop) {
2776
- const kind = prop.type.kind;
2777
- if (kind === "") return scalarValueKind(prop);
2778
- if (kind !== "union") return void 0;
2779
- const kinds = /* @__PURE__ */ new Set();
2780
- collectUnionKinds(prop.type.items, kinds);
2781
- if (kinds.size !== 1) return void 0;
2782
- return [...kinds][0];
2783
- }
2784
- //#endregion
2785
2867
  //#region src/table/value-kind.ts
2786
2868
  /** Storage kinds that hold plain numbers (a `timestamp` is epoch ms, but filters treat it as a date). */
2787
2869
  const NUMERIC_VALUE_KINDS = new Set([
@@ -2912,4 +2994,4 @@ function resolvePath(model, table, view) {
2912
2994
  return path.length > 0 ? path : void 0;
2913
2995
  }
2914
2996
  //#endregion
2915
- export { DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, EXPECT_MAX_LENGTH, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, NUMERIC_VALUE_KINDS, StaticFieldResolver, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaEntry, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setResolver, setValueHelpCacheTtl, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };
2997
+ export { DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, EXPECT_MAX_LENGTH, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, NUMERIC_VALUE_KINDS, StaticFieldResolver, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaCacheIdentity, getMetaEntry, getMetaTableDef, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, onMetaCacheReset, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setResolver, setValueHelpCacheTtl, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };