@happyvertical/smrt-core 0.38.5 → 0.38.7

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.
@@ -35,11 +35,27 @@ export interface WebCollectionEntry {
35
35
  * Select the manifest entries that become web collection definitions: one per
36
36
  * REST collection, STI children folding into their base model, collection
37
37
  * classes excluded, and only models that expose `list` (a read surface is
38
- * required to materialize a collection). Uses the canonical
39
- * {@link resolveApiActionSet} so the exposed-action set matches exactly what
40
- * the REST/SvelteKit generators actually emit.
38
+ * required to MATERIALIZE a client collection that is what persists).
41
39
  */
42
40
  export declare function selectWebCollectionEntries(manifest: SmartObjectManifest): WebCollectionEntry[];
41
+ /**
42
+ * Build the per-collection web-collection definition literal — the SINGLE
43
+ * source of truth for the shape emitted by {@link generateWebModule} and hashed
44
+ * by {@link computeWebManifestHash}. Building it in ONE place is a
45
+ * cache-coherency requirement: if the emitted shape and the hashed shape were
46
+ * built independently, adding a field to one and not the other would let the
47
+ * hash silently UNDER-cover a shape change, so persisted caches would not drop
48
+ * and stale rows would hydrate into new code.
49
+ */
50
+ export declare function buildWebCollectionDefinition(entry: WebCollectionEntry, manifest: SmartObjectManifest): {
51
+ name: string;
52
+ className: string;
53
+ endpoint: string;
54
+ idField: string;
55
+ actions: string[];
56
+ fields: Record<string, WebFieldDefinition>;
57
+ relationships: WebRelationship[];
58
+ };
43
59
  /**
44
60
  * Build the informational per-field metadata for a web collection definition:
45
61
  * the persisted public-DTO columns only. Relationship pseudo-fields, STI meta
@@ -70,4 +86,37 @@ export declare function buildWebFieldDefinitions(obj: SmartObjectDefinition): Re
70
86
  * and keeping it avoids a special case.
71
87
  */
72
88
  export declare function buildWebRelationships(obj: SmartObjectDefinition, manifest: SmartObjectManifest): WebRelationship[];
89
+ /**
90
+ * A deterministic, replica-stable digest of the web-collection SHAPE (#1764).
91
+ *
92
+ * The hash covers exactly the thing whose change means either old persisted
93
+ * client rows may mis-hydrate OR a stale read ETag would still 304: the same
94
+ * per-collection definition shape {@link generateWebModule} emits — name,
95
+ * className, endpoint, idField, actions, fields, relationships — built via the
96
+ * SHARED {@link buildWebCollectionDefinition} so the hash can never disagree
97
+ * with what is actually shipped. The shape is CANONICALIZED (keys recursively
98
+ * sorted; see {@link canonicalize}) before hashing, so the same schema always
99
+ * yields the same digest across builds and replicas regardless of manifest
100
+ * iteration order.
101
+ *
102
+ * SCOPE — get-OR-list (broader than materializable collections). Covered by
103
+ * {@link selectWebEtagSaltEntries}, so it includes GET-ONLY models too: those do
104
+ * not persist (no materializable collection), but their generated GET route IS
105
+ * salted with this hash, so a shape-only change to a get-only model must change
106
+ * it or a client holding the old concrete ETag gets a zero-query 304 after a
107
+ * shape-only deploy (the #1765 gap the salt closes). The two consumers both use
108
+ * this one value, so it stays identical between them:
109
+ * - `@happyvertical/smrt-web` persistence (#1764) folds it into the durable
110
+ * namespace, so a contract-changing deploy lands on a fresh namespace and old
111
+ * rows are never found (dropped, not mis-hydrated). Including get-only models
112
+ * here is harmless over-invalidation — only list-materializable collections
113
+ * ever hold a persisted snapshot.
114
+ * - the generated read ETag (#1765 salt, #1764) folds it in so a shape-only
115
+ * deploy (no table write) busts every read validator, get-only routes too.
116
+ *
117
+ * Truncated to the first 16 base64url chars: 96 bits is far more than enough to
118
+ * make an accidental shape collision negligible, and a short constant keeps the
119
+ * emitted module and every persistence key compact.
120
+ */
121
+ export declare function computeWebManifestHash(manifest: SmartObjectManifest): string;
73
122
  //# sourceMappingURL=web-collections.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"web-collections.d.ts","sourceRoot":"","sources":["../../src/vite-plugin/web-collections.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EACrB,mBAAmB,EACpB,MAAM,qBAAqB,CAAC;AAyB7B,4EAA4E;AAC5E,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,eAAe,CAAC,MAAM,CAAC,CAAC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B,GAC5B,eAAe,EAAE,CAiCnB;AAyBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,mBAAmB,GAAG,MAAM,CAa5E"}
@@ -1,6 +1,27 @@
1
1
  import { resolveApiActionSet } from "./sveltekit-generator.js";
2
+ import { createHash } from "node:crypto";
2
3
  //#region src/vite-plugin/web-collections.ts
3
4
  /**
5
+ * Manifest → web collection selection (single source of truth).
6
+ *
7
+ * The browser client data runtime (`@happyvertical/smrt-web`, #1761) consumes
8
+ * one typed collection definition per API-exposed REST collection. Three
9
+ * emission sites need the SAME selection and field rules, or the emitted
10
+ * runtime values and their declared types drift apart:
11
+ *
12
+ * - the `\0smrt:web` runtime virtual module (JSON literal — {@link generateWebModule})
13
+ * - the `@happyvertical/smrt-virt-web` ambient d.ts (vite-plugin)
14
+ * - the physical `@smrt/web` d.ts (prebuild, for `tsc`-only consumers)
15
+ *
16
+ * All three import {@link selectWebCollectionEntries} from here so the value
17
+ * emission and the type emission can never disagree. The per-collection SHAPE
18
+ * (name/className/endpoint/idField/actions/fields/relationships) is built by the
19
+ * ONE {@link buildWebCollectionDefinition}, shared by the runtime emission AND
20
+ * the #1764 {@link computeWebManifestHash} shape digest — so the emitted shape
21
+ * and the hashed shape can never drift (a drift would let the hash under-cover a
22
+ * change → stale client caches).
23
+ */
24
+ /**
4
25
  * Field types that are relationship pseudo-columns rather than persisted
5
26
  * public-DTO columns — they never appear on the wire as scalar values.
6
27
  */
@@ -75,19 +96,20 @@ function isStiChildModel(manifest, obj) {
75
96
  return false;
76
97
  }
77
98
  /**
78
- * Select the manifest entries that become web collection definitions: one per
79
- * REST collection, STI children folding into their base model, collection
80
- * classes excluded, and only models that expose `list` (a read surface is
81
- * required to materialize a collection). Uses the canonical
82
- * {@link resolveApiActionSet} so the exposed-action set matches exactly what
83
- * the REST/SvelteKit generators actually emit.
99
+ * Select one entry per REST collection whose exposed action set satisfies
100
+ * `qualifies` STI children folding into their base model, collection classes
101
+ * excluded. Uses the canonical {@link resolveApiActionSet} so the exposed-action
102
+ * set matches exactly what the REST/SvelteKit generators actually emit. Shared
103
+ * by {@link selectWebCollectionEntries} (list-qualified materializable
104
+ * collections) and {@link selectWebEtagSaltEntries} (get-OR-list — every model
105
+ * with a read route the ETag salt must cover).
84
106
  */
85
- function selectWebCollectionEntries(manifest) {
107
+ function selectEntriesQualifiedBy(manifest, qualifies) {
86
108
  const byCollection = /* @__PURE__ */ new Map();
87
109
  for (const obj of Object.values(manifest.objects)) {
88
110
  if (isWebCollectionClass(manifest, obj)) continue;
89
111
  const exposedActions = resolveApiActionSet(obj);
90
- if (!exposedActions.has("list")) continue;
112
+ if (!qualifies(exposedActions)) continue;
91
113
  const isStiChild = isStiChildModel(manifest, obj);
92
114
  const existing = byCollection.get(obj.collection);
93
115
  if (existing && !(existing.isStiChild && !isStiChild)) continue;
@@ -105,6 +127,48 @@ function selectWebCollectionEntries(manifest) {
105
127
  }));
106
128
  }
107
129
  /**
130
+ * Select the manifest entries that become web collection definitions: one per
131
+ * REST collection, STI children folding into their base model, collection
132
+ * classes excluded, and only models that expose `list` (a read surface is
133
+ * required to MATERIALIZE a client collection — that is what persists).
134
+ */
135
+ function selectWebCollectionEntries(manifest) {
136
+ return selectEntriesQualifiedBy(manifest, (actions) => actions.has("list"));
137
+ }
138
+ /**
139
+ * Select the entries the ETag salt (#1764) must cover: every api-exposed model
140
+ * with a GENERATED READ ROUTE — `list` OR `get`. Broader than
141
+ * {@link selectWebCollectionEntries} on purpose: a get-only model
142
+ * (`api: { include: ['get'] }`) has no materializable client collection (so it
143
+ * never persists), but its generated GET route IS salted, so a shape-only change
144
+ * to it must still change the salt — otherwise a client holding the old concrete
145
+ * ETag would get a zero-query 304 after a shape-only deploy (the #1765 gap the
146
+ * salt closes). Not exported: only {@link computeWebManifestHash} consumes it.
147
+ */
148
+ function selectWebEtagSaltEntries(manifest) {
149
+ return selectEntriesQualifiedBy(manifest, (actions) => actions.has("list") || actions.has("get"));
150
+ }
151
+ /**
152
+ * Build the per-collection web-collection definition literal — the SINGLE
153
+ * source of truth for the shape emitted by {@link generateWebModule} and hashed
154
+ * by {@link computeWebManifestHash}. Building it in ONE place is a
155
+ * cache-coherency requirement: if the emitted shape and the hashed shape were
156
+ * built independently, adding a field to one and not the other would let the
157
+ * hash silently UNDER-cover a shape change, so persisted caches would not drop
158
+ * and stale rows would hydrate into new code.
159
+ */
160
+ function buildWebCollectionDefinition(entry, manifest) {
161
+ return {
162
+ name: entry.collection,
163
+ className: entry.obj.className,
164
+ endpoint: `/${entry.collection}`,
165
+ idField: "id",
166
+ actions: entry.actions,
167
+ fields: buildWebFieldDefinitions(entry.obj),
168
+ relationships: buildWebRelationships(entry.obj, manifest)
169
+ };
170
+ }
171
+ /**
108
172
  * Build the informational per-field metadata for a web collection definition:
109
173
  * the persisted public-DTO columns only. Relationship pseudo-fields, STI meta
110
174
  * internals, transient (unpersisted) and sensitive (wire-stripped) fields are
@@ -168,7 +232,63 @@ function buildWebRelationships(obj, manifest) {
168
232
  }
169
233
  return relationships;
170
234
  }
235
+ /**
236
+ * Recursively sort object keys so structurally-equal values serialize to the
237
+ * SAME JSON regardless of insertion order. Arrays keep their order (order is
238
+ * semantic for `actions`/`relationships`); objects are rebuilt with keys sorted.
239
+ * Required for {@link computeWebManifestHash} to be replica-stable: two builds
240
+ * that produce the same schema but visit the manifest in a different order (map
241
+ * insertion, scan order) must still hash identically, which a plain
242
+ * `JSON.stringify` of insertion-ordered objects would NOT guarantee.
243
+ */
244
+ function canonicalize(value) {
245
+ if (Array.isArray(value)) return value.map((entry) => canonicalize(entry));
246
+ if (value && typeof value === "object") {
247
+ const sorted = {};
248
+ for (const key of Object.keys(value).sort()) sorted[key] = canonicalize(value[key]);
249
+ return sorted;
250
+ }
251
+ return value;
252
+ }
253
+ /**
254
+ * A deterministic, replica-stable digest of the web-collection SHAPE (#1764).
255
+ *
256
+ * The hash covers exactly the thing whose change means either old persisted
257
+ * client rows may mis-hydrate OR a stale read ETag would still 304: the same
258
+ * per-collection definition shape {@link generateWebModule} emits — name,
259
+ * className, endpoint, idField, actions, fields, relationships — built via the
260
+ * SHARED {@link buildWebCollectionDefinition} so the hash can never disagree
261
+ * with what is actually shipped. The shape is CANONICALIZED (keys recursively
262
+ * sorted; see {@link canonicalize}) before hashing, so the same schema always
263
+ * yields the same digest across builds and replicas regardless of manifest
264
+ * iteration order.
265
+ *
266
+ * SCOPE — get-OR-list (broader than materializable collections). Covered by
267
+ * {@link selectWebEtagSaltEntries}, so it includes GET-ONLY models too: those do
268
+ * not persist (no materializable collection), but their generated GET route IS
269
+ * salted with this hash, so a shape-only change to a get-only model must change
270
+ * it or a client holding the old concrete ETag gets a zero-query 304 after a
271
+ * shape-only deploy (the #1765 gap the salt closes). The two consumers both use
272
+ * this one value, so it stays identical between them:
273
+ * - `@happyvertical/smrt-web` persistence (#1764) folds it into the durable
274
+ * namespace, so a contract-changing deploy lands on a fresh namespace and old
275
+ * rows are never found (dropped, not mis-hydrated). Including get-only models
276
+ * here is harmless over-invalidation — only list-materializable collections
277
+ * ever hold a persisted snapshot.
278
+ * - the generated read ETag (#1765 salt, #1764) folds it in so a shape-only
279
+ * deploy (no table write) busts every read validator, get-only routes too.
280
+ *
281
+ * Truncated to the first 16 base64url chars: 96 bits is far more than enough to
282
+ * make an accidental shape collision negligible, and a short constant keeps the
283
+ * emitted module and every persistence key compact.
284
+ */
285
+ function computeWebManifestHash(manifest) {
286
+ const definitions = {};
287
+ for (const entry of selectWebEtagSaltEntries(manifest)) definitions[entry.collection] = buildWebCollectionDefinition(entry, manifest);
288
+ const canonicalJson = JSON.stringify(canonicalize(definitions));
289
+ return createHash("sha256").update(canonicalJson).digest("base64url").slice(0, 16);
290
+ }
171
291
  //#endregion
172
- export { buildWebFieldDefinitions, buildWebRelationships, selectWebCollectionEntries };
292
+ export { buildWebCollectionDefinition, buildWebFieldDefinitions, buildWebRelationships, computeWebManifestHash, selectWebCollectionEntries };
173
293
 
174
294
  //# sourceMappingURL=web-collections.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"web-collections.js","names":[],"sources":["../../src/vite-plugin/web-collections.ts"],"sourcesContent":["/**\n * Manifest → web collection selection (single source of truth).\n *\n * The browser client data runtime (`@happyvertical/smrt-web`, #1761) consumes\n * one typed collection definition per API-exposed REST collection. Three\n * emission sites need the SAME selection and field rules, or the emitted\n * runtime values and their declared types drift apart:\n *\n * - the `\\0smrt:web` runtime virtual module (JSON literal — {@link generateWebModule})\n * - the `@happyvertical/smrt-virt-web` ambient d.ts (vite-plugin)\n * - the physical `@smrt/web` d.ts (prebuild, for `tsc`-only consumers)\n *\n * All three import {@link selectWebCollectionEntries} from here so the value\n * emission and the type emission can never disagree.\n */\n\nimport type {\n FieldDefinition,\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { resolveApiActionSet } from './sveltekit-generator.js';\n\n/**\n * Field types that are relationship pseudo-columns rather than persisted\n * public-DTO columns — they never appear on the wire as scalar values.\n */\nconst RELATIONSHIP_FIELD_TYPES: ReadonlySet<FieldDefinition['type']> = new Set([\n 'oneToMany',\n 'manyToMany',\n]);\n\n/**\n * Field types that describe a relationship to another model. A superset of\n * {@link RELATIONSHIP_FIELD_TYPES}: `foreignKey`/`crossPackageRef` are persisted\n * scalar id columns (they DO appear on the wire), while `oneToMany`/`manyToMany`\n * are pseudo-columns — but all four carry a `related` edge to a sibling model.\n */\nconst RELATIONSHIP_EDGE_TYPES: ReadonlySet<FieldDefinition['type']> = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\n/** Informational per-column metadata carried by a collection definition. */\nexport interface WebFieldDefinition {\n type: FieldDefinition['type'];\n required?: boolean;\n default?: unknown;\n}\n\n/** The relationship kinds a web collection edge can describe. */\nexport type WebRelationshipKind =\n | 'foreignKey'\n | 'crossPackageRef'\n | 'oneToMany'\n | 'manyToMany';\n\n/**\n * One manifest-derived relationship edge from a collection to a sibling REST\n * collection. Consumed by the browser client-data runtime to invalidate\n * dependent collection caches when this collection is mutated (#1761) — the\n * cache-invalidation graph is derived entirely from these edges, never\n * hand-wired. SMRT-owned data: no client-engine type appears here.\n */\nexport interface WebRelationship {\n /** The declaring field carrying the relationship (e.g. `groupId`, `items`). */\n field: string;\n /** The relationship kind, mirroring the manifest field type. */\n kind: WebRelationshipKind;\n /** REST collection name the edge resolves to (e.g. `ad_groups`). */\n relatedCollection: string;\n}\n\n/** One selected REST collection and the model that owns its definition. */\nexport interface WebCollectionEntry {\n /** REST collection name (pluralized), e.g. `products`. */\n collection: string;\n /** The manifest object that owns this collection's definition. */\n obj: SmartObjectDefinition;\n /** Sorted set of exposed CRUD + custom actions. */\n actions: string[];\n}\n\n/** Resolve a manifest object by qualified name or simple class name. */\nfunction findByName(\n manifest: SmartObjectManifest,\n name: string,\n): SmartObjectDefinition | undefined {\n return Object.values(manifest.objects).find(\n (candidate) =>\n candidate.qualifiedName === name || candidate.className === name,\n );\n}\n\n/**\n * Normalize a relationship field's `related` value to a resolvable class name.\n *\n * Thunk forward-ref decorators — `@foreignKey(() => Scene)`, used heavily in\n * video/voice for models that reference a class declared later — serialize as\n * the RAW arrow-function source string `\"() => Scene\"` in the manifest, which\n * neither `className` nor `qualifiedName` matches. Extract the target class\n * name from the thunk so the edge resolves. Plain (`\"Scene\"`) and qualified\n * (`\"@happyvertical/smrt-assets:Asset\"`) forms contain no `=>` and pass through\n * untouched — the qualified `:` separator is preserved.\n *\n * Kept local to the relationship-edge path on purpose: extends-chain resolution\n * never sees a thunk, so `findByName` and the scanner stay unchanged.\n */\nfunction normalizeRelatedName(related: string): string {\n const thunk = related.match(/=>\\s*([A-Za-z_$][\\w$]*)/);\n return thunk ? thunk[1] : related.trim();\n}\n\n/**\n * True when `obj` is (transitively) a SmrtCollection subclass. Collection\n * classes describe access, not row shapes, so they never become web\n * collection definitions.\n *\n * NOTE: deliberately stronger than sveltekit-generator's private\n * `isCollectionClass`, which only inspects the direct base / a type argument.\n * A deeper subclass (`SpecialWidgetCollection extends WidgetCollection`)\n * carries no type argument of its own; without walking the extends chain it\n * would be mistaken for a model and claim its base model's REST collection.\n */\nfunction isWebCollectionClass(\n manifest: SmartObjectManifest,\n obj: SmartObjectDefinition,\n seen: Set<string> = new Set(),\n): boolean {\n // Truthy check (not `!== undefined`) mirrors the scanner's own\n // manifest-generator: a scanner that emits `extendsTypeArg: null` for a\n // non-generic base must not be misread as a collection.\n if (obj.extends === 'SmrtCollection' || obj.extendsTypeArg) {\n return true;\n }\n const parentName = obj.extendsQualified || obj.extends;\n if (!parentName || seen.has(parentName)) return false;\n seen.add(parentName);\n const parent = findByName(manifest, parentName);\n return parent ? isWebCollectionClass(manifest, parent, seen) : false;\n}\n\n/**\n * True when some ancestor model maps to the SAME REST collection (a shared STI\n * table). The STI base model owns the shared table's single definition.\n */\nfunction isStiChildModel(\n manifest: SmartObjectManifest,\n obj: SmartObjectDefinition,\n): boolean {\n const seen = new Set<string>();\n let parentName = obj.extendsQualified || obj.extends;\n while (parentName && !seen.has(parentName)) {\n seen.add(parentName);\n const parent = findByName(manifest, parentName);\n if (!parent) return false;\n if (parent.collection === obj.collection) return true;\n parentName = parent.extendsQualified || parent.extends;\n }\n return false;\n}\n\n/**\n * Select the manifest entries that become web collection definitions: one per\n * REST collection, STI children folding into their base model, collection\n * classes excluded, and only models that expose `list` (a read surface is\n * required to materialize a collection). Uses the canonical\n * {@link resolveApiActionSet} so the exposed-action set matches exactly what\n * the REST/SvelteKit generators actually emit.\n */\nexport function selectWebCollectionEntries(\n manifest: SmartObjectManifest,\n): WebCollectionEntry[] {\n const byCollection = new Map<\n string,\n WebCollectionEntry & { isStiChild: boolean }\n >();\n\n for (const obj of Object.values(manifest.objects)) {\n if (isWebCollectionClass(manifest, obj)) continue;\n\n const exposedActions = resolveApiActionSet(obj);\n if (!exposedActions.has('list')) continue;\n\n const isStiChild = isStiChildModel(manifest, obj);\n const existing = byCollection.get(obj.collection);\n // One definition per REST collection. The STI BASE model owns it: a child\n // only wins while no base has been recorded yet, so the result is\n // independent of declaration / scan order.\n if (existing && !(existing.isStiChild && !isStiChild)) continue;\n\n byCollection.set(obj.collection, {\n collection: obj.collection,\n obj,\n actions: [...exposedActions].sort(),\n isStiChild,\n });\n }\n\n return [...byCollection.values()].map(({ collection, obj, actions }) => ({\n collection,\n obj,\n actions,\n }));\n}\n\n/**\n * Build the informational per-field metadata for a web collection definition:\n * the persisted public-DTO columns only. Relationship pseudo-fields, STI meta\n * internals, transient (unpersisted) and sensitive (wire-stripped) fields are\n * excluded — they are not columns a client reads back over the REST surface.\n */\nexport function buildWebFieldDefinitions(\n obj: SmartObjectDefinition,\n): Record<string, WebFieldDefinition> {\n const fields: Record<string, WebFieldDefinition> = {};\n for (const [fieldName, field] of Object.entries(obj.fields ?? {})) {\n if (RELATIONSHIP_FIELD_TYPES.has(field.type)) continue;\n if (field.type === 'meta') continue;\n if (field.transient) continue;\n if (field.sensitive) continue;\n fields[fieldName] = {\n type: field.type,\n ...(field.required !== undefined ? { required: field.required } : {}),\n ...(field.default !== undefined ? { default: field.default } : {}),\n };\n }\n return fields;\n}\n\n/**\n * Build the manifest-derived relationship edges for a web collection\n * definition (#1761): one entry per relationship field (`foreignKey`,\n * `crossPackageRef`, `oneToMany`, `manyToMany`) whose `related` target resolves\n * to another API-exposed REST collection.\n *\n * These edges drive relationship-derived cache invalidation in the browser\n * client-data runtime: mutating this collection invalidates the caches of the\n * collections named here. The invalidation graph is thus derived entirely from\n * the manifest — no hand-wired cache keys.\n *\n * An edge is SKIPPED (not emitted) when:\n * - `related` is missing, or\n * - `related` cannot be resolved to a manifest object (e.g. a cross-package\n * target not present in this package's manifest), or\n * - the resolved target is not itself an API-exposed web collection (no read\n * surface to invalidate — it never appears in {@link selectWebCollectionEntries}).\n *\n * Self-referential edges (a collection related to itself) are kept: the runtime\n * always invalidates the mutated collection anyway, so a self edge is harmless\n * and keeping it avoids a special case.\n */\nexport function buildWebRelationships(\n obj: SmartObjectDefinition,\n manifest: SmartObjectManifest,\n): WebRelationship[] {\n // The set of REST collections that are actually materialized as web\n // collections. An edge to a model outside this set has no client cache to\n // invalidate, so it is dropped.\n const exposedCollections = new Set(\n selectWebCollectionEntries(manifest).map((entry) => entry.collection),\n );\n\n const relationships: WebRelationship[] = [];\n const seen = new Set<string>();\n for (const [fieldName, field] of Object.entries(obj.fields ?? {})) {\n if (!RELATIONSHIP_EDGE_TYPES.has(field.type)) continue;\n if (!field.related) continue;\n\n // Normalize first: `@foreignKey(() => Scene)` thunks serialize as the raw\n // \"() => Scene\" source, which findByName cannot match on its own.\n const target = findByName(manifest, normalizeRelatedName(field.related));\n if (!target) continue;\n if (!exposedCollections.has(target.collection)) continue;\n\n // De-dupe on (field, relatedCollection): a model never declares the same\n // field twice, but guard anyway so the emitted edge list is stable.\n const dedupeKey = `${fieldName}:${target.collection}`;\n if (seen.has(dedupeKey)) continue;\n seen.add(dedupeKey);\n\n relationships.push({\n field: fieldName,\n kind: field.type as WebRelationshipKind,\n relatedCollection: target.collection,\n });\n }\n return relationships;\n}\n"],"mappings":";;;;;;AA2BA,IAAM,2CAAiE,IAAI,IAAI,CAC7E,aACA,YACF,CAAC;;;;;;;AAQD,IAAM,0CAAgE,IAAI,IAAI;CAC5E;CACA;CACA;CACA;AACF,CAAC;;AA2CD,SAAS,WACP,UACA,MACmC;CACnC,OAAO,OAAO,OAAO,SAAS,OAAO,CAAC,CAAC,MACpC,cACC,UAAU,kBAAkB,QAAQ,UAAU,cAAc,IAChE;AACF;;;;;;;;;;;;;;;AAgBA,SAAS,qBAAqB,SAAyB;CACrD,MAAM,QAAQ,QAAQ,MAAM,yBAAyB;CACrD,OAAO,QAAQ,MAAM,KAAK,QAAQ,KAAK;AACzC;;;;;;;;;;;;AAaA,SAAS,qBACP,UACA,KACA,uBAAoB,IAAI,IAAI,GACnB;CAIT,IAAI,IAAI,YAAY,oBAAoB,IAAI,gBAC1C,OAAO;CA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,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,IAAI,UAAU,CAAC,CAAC,GAAG;EACjE,IAAI,yBAAyB,IAAI,MAAM,IAAI,GAAG;EAC9C,IAAI,MAAM,SAAS,QAAQ;EAC3B,IAAI,MAAM,WAAW;EACrB,IAAI,MAAM,WAAW;EACrB,OAAO,aAAa;GAClB,MAAM,MAAM;GACZ,GAAI,MAAM,aAAa,KAAA,IAAY,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;GACnE,GAAI,MAAM,YAAY,KAAA,IAAY,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;EAClE;CACF;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,sBACd,KACA,UACmB;CAInB,MAAM,qBAAqB,IAAI,IAC7B,2BAA2B,QAAQ,CAAC,CAAC,KAAK,UAAU,MAAM,UAAU,CACtE;CAEA,MAAM,gBAAmC,CAAC;CAC1C,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,IAAI,UAAU,CAAC,CAAC,GAAG;EACjE,IAAI,CAAC,wBAAwB,IAAI,MAAM,IAAI,GAAG;EAC9C,IAAI,CAAC,MAAM,SAAS;EAIpB,MAAM,SAAS,WAAW,UAAU,qBAAqB,MAAM,OAAO,CAAC;EACvE,IAAI,CAAC,QAAQ;EACb,IAAI,CAAC,mBAAmB,IAAI,OAAO,UAAU,GAAG;EAIhD,MAAM,YAAY,GAAG,UAAU,GAAG,OAAO;EACzC,IAAI,KAAK,IAAI,SAAS,GAAG;EACzB,KAAK,IAAI,SAAS;EAElB,cAAc,KAAK;GACjB,OAAO;GACP,MAAM,MAAM;GACZ,mBAAmB,OAAO;EAC5B,CAAC;CACH;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"web-collections.js","names":[],"sources":["../../src/vite-plugin/web-collections.ts"],"sourcesContent":["/**\n * Manifest → web collection selection (single source of truth).\n *\n * The browser client data runtime (`@happyvertical/smrt-web`, #1761) consumes\n * one typed collection definition per API-exposed REST collection. Three\n * emission sites need the SAME selection and field rules, or the emitted\n * runtime values and their declared types drift apart:\n *\n * - the `\\0smrt:web` runtime virtual module (JSON literal — {@link generateWebModule})\n * - the `@happyvertical/smrt-virt-web` ambient d.ts (vite-plugin)\n * - the physical `@smrt/web` d.ts (prebuild, for `tsc`-only consumers)\n *\n * All three import {@link selectWebCollectionEntries} from here so the value\n * emission and the type emission can never disagree. The per-collection SHAPE\n * (name/className/endpoint/idField/actions/fields/relationships) is built by the\n * ONE {@link buildWebCollectionDefinition}, shared by the runtime emission AND\n * the #1764 {@link computeWebManifestHash} shape digest — so the emitted shape\n * and the hashed shape can never drift (a drift would let the hash under-cover a\n * change → stale client caches).\n */\n\nimport { createHash } from 'node:crypto';\nimport type {\n FieldDefinition,\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { resolveApiActionSet } from './sveltekit-generator.js';\n\n/**\n * Field types that are relationship pseudo-columns rather than persisted\n * public-DTO columns — they never appear on the wire as scalar values.\n */\nconst RELATIONSHIP_FIELD_TYPES: ReadonlySet<FieldDefinition['type']> = new Set([\n 'oneToMany',\n 'manyToMany',\n]);\n\n/**\n * Field types that describe a relationship to another model. A superset of\n * {@link RELATIONSHIP_FIELD_TYPES}: `foreignKey`/`crossPackageRef` are persisted\n * scalar id columns (they DO appear on the wire), while `oneToMany`/`manyToMany`\n * are pseudo-columns — but all four carry a `related` edge to a sibling model.\n */\nconst RELATIONSHIP_EDGE_TYPES: ReadonlySet<FieldDefinition['type']> = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\n/** Informational per-column metadata carried by a collection definition. */\nexport interface WebFieldDefinition {\n type: FieldDefinition['type'];\n required?: boolean;\n default?: unknown;\n}\n\n/** The relationship kinds a web collection edge can describe. */\nexport type WebRelationshipKind =\n | 'foreignKey'\n | 'crossPackageRef'\n | 'oneToMany'\n | 'manyToMany';\n\n/**\n * One manifest-derived relationship edge from a collection to a sibling REST\n * collection. Consumed by the browser client-data runtime to invalidate\n * dependent collection caches when this collection is mutated (#1761) — the\n * cache-invalidation graph is derived entirely from these edges, never\n * hand-wired. SMRT-owned data: no client-engine type appears here.\n */\nexport interface WebRelationship {\n /** The declaring field carrying the relationship (e.g. `groupId`, `items`). */\n field: string;\n /** The relationship kind, mirroring the manifest field type. */\n kind: WebRelationshipKind;\n /** REST collection name the edge resolves to (e.g. `ad_groups`). */\n relatedCollection: string;\n}\n\n/** One selected REST collection and the model that owns its definition. */\nexport interface WebCollectionEntry {\n /** REST collection name (pluralized), e.g. `products`. */\n collection: string;\n /** The manifest object that owns this collection's definition. */\n obj: SmartObjectDefinition;\n /** Sorted set of exposed CRUD + custom actions. */\n actions: string[];\n}\n\n/** Resolve a manifest object by qualified name or simple class name. */\nfunction findByName(\n manifest: SmartObjectManifest,\n name: string,\n): SmartObjectDefinition | undefined {\n return Object.values(manifest.objects).find(\n (candidate) =>\n candidate.qualifiedName === name || candidate.className === name,\n );\n}\n\n/**\n * Normalize a relationship field's `related` value to a resolvable class name.\n *\n * Thunk forward-ref decorators — `@foreignKey(() => Scene)`, used heavily in\n * video/voice for models that reference a class declared later — serialize as\n * the RAW arrow-function source string `\"() => Scene\"` in the manifest, which\n * neither `className` nor `qualifiedName` matches. Extract the target class\n * name from the thunk so the edge resolves. Plain (`\"Scene\"`) and qualified\n * (`\"@happyvertical/smrt-assets:Asset\"`) forms contain no `=>` and pass through\n * untouched — the qualified `:` separator is preserved.\n *\n * Kept local to the relationship-edge path on purpose: extends-chain resolution\n * never sees a thunk, so `findByName` and the scanner stay unchanged.\n */\nfunction normalizeRelatedName(related: string): string {\n const thunk = related.match(/=>\\s*([A-Za-z_$][\\w$]*)/);\n return thunk ? thunk[1] : related.trim();\n}\n\n/**\n * True when `obj` is (transitively) a SmrtCollection subclass. Collection\n * classes describe access, not row shapes, so they never become web\n * collection definitions.\n *\n * NOTE: deliberately stronger than sveltekit-generator's private\n * `isCollectionClass`, which only inspects the direct base / a type argument.\n * A deeper subclass (`SpecialWidgetCollection extends WidgetCollection`)\n * carries no type argument of its own; without walking the extends chain it\n * would be mistaken for a model and claim its base model's REST collection.\n */\nfunction isWebCollectionClass(\n manifest: SmartObjectManifest,\n obj: SmartObjectDefinition,\n seen: Set<string> = new Set(),\n): boolean {\n // Truthy check (not `!== undefined`) mirrors the scanner's own\n // manifest-generator: a scanner that emits `extendsTypeArg: null` for a\n // non-generic base must not be misread as a collection.\n if (obj.extends === 'SmrtCollection' || obj.extendsTypeArg) {\n return true;\n }\n const parentName = obj.extendsQualified || obj.extends;\n if (!parentName || seen.has(parentName)) return false;\n seen.add(parentName);\n const parent = findByName(manifest, parentName);\n return parent ? isWebCollectionClass(manifest, parent, seen) : false;\n}\n\n/**\n * True when some ancestor model maps to the SAME REST collection (a shared STI\n * table). The STI base model owns the shared table's single definition.\n */\nfunction isStiChildModel(\n manifest: SmartObjectManifest,\n obj: SmartObjectDefinition,\n): boolean {\n const seen = new Set<string>();\n let parentName = obj.extendsQualified || obj.extends;\n while (parentName && !seen.has(parentName)) {\n seen.add(parentName);\n const parent = findByName(manifest, parentName);\n if (!parent) return false;\n if (parent.collection === obj.collection) return true;\n parentName = parent.extendsQualified || parent.extends;\n }\n return false;\n}\n\n/**\n * Select one entry per REST collection whose exposed action set satisfies\n * `qualifies` — STI children folding into their base model, collection classes\n * excluded. Uses the canonical {@link resolveApiActionSet} so the exposed-action\n * set matches exactly what the REST/SvelteKit generators actually emit. Shared\n * by {@link selectWebCollectionEntries} (list-qualified — materializable\n * collections) and {@link selectWebEtagSaltEntries} (get-OR-list — every model\n * with a read route the ETag salt must cover).\n */\nfunction selectEntriesQualifiedBy(\n manifest: SmartObjectManifest,\n qualifies: (actions: ReadonlySet<string>) => boolean,\n): WebCollectionEntry[] {\n const byCollection = new Map<\n string,\n WebCollectionEntry & { isStiChild: boolean }\n >();\n\n for (const obj of Object.values(manifest.objects)) {\n if (isWebCollectionClass(manifest, obj)) continue;\n\n const exposedActions = resolveApiActionSet(obj);\n if (!qualifies(exposedActions)) continue;\n\n const isStiChild = isStiChildModel(manifest, obj);\n const existing = byCollection.get(obj.collection);\n // One definition per REST collection. The STI BASE model owns it: a child\n // only wins while no base has been recorded yet, so the result is\n // independent of declaration / scan order.\n if (existing && !(existing.isStiChild && !isStiChild)) continue;\n\n byCollection.set(obj.collection, {\n collection: obj.collection,\n obj,\n actions: [...exposedActions].sort(),\n isStiChild,\n });\n }\n\n return [...byCollection.values()].map(({ collection, obj, actions }) => ({\n collection,\n obj,\n actions,\n }));\n}\n\n/**\n * Select the manifest entries that become web collection definitions: one per\n * REST collection, STI children folding into their base model, collection\n * classes excluded, and only models that expose `list` (a read surface is\n * required to MATERIALIZE a client collection — that is what persists).\n */\nexport function selectWebCollectionEntries(\n manifest: SmartObjectManifest,\n): WebCollectionEntry[] {\n return selectEntriesQualifiedBy(manifest, (actions) => actions.has('list'));\n}\n\n/**\n * Select the entries the ETag salt (#1764) must cover: every api-exposed model\n * with a GENERATED READ ROUTE — `list` OR `get`. Broader than\n * {@link selectWebCollectionEntries} on purpose: a get-only model\n * (`api: { include: ['get'] }`) has no materializable client collection (so it\n * never persists), but its generated GET route IS salted, so a shape-only change\n * to it must still change the salt — otherwise a client holding the old concrete\n * ETag would get a zero-query 304 after a shape-only deploy (the #1765 gap the\n * salt closes). Not exported: only {@link computeWebManifestHash} consumes it.\n */\nfunction selectWebEtagSaltEntries(\n manifest: SmartObjectManifest,\n): WebCollectionEntry[] {\n return selectEntriesQualifiedBy(\n manifest,\n (actions) => actions.has('list') || actions.has('get'),\n );\n}\n\n/**\n * Build the per-collection web-collection definition literal — the SINGLE\n * source of truth for the shape emitted by {@link generateWebModule} and hashed\n * by {@link computeWebManifestHash}. Building it in ONE place is a\n * cache-coherency requirement: if the emitted shape and the hashed shape were\n * built independently, adding a field to one and not the other would let the\n * hash silently UNDER-cover a shape change, so persisted caches would not drop\n * and stale rows would hydrate into new code.\n */\nexport function buildWebCollectionDefinition(\n entry: WebCollectionEntry,\n manifest: SmartObjectManifest,\n): {\n name: string;\n className: string;\n endpoint: string;\n idField: string;\n actions: string[];\n fields: Record<string, WebFieldDefinition>;\n relationships: WebRelationship[];\n} {\n return {\n name: entry.collection,\n className: entry.obj.className,\n endpoint: `/${entry.collection}`,\n idField: 'id',\n actions: entry.actions,\n fields: buildWebFieldDefinitions(entry.obj),\n relationships: buildWebRelationships(entry.obj, manifest),\n };\n}\n\n/**\n * Build the informational per-field metadata for a web collection definition:\n * the persisted public-DTO columns only. Relationship pseudo-fields, STI meta\n * internals, transient (unpersisted) and sensitive (wire-stripped) fields are\n * excluded — they are not columns a client reads back over the REST surface.\n */\nexport function buildWebFieldDefinitions(\n obj: SmartObjectDefinition,\n): Record<string, WebFieldDefinition> {\n const fields: Record<string, WebFieldDefinition> = {};\n for (const [fieldName, field] of Object.entries(obj.fields ?? {})) {\n if (RELATIONSHIP_FIELD_TYPES.has(field.type)) continue;\n if (field.type === 'meta') continue;\n if (field.transient) continue;\n if (field.sensitive) continue;\n fields[fieldName] = {\n type: field.type,\n ...(field.required !== undefined ? { required: field.required } : {}),\n ...(field.default !== undefined ? { default: field.default } : {}),\n };\n }\n return fields;\n}\n\n/**\n * Build the manifest-derived relationship edges for a web collection\n * definition (#1761): one entry per relationship field (`foreignKey`,\n * `crossPackageRef`, `oneToMany`, `manyToMany`) whose `related` target resolves\n * to another API-exposed REST collection.\n *\n * These edges drive relationship-derived cache invalidation in the browser\n * client-data runtime: mutating this collection invalidates the caches of the\n * collections named here. The invalidation graph is thus derived entirely from\n * the manifest — no hand-wired cache keys.\n *\n * An edge is SKIPPED (not emitted) when:\n * - `related` is missing, or\n * - `related` cannot be resolved to a manifest object (e.g. a cross-package\n * target not present in this package's manifest), or\n * - the resolved target is not itself an API-exposed web collection (no read\n * surface to invalidate — it never appears in {@link selectWebCollectionEntries}).\n *\n * Self-referential edges (a collection related to itself) are kept: the runtime\n * always invalidates the mutated collection anyway, so a self edge is harmless\n * and keeping it avoids a special case.\n */\nexport function buildWebRelationships(\n obj: SmartObjectDefinition,\n manifest: SmartObjectManifest,\n): WebRelationship[] {\n // The set of REST collections that are actually materialized as web\n // collections. An edge to a model outside this set has no client cache to\n // invalidate, so it is dropped.\n const exposedCollections = new Set(\n selectWebCollectionEntries(manifest).map((entry) => entry.collection),\n );\n\n const relationships: WebRelationship[] = [];\n const seen = new Set<string>();\n for (const [fieldName, field] of Object.entries(obj.fields ?? {})) {\n if (!RELATIONSHIP_EDGE_TYPES.has(field.type)) continue;\n if (!field.related) continue;\n\n // Normalize first: `@foreignKey(() => Scene)` thunks serialize as the raw\n // \"() => Scene\" source, which findByName cannot match on its own.\n const target = findByName(manifest, normalizeRelatedName(field.related));\n if (!target) continue;\n if (!exposedCollections.has(target.collection)) continue;\n\n // De-dupe on (field, relatedCollection): a model never declares the same\n // field twice, but guard anyway so the emitted edge list is stable.\n const dedupeKey = `${fieldName}:${target.collection}`;\n if (seen.has(dedupeKey)) continue;\n seen.add(dedupeKey);\n\n relationships.push({\n field: fieldName,\n kind: field.type as WebRelationshipKind,\n relatedCollection: target.collection,\n });\n }\n return relationships;\n}\n\n/**\n * Recursively sort object keys so structurally-equal values serialize to the\n * SAME JSON regardless of insertion order. Arrays keep their order (order is\n * semantic for `actions`/`relationships`); objects are rebuilt with keys sorted.\n * Required for {@link computeWebManifestHash} to be replica-stable: two builds\n * that produce the same schema but visit the manifest in a different order (map\n * insertion, scan order) must still hash identically, which a plain\n * `JSON.stringify` of insertion-ordered objects would NOT guarantee.\n */\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((entry) => canonicalize(entry));\n }\n if (value && typeof value === 'object') {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[key] = canonicalize((value as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n return value;\n}\n\n/**\n * A deterministic, replica-stable digest of the web-collection SHAPE (#1764).\n *\n * The hash covers exactly the thing whose change means either old persisted\n * client rows may mis-hydrate OR a stale read ETag would still 304: the same\n * per-collection definition shape {@link generateWebModule} emits — name,\n * className, endpoint, idField, actions, fields, relationships — built via the\n * SHARED {@link buildWebCollectionDefinition} so the hash can never disagree\n * with what is actually shipped. The shape is CANONICALIZED (keys recursively\n * sorted; see {@link canonicalize}) before hashing, so the same schema always\n * yields the same digest across builds and replicas regardless of manifest\n * iteration order.\n *\n * SCOPE — get-OR-list (broader than materializable collections). Covered by\n * {@link selectWebEtagSaltEntries}, so it includes GET-ONLY models too: those do\n * not persist (no materializable collection), but their generated GET route IS\n * salted with this hash, so a shape-only change to a get-only model must change\n * it or a client holding the old concrete ETag gets a zero-query 304 after a\n * shape-only deploy (the #1765 gap the salt closes). The two consumers both use\n * this one value, so it stays identical between them:\n * - `@happyvertical/smrt-web` persistence (#1764) folds it into the durable\n * namespace, so a contract-changing deploy lands on a fresh namespace and old\n * rows are never found (dropped, not mis-hydrated). Including get-only models\n * here is harmless over-invalidation — only list-materializable collections\n * ever hold a persisted snapshot.\n * - the generated read ETag (#1765 salt, #1764) folds it in so a shape-only\n * deploy (no table write) busts every read validator, get-only routes too.\n *\n * Truncated to the first 16 base64url chars: 96 bits is far more than enough to\n * make an accidental shape collision negligible, and a short constant keeps the\n * emitted module and every persistence key compact.\n */\nexport function computeWebManifestHash(manifest: SmartObjectManifest): string {\n const definitions: Record<string, unknown> = {};\n for (const entry of selectWebEtagSaltEntries(manifest)) {\n definitions[entry.collection] = buildWebCollectionDefinition(\n entry,\n manifest,\n );\n }\n const canonicalJson = JSON.stringify(canonicalize(definitions));\n return createHash('sha256')\n .update(canonicalJson)\n .digest('base64url')\n .slice(0, 16);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAM,2CAAiE,IAAI,IAAI,CAC7E,aACA,YACF,CAAC;;;;;;;AAQD,IAAM,0CAAgE,IAAI,IAAI;CAC5E;CACA;CACA;CACA;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BAAgB,KAAK,UAAU,aAAa,WAAW,CAAC;CAC9D,OAAO,WAAW,QAAQ,CAAC,CACxB,OAAO,aAAa,CAAC,CACrB,OAAO,WAAW,CAAC,CACnB,MAAM,GAAG,EAAE;AAChB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-core",
3
- "version": "0.38.5",
3
+ "version": "0.38.7",
4
4
  "description": "Core AI agent framework with standardized collections, object-relational mapping, and code generators",
5
5
  "author": "HappyVertical",
6
6
  "type": "module",
@@ -154,9 +154,9 @@
154
154
  "tsx": "^4.23.0",
155
155
  "typescript": "^5.9.3",
156
156
  "yaml": "^2.9.0",
157
- "@happyvertical/smrt-config": "0.38.5",
158
- "@happyvertical/smrt-scanner": "0.38.5",
159
- "@happyvertical/smrt-types": "0.38.5"
157
+ "@happyvertical/smrt-config": "0.38.7",
158
+ "@happyvertical/smrt-types": "0.38.7",
159
+ "@happyvertical/smrt-scanner": "0.38.7"
160
160
  },
161
161
  "peerDependencies": {
162
162
  "@huggingface/transformers": ">=3.0.0 <4.0.0",