@atscript/ui 0.1.162 → 0.1.164

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 (156) hide show
  1. package/dist/client-factory.cjs +27 -0
  2. package/dist/client-factory.d.cts +53 -0
  3. package/dist/client-factory.d.mts +53 -0
  4. package/dist/client-factory.mjs +25 -0
  5. package/dist/form/apply.cjs +38 -0
  6. package/dist/form/apply.d.cts +36 -0
  7. package/dist/form/apply.d.mts +36 -0
  8. package/dist/form/apply.mjs +38 -0
  9. package/dist/form/clone.cjs +30 -0
  10. package/dist/form/clone.d.cts +23 -0
  11. package/dist/form/clone.d.mts +23 -0
  12. package/dist/form/clone.mjs +30 -0
  13. package/dist/form/create-form-def.cjs +440 -0
  14. package/dist/form/create-form-def.d.cts +67 -0
  15. package/dist/form/create-form-def.d.mts +67 -0
  16. package/dist/form/create-form-def.mjs +438 -0
  17. package/dist/form/decimal-format.cjs +324 -0
  18. package/dist/form/decimal-format.d.cts +86 -0
  19. package/dist/form/decimal-format.d.mts +86 -0
  20. package/dist/form/decimal-format.mjs +315 -0
  21. package/dist/form/diff.cjs +458 -0
  22. package/dist/form/diff.d.cts +80 -0
  23. package/dist/form/diff.d.mts +80 -0
  24. package/dist/form/diff.mjs +457 -0
  25. package/dist/form/dirty.cjs +65 -0
  26. package/dist/form/dirty.d.cts +47 -0
  27. package/dist/form/dirty.d.mts +47 -0
  28. package/dist/form/dirty.mjs +64 -0
  29. package/dist/form/error-utils.cjs +97 -0
  30. package/dist/form/error-utils.d.cts +58 -0
  31. package/dist/form/error-utils.d.mts +58 -0
  32. package/dist/form/error-utils.mjs +92 -0
  33. package/dist/form/form-actions.cjs +30 -0
  34. package/dist/form/form-actions.d.cts +17 -0
  35. package/dist/form/form-actions.d.mts +17 -0
  36. package/dist/form/form-actions.mjs +30 -0
  37. package/dist/form/grid.cjs +69 -0
  38. package/dist/form/grid.d.cts +49 -0
  39. package/dist/form/grid.d.mts +49 -0
  40. package/dist/form/grid.mjs +64 -0
  41. package/dist/form/labels.cjs +10 -0
  42. package/dist/form/labels.d.cts +7 -0
  43. package/dist/form/labels.d.mts +7 -0
  44. package/dist/form/labels.mjs +10 -0
  45. package/dist/form/measurement.cjs +20 -0
  46. package/dist/form/measurement.d.cts +29 -0
  47. package/dist/form/measurement.d.mts +29 -0
  48. package/dist/form/measurement.mjs +20 -0
  49. package/dist/form/path-utils.cjs +182 -0
  50. package/dist/form/path-utils.d.cts +47 -0
  51. package/dist/form/path-utils.d.mts +47 -0
  52. package/dist/form/path-utils.mjs +175 -0
  53. package/dist/form/rebase.cjs +89 -0
  54. package/dist/form/rebase.d.cts +61 -0
  55. package/dist/form/rebase.d.mts +61 -0
  56. package/dist/form/rebase.mjs +89 -0
  57. package/dist/form/skipped-nav.cjs +100 -0
  58. package/dist/form/skipped-nav.d.cts +13 -0
  59. package/dist/form/skipped-nav.d.mts +13 -0
  60. package/dist/form/skipped-nav.mjs +98 -0
  61. package/dist/form/types.cjs +40 -0
  62. package/dist/form/types.d.cts +133 -0
  63. package/dist/form/types.d.mts +133 -0
  64. package/dist/form/types.mjs +36 -0
  65. package/dist/form/union-detect.cjs +46 -0
  66. package/dist/form/union-detect.d.cts +22 -0
  67. package/dist/form/union-detect.d.mts +22 -0
  68. package/dist/form/union-detect.mjs +46 -0
  69. package/dist/form/validate.cjs +150 -0
  70. package/dist/form/validate.d.cts +50 -0
  71. package/dist/form/validate.d.mts +50 -0
  72. package/dist/form/validate.mjs +147 -0
  73. package/dist/index.cjs +217 -3360
  74. package/dist/index.d.cts +38 -1693
  75. package/dist/index.d.mts +38 -1693
  76. package/dist/index.mjs +35 -3179
  77. package/dist/nav/model-routes.cjs +59 -0
  78. package/dist/nav/model-routes.d.cts +33 -0
  79. package/dist/nav/model-routes.d.mts +33 -0
  80. package/dist/nav/model-routes.mjs +59 -0
  81. package/dist/plugin/annotations.cjs +577 -0
  82. package/dist/plugin/annotations.mjs +577 -0
  83. package/dist/plugin/primitives.cjs +30 -0
  84. package/dist/plugin/primitives.mjs +30 -0
  85. package/dist/plugin/value-help-validation.cjs +419 -0
  86. package/dist/plugin/value-help-validation.mjs +413 -0
  87. package/dist/plugin.cjs +4 -1001
  88. package/dist/plugin.mjs +2 -999
  89. package/dist/shared/annotation-keys.cjs +189 -0
  90. package/dist/shared/annotation-keys.d.cts +82 -0
  91. package/dist/shared/annotation-keys.d.mts +82 -0
  92. package/dist/shared/annotation-keys.mjs +97 -0
  93. package/dist/shared/field-resolver.cjs +123 -0
  94. package/dist/shared/field-resolver.d.cts +77 -0
  95. package/dist/shared/field-resolver.d.mts +77 -0
  96. package/dist/shared/field-resolver.mjs +110 -0
  97. package/dist/shared/meta-cache.cjs +244 -0
  98. package/dist/shared/meta-cache.d.cts +110 -0
  99. package/dist/shared/meta-cache.d.mts +110 -0
  100. package/dist/shared/meta-cache.mjs +237 -0
  101. package/dist/shared/str.cjs +19 -0
  102. package/dist/shared/str.d.cts +7 -0
  103. package/dist/shared/str.d.mts +7 -0
  104. package/dist/shared/str.mjs +17 -0
  105. package/dist/table/column-resolver.cjs +17 -0
  106. package/dist/table/column-resolver.d.cts +11 -0
  107. package/dist/table/column-resolver.d.mts +11 -0
  108. package/dist/table/column-resolver.mjs +15 -0
  109. package/dist/table/create-table-def.cjs +233 -0
  110. package/dist/table/create-table-def.d.cts +15 -0
  111. package/dist/table/create-table-def.d.mts +15 -0
  112. package/dist/table/create-table-def.mjs +233 -0
  113. package/dist/table/navigate-href.cjs +45 -0
  114. package/dist/table/navigate-href.d.cts +31 -0
  115. package/dist/table/navigate-href.d.mts +31 -0
  116. package/dist/table/navigate-href.mjs +45 -0
  117. package/dist/table/types.d.cts +287 -0
  118. package/dist/table/types.d.mts +287 -0
  119. package/dist/table/value-kind.cjs +20 -0
  120. package/dist/table/value-kind.d.cts +15 -0
  121. package/dist/table/value-kind.d.mts +15 -0
  122. package/dist/table/value-kind.mjs +19 -0
  123. package/dist/value-help/dict-paths.cjs +17 -0
  124. package/dist/value-help/dict-paths.d.cts +11 -0
  125. package/dist/value-help/dict-paths.d.mts +11 -0
  126. package/dist/value-help/dict-paths.mjs +17 -0
  127. package/dist/value-help/distinct-client.cjs +51 -0
  128. package/dist/value-help/distinct-client.d.cts +40 -0
  129. package/dist/value-help/distinct-client.d.mts +40 -0
  130. package/dist/value-help/distinct-client.mjs +50 -0
  131. package/dist/value-help/extract-literals.cjs +76 -0
  132. package/dist/value-help/extract-literals.d.cts +32 -0
  133. package/dist/value-help/extract-literals.d.mts +32 -0
  134. package/dist/value-help/extract-literals.mjs +74 -0
  135. package/dist/value-help/extract-ref.cjs +100 -0
  136. package/dist/value-help/extract-ref.d.cts +37 -0
  137. package/dist/value-help/extract-ref.d.mts +37 -0
  138. package/dist/value-help/extract-ref.mjs +100 -0
  139. package/dist/value-help/filter-tree.cjs +45 -0
  140. package/dist/value-help/filter-tree.mjs +45 -0
  141. package/dist/value-help/index.d.mts +8 -0
  142. package/dist/value-help/resolve-options.cjs +64 -0
  143. package/dist/value-help/resolve-options.d.cts +35 -0
  144. package/dist/value-help/resolve-options.d.mts +35 -0
  145. package/dist/value-help/resolve-options.mjs +60 -0
  146. package/dist/value-help/resolve.cjs +62 -0
  147. package/dist/value-help/resolve.d.cts +31 -0
  148. package/dist/value-help/resolve.d.mts +31 -0
  149. package/dist/value-help/resolve.mjs +61 -0
  150. package/dist/value-help/types.d.cts +36 -0
  151. package/dist/value-help/types.d.mts +36 -0
  152. package/dist/value-help/value-help-client.cjs +136 -0
  153. package/dist/value-help/value-help-client.d.cts +67 -0
  154. package/dist/value-help/value-help-client.d.mts +67 -0
  155. package/dist/value-help/value-help-client.mjs +134 -0
  156. package/package.json +10 -10
@@ -0,0 +1,237 @@
1
+ import { invalidateValueHelpCache } from "../value-help/value-help-client.mjs";
2
+ import { getDefaultClientFactory } from "../client-factory.mjs";
3
+ import { createTableDef } from "../table/create-table-def.mjs";
4
+ import { deserializeAnnotatedType } from "@atscript/typescript/utils";
5
+ import { clearMetaStore, defaultMetaStore } from "@atscript/db-client";
6
+ //#region src/shared/meta-cache.ts
7
+ /**
8
+ * Enough for every URL a page touches — a table, the dictionaries its
9
+ * filters and forms pick from — plus the recent navigation history, so going
10
+ * back is instant; small enough to cap a long session at a few MB of parsed
11
+ * `/meta`. Twice the `@atscript/db-client` `MetaStore` body limit, since
12
+ * parametric URLs share bodies.
13
+ */
14
+ const DEFAULT_MAX_ENTRIES = 100;
15
+ let maxEntries = DEFAULT_MAX_ENTRIES;
16
+ /** Per-URL entries, least recently used first. Browser only. */
17
+ const cache = /* @__PURE__ */ new Map();
18
+ const slots = /* @__PURE__ */ new WeakMap();
19
+ /** Derived shapes per `ETag`, counted by the cached entries that use them. Browser only. */
20
+ const derivedByEtag = /* @__PURE__ */ new Map();
21
+ /** Custom `/meta` stores of cached clients, counted by the entries that use them. */
22
+ const customStores = /* @__PURE__ */ new Map();
23
+ /** `undefined` until the first `setMetaCacheIdentity` call; `null` = anonymous. */
24
+ let identity;
25
+ const resetListeners = /* @__PURE__ */ new Set();
26
+ /**
27
+ * Get or create the cache entry for `url`. First caller's `factory` (and
28
+ * `options.metaKey`) seeds the `Client`; subsequent callers reuse it. On
29
+ * `meta` rejection, the entry is evicted so the next call retries. A hit
30
+ * marks the URL most recently used; hold an entry you keep using with
31
+ * {@link retainMetaEntry}. Without a browser `window` nothing is cached and
32
+ * the client is asked for `metaStore: false`.
33
+ */
34
+ function getMetaEntry(url, factory, options) {
35
+ const browser = typeof window !== "undefined";
36
+ const existing = browser ? cache.get(url) : void 0;
37
+ if (existing) {
38
+ touch(url, existing);
39
+ return existing;
40
+ }
41
+ const f = factory ?? getDefaultClientFactory();
42
+ let client;
43
+ if (!browser) client = f(url, { metaStore: false });
44
+ else if (options?.metaKey) client = f(url, { metaKey: options.metaKey });
45
+ else client = f(url);
46
+ const meta = client.meta().catch((err) => {
47
+ if (cache.get(url) === entry) evict(url, entry);
48
+ throw err;
49
+ });
50
+ const derived = meta.then((m) => derive(entry, client, m));
51
+ const type = derived.then((d) => d.type);
52
+ type.catch(() => {});
53
+ const entry = {
54
+ client,
55
+ meta,
56
+ type
57
+ };
58
+ const slot = {
59
+ url,
60
+ derived,
61
+ holds: 0
62
+ };
63
+ slots.set(entry, slot);
64
+ if (browser) {
65
+ slot.store = customStoreOf(client);
66
+ if (slot.store) customStores.set(slot.store, (customStores.get(slot.store) ?? 0) + 1);
67
+ cache.set(url, entry);
68
+ trim(entry);
69
+ }
70
+ return entry;
71
+ }
72
+ /**
73
+ * Keep `entry` in the cache while it is in use: a held entry is never
74
+ * evicted by the size limit ({@link setMetaCacheMaxEntries}), so later
75
+ * `getMetaEntry` / `resolveValueHelp` calls for its URL keep returning it.
76
+ * Call the returned function (idempotent) once done — `useTable` and the
77
+ * form value-help do this for their component's lifetime. A reset still
78
+ * drops held entries. Since 0.1.154.
79
+ */
80
+ function retainMetaEntry(entry) {
81
+ const slot = slots.get(entry);
82
+ if (!slot) return () => {};
83
+ slot.holds++;
84
+ let released = false;
85
+ return () => {
86
+ if (released) return;
87
+ released = true;
88
+ slot.holds--;
89
+ if (slot.holds === 0 && cache.get(slot.url) === entry) {
90
+ touch(slot.url, entry);
91
+ trim();
92
+ }
93
+ };
94
+ }
95
+ /**
96
+ * How many URLs the meta cache keeps (default `100`). Least recently used
97
+ * entries beyond it are dropped — entries held with {@link retainMetaEntry}
98
+ * (every mounted table and form value-help) never are, and may exceed it.
99
+ * At least `1`; `Infinity` turns the limit off; no argument restores the
100
+ * default. Since 0.1.154.
101
+ */
102
+ function setMetaCacheMaxEntries(max) {
103
+ maxEntries = max === void 0 ? DEFAULT_MAX_ENTRIES : max >= 1 ? max : 1;
104
+ trim();
105
+ }
106
+ function touch(url, entry) {
107
+ cache.delete(url);
108
+ cache.set(url, entry);
109
+ }
110
+ /**
111
+ * Drop least recently used entries nothing holds until the cache fits.
112
+ * `spare` — the entry just handed out, about to be retained by its caller.
113
+ */
114
+ function trim(spare) {
115
+ if (cache.size <= maxEntries) return;
116
+ for (const [url, entry] of cache) {
117
+ if (entry !== spare && slots.get(entry).holds === 0) evict(url, entry);
118
+ if (cache.size <= maxEntries) return;
119
+ }
120
+ }
121
+ /**
122
+ * Remove `entry` and release what only it kept: its shared `Derived` and
123
+ * custom store. A reset no longer reaches its client, so the client's memoized
124
+ * `/meta` goes now — a factory that reuses clients per URL would otherwise
125
+ * hand it to the next viewer.
126
+ */
127
+ function evict(url, entry) {
128
+ cache.delete(url);
129
+ entry.client.invalidateMeta?.();
130
+ const slot = slots.get(entry);
131
+ if (slot.etag !== void 0 && --derivedByEtag.get(slot.etag).refs === 0) derivedByEtag.delete(slot.etag);
132
+ if (slot.store) {
133
+ const refs = customStores.get(slot.store);
134
+ if (refs > 1) customStores.set(slot.store, refs - 1);
135
+ else {
136
+ slot.store.clear();
137
+ customStores.delete(slot.store);
138
+ }
139
+ }
140
+ }
141
+ /**
142
+ * The `TableDef` for a cache entry, built once per entry — and once per
143
+ * `/meta` `ETag` across entries. Since 0.1.153.
144
+ */
145
+ function getMetaTableDef(entry) {
146
+ if (!entry.tableDef) {
147
+ const derived = slots.get(entry)?.derived;
148
+ 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));
149
+ }
150
+ return entry.tableDef;
151
+ }
152
+ /**
153
+ * Shares the `Derived` of one `ETag` among the cached entries that loaded it;
154
+ * an entry no longer cached (evicted, reset, server render) keeps its own.
155
+ */
156
+ function derive(entry, client, meta) {
157
+ const slot = slots.get(entry);
158
+ const etag = cache.get(slot.url) === entry ? client.metaEtag?.() : void 0;
159
+ if (etag === void 0) return { type: deserializeAnnotatedType(meta.type) };
160
+ let shared = derivedByEtag.get(etag);
161
+ if (shared) shared.refs++;
162
+ else {
163
+ shared = {
164
+ derived: { type: deserializeAnnotatedType(meta.type) },
165
+ refs: 1
166
+ };
167
+ derivedByEtag.set(etag, shared);
168
+ }
169
+ slot.etag = etag;
170
+ return shared.derived;
171
+ }
172
+ /**
173
+ * The custom `/meta` store a factory gave `client`, so a reset (and the
174
+ * eviction of its last cached client) can clear it. The shared
175
+ * `defaultMetaStore` is skipped: a reset clears it through
176
+ * `clearMetaStore()`, and an eviction must not drop the ETags of every
177
+ * other URL. A store-less client (`metaStore: false`) is skipped too.
178
+ */
179
+ function customStoreOf(client) {
180
+ const store = client.metaStore;
181
+ return store && store !== defaultMetaStore ? store : void 0;
182
+ }
183
+ /**
184
+ * Drop every cached `/meta` — including the copy each cached `Client`
185
+ * memoizes and the `@atscript/db-client` meta stores used to revalidate it
186
+ * (the shared default one and any custom one a factory supplied) — the
187
+ * value-help searches shared under them, and everything registered through
188
+ * {@link onMetaCacheReset} (e.g. the table-presets cache). Entries already
189
+ * handed out keep working; the next `getMetaEntry` refetches.
190
+ */
191
+ function resetMetaCache() {
192
+ const entries = [...cache.values()];
193
+ cache.clear();
194
+ derivedByEtag.clear();
195
+ for (const entry of entries) entry.client.invalidateMeta?.();
196
+ clearMetaStore();
197
+ for (const store of customStores.keys()) store.clear();
198
+ customStores.clear();
199
+ invalidateValueHelpCache();
200
+ for (const listener of resetListeners) listener();
201
+ }
202
+ /**
203
+ * Bind the meta cache to the current viewer. Call it whenever the signed-in
204
+ * user or their role may have changed — after login, after logout and on
205
+ * every reload of the current user. A key that differs from the previous
206
+ * one resets the cache (`resetMetaCache`); the same key keeps it. `null` /
207
+ * `undefined` = anonymous.
208
+ *
209
+ * Binding an identity also turns on caches that are only safe when the app
210
+ * reports sign-in changes, such as the table-presets cache.
211
+ */
212
+ function setMetaCacheIdentity(key) {
213
+ const next = key ?? null;
214
+ if (next === identity) return;
215
+ identity = next;
216
+ resetMetaCache();
217
+ }
218
+ /**
219
+ * The identity last passed to {@link setMetaCacheIdentity}: `undefined` when
220
+ * the app never bound one, `null` for anonymous. Since 0.1.153.
221
+ */
222
+ function getMetaCacheIdentity() {
223
+ return identity;
224
+ }
225
+ /**
226
+ * Run `listener` on every {@link resetMetaCache} (and so on every identity
227
+ * change). For caches that belong to the signed-in viewer. Returns an
228
+ * unsubscribe function. Since 0.1.153.
229
+ */
230
+ function onMetaCacheReset(listener) {
231
+ resetListeners.add(listener);
232
+ return () => {
233
+ resetListeners.delete(listener);
234
+ };
235
+ }
236
+ //#endregion
237
+ export { getMetaCacheIdentity, getMetaEntry, getMetaTableDef, onMetaCacheReset, resetMetaCache, retainMetaEntry, setMetaCacheIdentity, setMetaCacheMaxEntries };
@@ -0,0 +1,19 @@
1
+ //#region src/shared/str.ts
2
+ /** Converts a dot-path to a human-readable label (e.g. 'firstName' → 'First Name'). */
3
+ function humanizePath(path) {
4
+ return path.slice(path.lastIndexOf(".") + 1).replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, (s) => s.toUpperCase());
5
+ }
6
+ /** Escape special regex characters in user input for safe embedding in a `$regex` filter. */
7
+ function escapeRegex(input) {
8
+ return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9
+ }
10
+ /** Safely convert an unknown value to a string without triggering no-base-to-string lint errors. */
11
+ function str(value) {
12
+ if (typeof value === "string") return value;
13
+ if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return `${value}`;
14
+ return JSON.stringify(value) ?? "";
15
+ }
16
+ //#endregion
17
+ exports.escapeRegex = escapeRegex;
18
+ exports.humanizePath = humanizePath;
19
+ exports.str = str;
@@ -0,0 +1,7 @@
1
+ //#region src/shared/str.d.ts
2
+ /** Escape special regex characters in user input for safe embedding in a `$regex` filter. */
3
+ declare function escapeRegex(input: string): string;
4
+ /** Safely convert an unknown value to a string without triggering no-base-to-string lint errors. */
5
+ declare function str(value: unknown): string;
6
+ //#endregion
7
+ export { escapeRegex, str };
@@ -0,0 +1,7 @@
1
+ //#region src/shared/str.d.ts
2
+ /** Escape special regex characters in user input for safe embedding in a `$regex` filter. */
3
+ declare function escapeRegex(input: string): string;
4
+ /** Safely convert an unknown value to a string without triggering no-base-to-string lint errors. */
5
+ declare function str(value: unknown): string;
6
+ //#endregion
7
+ export { escapeRegex, str };
@@ -0,0 +1,17 @@
1
+ //#region src/shared/str.ts
2
+ /** Converts a dot-path to a human-readable label (e.g. 'firstName' → 'First Name'). */
3
+ function humanizePath(path) {
4
+ return path.slice(path.lastIndexOf(".") + 1).replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, (s) => s.toUpperCase());
5
+ }
6
+ /** Escape special regex characters in user input for safe embedding in a `$regex` filter. */
7
+ function escapeRegex(input) {
8
+ return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9
+ }
10
+ /** Safely convert an unknown value to a string without triggering no-base-to-string lint errors. */
11
+ function str(value) {
12
+ if (typeof value === "string") return value;
13
+ if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return `${value}`;
14
+ return JSON.stringify(value) ?? "";
15
+ }
16
+ //#endregion
17
+ export { escapeRegex, humanizePath, str };
@@ -0,0 +1,17 @@
1
+ //#region src/table/column-resolver.ts
2
+ /** Get sortable columns. */
3
+ function getSortableColumns(def) {
4
+ return def.columns.filter((c) => c.sortable);
5
+ }
6
+ /** Get filterable columns. */
7
+ function getFilterableColumns(def) {
8
+ return def.columns.filter((c) => c.filterable);
9
+ }
10
+ /** Find a column by path. */
11
+ function getColumn(def, path) {
12
+ return def.columns.find((c) => c.path === path);
13
+ }
14
+ //#endregion
15
+ exports.getColumn = getColumn;
16
+ exports.getFilterableColumns = getFilterableColumns;
17
+ exports.getSortableColumns = getSortableColumns;
@@ -0,0 +1,11 @@
1
+ import { ColumnDef, TableDef } from "./types.cjs";
2
+
3
+ //#region src/table/column-resolver.d.ts
4
+ /** Get sortable columns. */
5
+ declare function getSortableColumns(def: TableDef): ColumnDef[];
6
+ /** Get filterable columns. */
7
+ declare function getFilterableColumns(def: TableDef): ColumnDef[];
8
+ /** Find a column by path. */
9
+ declare function getColumn(def: TableDef, path: string): ColumnDef | undefined;
10
+ //#endregion
11
+ export { getColumn, getFilterableColumns, getSortableColumns };
@@ -0,0 +1,11 @@
1
+ import { ColumnDef, TableDef } from "./types.mjs";
2
+
3
+ //#region src/table/column-resolver.d.ts
4
+ /** Get sortable columns. */
5
+ declare function getSortableColumns(def: TableDef): ColumnDef[];
6
+ /** Get filterable columns. */
7
+ declare function getFilterableColumns(def: TableDef): ColumnDef[];
8
+ /** Find a column by path. */
9
+ declare function getColumn(def: TableDef, path: string): ColumnDef | undefined;
10
+ //#endregion
11
+ export { getColumn, getFilterableColumns, getSortableColumns };
@@ -0,0 +1,15 @@
1
+ //#region src/table/column-resolver.ts
2
+ /** Get sortable columns. */
3
+ function getSortableColumns(def) {
4
+ return def.columns.filter((c) => c.sortable);
5
+ }
6
+ /** Get filterable columns. */
7
+ function getFilterableColumns(def) {
8
+ return def.columns.filter((c) => c.filterable);
9
+ }
10
+ /** Find a column by path. */
11
+ function getColumn(def, path) {
12
+ return def.columns.find((c) => c.path === path);
13
+ }
14
+ //#endregion
15
+ export { getColumn, getFilterableColumns, getSortableColumns };
@@ -0,0 +1,233 @@
1
+ const require_annotation_keys = require("../shared/annotation-keys.cjs");
2
+ const require_field_resolver = require("../shared/field-resolver.cjs");
3
+ const require_extract_literals = require("../value-help/extract-literals.cjs");
4
+ const require_extract_ref = require("../value-help/extract-ref.cjs");
5
+ const require_str = require("../shared/str.cjs");
6
+ const require_measurement = require("../form/measurement.cjs");
7
+ let _atscript_typescript_utils = require("@atscript/typescript/utils");
8
+ //#region src/table/create-table-def.ts
9
+ /**
10
+ * Builds a TableDef from a moost-db MetaResponse.
11
+ *
12
+ * 1. Deserializes `meta.type` into a live TAtscriptAnnotatedType
13
+ * 2. Flattens to discover all field paths
14
+ * 3. Builds ColumnDef per field using annotations + meta.fields capabilities
15
+ * 4. Sorts by @ui.table.order
16
+ */
17
+ function createTableDef(meta, preDeserializedType) {
18
+ const type = preDeserializedType ?? (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.type);
19
+ const flatMap = type.type.kind === "object" ? (0, _atscript_typescript_utils.flattenAnnotatedType)(type, { excludePhantomTypes: true }) : /* @__PURE__ */ new Map();
20
+ const columns = [];
21
+ for (const [path, prop] of flatMap.entries()) {
22
+ if (path === "") continue;
23
+ if (path === meta.versionColumn) continue;
24
+ const fieldMeta = meta.fields[path];
25
+ if (!isReadable(fieldMeta)) continue;
26
+ if (require_field_resolver.getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
27
+ const options = require_extract_literals.extractFieldLiteralOptions(prop);
28
+ const valueHelpInfo = require_extract_ref.extractValueHelp(prop);
29
+ let distinct;
30
+ if (!valueHelpInfo && !options && fieldMeta.groupable && fieldMeta.filterable) {
31
+ const url = type.metadata.get(require_annotation_keys.DB_HTTP_PATH);
32
+ if (url && require_field_resolver.getFieldMeta(prop, "ui.valueHelp.distinct") !== void 0) distinct = {
33
+ url,
34
+ field: path
35
+ };
36
+ }
37
+ columns.push(buildColumn(path, prop, fieldMeta, {
38
+ options,
39
+ valueHelpInfo,
40
+ distinct
41
+ }));
42
+ }
43
+ if (meta.decorations) {
44
+ const decoType = (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.decorations);
45
+ if (decoType.type.kind === "object") for (const [path, prop] of decoType.type.props) {
46
+ const fieldMeta = meta.fields[path];
47
+ if (!fieldMeta?.decoration || flatMap.has(path)) continue;
48
+ if (require_field_resolver.getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
49
+ flatMap.set(path, prop);
50
+ columns.push(buildColumn(path, prop, fieldMeta, { options: require_extract_literals.extractFieldLiteralOptions(prop) }));
51
+ }
52
+ }
53
+ columns.sort((a, b) => a.order - b.order);
54
+ const actions = groupActions(meta.actions ?? []);
55
+ const crud = meta.crud ?? {};
56
+ const preferredId = meta.preferredId ?? meta.primaryKeys;
57
+ return {
58
+ type,
59
+ columns,
60
+ flatMap,
61
+ fetchableFields: new Set(Object.keys(meta.fields).filter((p) => isReadable(meta.fields[p]))),
62
+ primaryKeys: meta.primaryKeys,
63
+ preferredId,
64
+ identifierFields: identifierFieldsOf(preferredId, meta.actions ?? []),
65
+ versionColumn: meta.versionColumn,
66
+ crud,
67
+ canRemove: "remove" in crud,
68
+ actions,
69
+ searchable: meta.searchable,
70
+ vectorSearchable: meta.vectorSearchable,
71
+ searchIndexes: meta.searchIndexes,
72
+ relations: meta.relations
73
+ };
74
+ }
75
+ /**
76
+ * One column. A server-declared display-only column (`fieldMeta.decoration`)
77
+ * is never sortable, filterable or groupable and always nullable (a decoration
78
+ * can be absent); an ordinary one takes its capabilities from `/meta`.
79
+ */
80
+ function buildColumn(path, prop, fieldMeta, resolved) {
81
+ const { options, valueHelpInfo, distinct } = resolved;
82
+ const maxLengthMeta = require_field_resolver.getFieldMeta(prop, require_annotation_keys.EXPECT_MAX_LENGTH);
83
+ const tableType = require_field_resolver.getFieldMeta(prop, require_annotation_keys.UI_TABLE_TYPE);
84
+ const sharedType = require_field_resolver.getFieldMeta(prop, require_annotation_keys.UI_TYPE);
85
+ const tableComponent = require_field_resolver.getFieldMeta(prop, require_annotation_keys.UI_TABLE_COMPONENT);
86
+ const decoration = fieldMeta.decoration === true;
87
+ const filterOps = decoration ? void 0 : fieldMeta.filterOps;
88
+ return {
89
+ path,
90
+ label: require_field_resolver.getFieldMeta(prop, "meta.label") ?? require_str.humanizePath(path),
91
+ type: tableType ?? sharedType ?? (valueHelpInfo ? "ref" : inferDisplayType(prop, options)),
92
+ valueKind: inferValueKind(prop),
93
+ component: tableComponent,
94
+ selectWith: require_field_resolver.getFieldMeta(prop, require_annotation_keys.UI_TABLE_SELECT_WITH),
95
+ sortable: !decoration && (fieldMeta.sortable ?? false),
96
+ filterable: !decoration && (fieldMeta.filterable ?? false),
97
+ ...filterOps && { filterOps: [...filterOps] },
98
+ nullable: decoration || prop.optional === true,
99
+ width: require_field_resolver.getFieldMeta(prop, require_annotation_keys.UI_TABLE_WIDTH),
100
+ maxLen: maxLengthMeta?.length,
101
+ order: require_field_resolver.getFieldMeta(prop, "ui.table.order") ?? Infinity,
102
+ options,
103
+ valueHelpInfo,
104
+ ...distinct && { distinct },
105
+ ...require_measurement.extractMeasurement(prop)
106
+ };
107
+ }
108
+ /**
109
+ * `preferredId` ∪ every delegated action's `idMap` paths, in that order —
110
+ * the same array when no action carries an `idMap`.
111
+ */
112
+ function identifierFieldsOf(preferredId, actions) {
113
+ let out;
114
+ for (const a of actions) {
115
+ if (!a.idMap) continue;
116
+ for (const path of Object.values(a.idMap)) {
117
+ if (preferredId.includes(path) || out?.includes(path)) continue;
118
+ (out ??= [...preferredId]).push(path);
119
+ }
120
+ }
121
+ return out ?? preferredId;
122
+ }
123
+ /** A field the caller may read: listed in `meta.fields` and not write-only. */
124
+ function isReadable(field) {
125
+ return field !== void 0 && field.writeOnly !== true;
126
+ }
127
+ /** Sort by (order ?? 0). `toSorted` is stable per spec, so ties preserve declaration order. */
128
+ function byOrder(xs) {
129
+ return xs.toSorted((x, y) => (x.order ?? 0) - (y.order ?? 0));
130
+ }
131
+ /**
132
+ * Partition actions by `level`, sort each group by `(order ?? 0)` then
133
+ * declaration order, and pick the first `default: true` entry per level.
134
+ * The synthesised `__remove` UI action lives outside this set and is never
135
+ * a candidate for `default.row`.
136
+ */
137
+ function groupActions(actions) {
138
+ const table = [];
139
+ const row = [];
140
+ const rows = [];
141
+ for (const a of actions) if (a.level === "table") table.push(a);
142
+ else if (a.level === "row") row.push(a);
143
+ else if (a.level === "rows") rows.push(a);
144
+ const tableSorted = byOrder(table);
145
+ const rowSorted = byOrder(row);
146
+ const rowsSorted = byOrder(rows);
147
+ return {
148
+ table: tableSorted,
149
+ row: rowSorted,
150
+ rows: rowsSorted,
151
+ default: {
152
+ table: tableSorted.find((a) => a.default === true),
153
+ row: rowSorted.find((a) => a.default === true),
154
+ rows: rowsSorted.find((a) => a.default === true)
155
+ }
156
+ };
157
+ }
158
+ /** Infers a display type string from the annotated type's kind and designType. */
159
+ function inferDisplayType(prop, literalOpts) {
160
+ const kind = prop.type.kind;
161
+ if (kind === "array") return "array";
162
+ if (kind === "object") return "object";
163
+ if (kind === "union") return literalOpts !== void 0 ? "enum" : "union";
164
+ if (kind === "") {
165
+ const final = prop.type;
166
+ const dt = final.designType;
167
+ if (dt === "number") return final.tags?.has("timestamp") ? "datetime" : "number";
168
+ if (dt === "decimal") return "number";
169
+ if (dt === "boolean") return "boolean";
170
+ return "text";
171
+ }
172
+ return "text";
173
+ }
174
+ /**
175
+ * Number metadata that makes the server treat a plain `number` column as an
176
+ * integer (mirrors the db layer's `valueTypeOf`), beside the `int` / `expect.int` tags.
177
+ */
178
+ const INTEGER_NUMBER_META = [
179
+ "expect.int",
180
+ "db.default.increment",
181
+ "db.default.now",
182
+ "db.agg.count",
183
+ "db.agg.countDistinct"
184
+ ];
185
+ /** The kind of one scalar leaf, or `undefined` for a non-scalar / unknown design type. */
186
+ function scalarValueKind(prop) {
187
+ const final = prop.type;
188
+ const tags = final.tags;
189
+ switch (final.designType) {
190
+ case "string": return tags?.has("isoDate") ? "isoDate" : tags?.has("date") ? "date" : "string";
191
+ case "number":
192
+ if (tags?.has("timestamp")) return "timestamp";
193
+ if (tags?.has("int") || INTEGER_NUMBER_META.some((k) => prop.metadata.has(k))) return "integer";
194
+ return "number";
195
+ case "decimal": return "decimal";
196
+ case "boolean": return "boolean";
197
+ default: return;
198
+ }
199
+ }
200
+ /** Kinds of every non-null leaf of a (possibly nested) union; `null` when one is not a scalar. */
201
+ function collectUnionKinds(items, out) {
202
+ for (const item of items) {
203
+ if (item.type.kind === "union") {
204
+ collectUnionKinds(item.type.items, out);
205
+ continue;
206
+ }
207
+ if (item.type.kind === "") {
208
+ const dt = item.type.designType;
209
+ if (dt === "null" || dt === "undefined") continue;
210
+ out.add(scalarValueKind(item));
211
+ continue;
212
+ }
213
+ out.add(void 0);
214
+ }
215
+ }
216
+ /**
217
+ * Scalar storage kind of the column's value — what the server's filter guard
218
+ * checks. A scalar maps to its kind; a union that agrees on one kind across
219
+ * its non-null members (`'a' | 'b'`, `1 | 2`, `number.timestamp | null`)
220
+ * takes it; arrays, objects, JSON and mixed unions have none (`undefined`),
221
+ * which means no value coercion.
222
+ */
223
+ function inferValueKind(prop) {
224
+ const kind = prop.type.kind;
225
+ if (kind === "") return scalarValueKind(prop);
226
+ if (kind !== "union") return void 0;
227
+ const kinds = /* @__PURE__ */ new Set();
228
+ collectUnionKinds(prop.type.items, kinds);
229
+ if (kinds.size !== 1) return void 0;
230
+ return [...kinds][0];
231
+ }
232
+ //#endregion
233
+ exports.createTableDef = createTableDef;
@@ -0,0 +1,15 @@
1
+ import { MetaResponse, TableDef } from "./types.cjs";
2
+ import { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
3
+
4
+ //#region src/table/create-table-def.d.ts
5
+ /**
6
+ * Builds a TableDef from a moost-db MetaResponse.
7
+ *
8
+ * 1. Deserializes `meta.type` into a live TAtscriptAnnotatedType
9
+ * 2. Flattens to discover all field paths
10
+ * 3. Builds ColumnDef per field using annotations + meta.fields capabilities
11
+ * 4. Sorts by @ui.table.order
12
+ */
13
+ declare function createTableDef(meta: MetaResponse, preDeserializedType?: TAtscriptAnnotatedType): TableDef;
14
+ //#endregion
15
+ export { createTableDef };
@@ -0,0 +1,15 @@
1
+ import { MetaResponse, TableDef } from "./types.mjs";
2
+ import { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
3
+
4
+ //#region src/table/create-table-def.d.ts
5
+ /**
6
+ * Builds a TableDef from a moost-db MetaResponse.
7
+ *
8
+ * 1. Deserializes `meta.type` into a live TAtscriptAnnotatedType
9
+ * 2. Flattens to discover all field paths
10
+ * 3. Builds ColumnDef per field using annotations + meta.fields capabilities
11
+ * 4. Sorts by @ui.table.order
12
+ */
13
+ declare function createTableDef(meta: MetaResponse, preDeserializedType?: TAtscriptAnnotatedType): TableDef;
14
+ //#endregion
15
+ export { createTableDef };