@memberjunction/integration-engine 6.2.0-edge.5 → 6.2.0-edge.6

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 (52) hide show
  1. package/dist/BaseIntegrationConnector.d.ts.map +1 -1
  2. package/dist/BaseIntegrationConnector.js +22 -4
  3. package/dist/BaseIntegrationConnector.js.map +1 -1
  4. package/dist/BaseRESTIntegrationConnector.d.ts +2 -2
  5. package/dist/BaseRESTIntegrationConnector.d.ts.map +1 -1
  6. package/dist/BaseRESTIntegrationConnector.js +34 -4
  7. package/dist/BaseRESTIntegrationConnector.js.map +1 -1
  8. package/dist/CatalogScope.d.ts +152 -0
  9. package/dist/CatalogScope.d.ts.map +1 -0
  10. package/dist/CatalogScope.js +399 -0
  11. package/dist/CatalogScope.js.map +1 -0
  12. package/dist/CatalogSource.d.ts +53 -0
  13. package/dist/CatalogSource.d.ts.map +1 -0
  14. package/dist/CatalogSource.js +82 -0
  15. package/dist/CatalogSource.js.map +1 -0
  16. package/dist/CatalogWriter.d.ts +216 -0
  17. package/dist/CatalogWriter.d.ts.map +1 -0
  18. package/dist/CatalogWriter.js +457 -0
  19. package/dist/CatalogWriter.js.map +1 -0
  20. package/dist/CompanyIntegrationCatalogStore.d.ts +109 -0
  21. package/dist/CompanyIntegrationCatalogStore.d.ts.map +1 -0
  22. package/dist/CompanyIntegrationCatalogStore.js +229 -0
  23. package/dist/CompanyIntegrationCatalogStore.js.map +1 -0
  24. package/dist/DiscoveryWatchdog.d.ts +38 -1
  25. package/dist/DiscoveryWatchdog.d.ts.map +1 -1
  26. package/dist/DiscoveryWatchdog.js +56 -1
  27. package/dist/DiscoveryWatchdog.js.map +1 -1
  28. package/dist/IntegrationActionGenerator.d.ts.map +1 -1
  29. package/dist/IntegrationActionGenerator.js +33 -26
  30. package/dist/IntegrationActionGenerator.js.map +1 -1
  31. package/dist/IntegrationConnectorCreationPipeline.d.ts +141 -4
  32. package/dist/IntegrationConnectorCreationPipeline.d.ts.map +1 -1
  33. package/dist/IntegrationConnectorCreationPipeline.js +521 -64
  34. package/dist/IntegrationConnectorCreationPipeline.js.map +1 -1
  35. package/dist/IntegrationEngine.d.ts +13 -0
  36. package/dist/IntegrationEngine.d.ts.map +1 -1
  37. package/dist/IntegrationEngine.js +250 -164
  38. package/dist/IntegrationEngine.js.map +1 -1
  39. package/dist/IntegrationSchemaSync.d.ts +97 -0
  40. package/dist/IntegrationSchemaSync.d.ts.map +1 -1
  41. package/dist/IntegrationSchemaSync.js +300 -49
  42. package/dist/IntegrationSchemaSync.js.map +1 -1
  43. package/dist/MatchEngine.d.ts.map +1 -1
  44. package/dist/MatchEngine.js +6 -0
  45. package/dist/MatchEngine.js.map +1 -1
  46. package/dist/index.d.ts +8 -0
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +6 -0
  49. package/dist/index.js.map +1 -1
  50. package/dist/types.d.ts +21 -0
  51. package/dist/types.d.ts.map +1 -1
  52. package/package.json +7 -7
@@ -0,0 +1,457 @@
1
+ import { CompositeKey, LogError, RunView } from '@memberjunction/core';
2
+ import { EscapeSQLString } from '@memberjunction/global';
3
+ import { CATALOG_FIELD_COLUMNS, CATALOG_OBJECT_COLUMNS, CompanyIntegrationCatalogSchemaMismatch, ENTITY_COMPANY_INTEGRATION_OBJECTS, ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS, DECLARED_OWNED_OBJECT_COLUMNS, DECLARED_OWNED_FIELD_COLUMNS, } from '@memberjunction/integration-engine-base';
4
+ /**
5
+ * One write interface over BOTH integration catalogs — the one shared by every connection of a
6
+ * connector, and the one belonging to a single connection.
7
+ *
8
+ * The persistence logic is identical for both: the same per-attribute overlay deciders, the same
9
+ * two-pass object-then-field ordering, the same reactivate-on-rediscover rule, the same
10
+ * absent-deactivation pass. Only the entity name, the scope filter and a few ownership columns
11
+ * differ. This abstracts exactly those and leaves the merge logic untouched.
12
+ *
13
+ * ── Why the rows are proxies ───────────────────────────────────────────────────────────────────
14
+ *
15
+ * The per-connection entities are registered by a migration, not by CodeGen (tenant CodeGen
16
+ * excludes the core schema), so they have NO generated subclass. On such a row:
17
+ *
18
+ * row.Description = 'x'; // creates an own property beside the entity's field list
19
+ * await row.Save(); // returns true, sends nothing, logs nothing
20
+ *
21
+ * There is no accessor to intercept the assignment. Across a discovery persisting hundreds of rows
22
+ * that presents as a source that returned less than expected — a vendor problem, not a code one.
23
+ *
24
+ * A proxy closes that gap without touching the merge logic. Property access it cannot find on the
25
+ * row falls through to `Get`/`Set`, which is exactly what a generated accessor does:
26
+ *
27
+ * get Description() { return this.Get('Description'); }
28
+ * set Description(v) { this.Set('Description', v); }
29
+ *
30
+ * So for the SHARED catalog the proxy is transparent — the real accessor is found on the prototype
31
+ * and used. For the per-connection catalog it supplies the accessor that was never generated. The
32
+ * alternative was rewriting ~50 assignments in a 1,181-line file whose orchestration has no test
33
+ * coverage at all; this way the delicate part does not move.
34
+ *
35
+ * Methods are bound to the underlying row rather than the proxy, so `Save()` runs against the real
36
+ * entity and cannot recurse back through this handler.
37
+ */
38
+ /** Write-side column aliases, mirroring what the per-connection VIEW already does for reads. */
39
+ const FIELD_WRITE_ALIASES = {
40
+ // A field's parent and its dependency-edge target are named for the shared catalog throughout
41
+ // the persistence code. On the per-connection tables the real columns carry the per-connection
42
+ // names, and the view exposes the shared names as aliases. Mapping them here means the merge
43
+ // logic keeps writing `field.IntegrationObjectID` and lands on the right column.
44
+ IntegrationObjectID: 'CompanyIntegrationObjectID',
45
+ RelatedIntegrationObjectID: 'RelatedCompanyIntegrationObjectID',
46
+ };
47
+ /**
48
+ * Wrap a row so property access resolves through `Get`/`Set`, with an optional column allowlist and
49
+ * alias map.
50
+ *
51
+ * `required` is set only for the per-connection entities and does two jobs. On wrap it asserts the
52
+ * loaded entity carries every column this code writes, so an absent or stale migration fails here,
53
+ * named, instead of as scattered missing values hours later in a run that reported success. On each
54
+ * write it checks the column against the ROW'S OWN field list — not against `required` — because
55
+ * those answer different questions: `required` is what we expect, the field list is what the
56
+ * database actually has, and it is the gap between them that loses writes silently.
57
+ *
58
+ * The shared entities are left unguarded: their generated subclass turns a bad column name into a
59
+ * compile error long before this point.
60
+ */
61
+ function proxyRow(row, entityName, required, aliases) {
62
+ const columns = required === null ? null : new Set((row.Fields ?? []).map(f => f.Name));
63
+ if (required !== null && columns !== null) {
64
+ const missing = required.filter(c => !columns.has(c));
65
+ if (missing.length > 0)
66
+ throw new CompanyIntegrationCatalogSchemaMismatch(entityName, missing);
67
+ }
68
+ return new Proxy(row, {
69
+ get(target, prop, receiver) {
70
+ if (typeof prop !== 'string')
71
+ return Reflect.get(target, prop, receiver);
72
+ if (prop in target) {
73
+ const value = Reflect.get(target, prop, target);
74
+ // Bind to the REAL row: an unbound method called on the proxy would run its own
75
+ // internals back through this handler.
76
+ return typeof value === 'function' ? value.bind(target) : value;
77
+ }
78
+ return target.Get(aliases?.[prop] ?? prop);
79
+ },
80
+ set(target, prop, value, receiver) {
81
+ if (typeof prop !== 'string')
82
+ return Reflect.set(target, prop, value, receiver);
83
+ if (prop in target)
84
+ return Reflect.set(target, prop, value, target);
85
+ const column = aliases?.[prop] ?? prop;
86
+ if (columns && !columns.has(column)) {
87
+ throw new Error(`${entityName} has no column '${column}'`
88
+ + (column === prop ? '' : ` (aliased from '${prop}')`)
89
+ + `. Writing it would create a property beside the entity's field list and `
90
+ + `Save() would report success while writing nothing.`);
91
+ }
92
+ target.Set(column, value);
93
+ return true;
94
+ },
95
+ });
96
+ }
97
+ /** Telemetry note on every catalog read below: each deliberately reads around the query cache. */
98
+ const CATALOG_READ_TELEMETRY = {
99
+ Exempt: true,
100
+ Reason: 'Catalog read inside a discovery run; a cached answer predates the write it must observe',
101
+ };
102
+ async function newRow(md, entityName, contextUser, guard, aliases) {
103
+ const row = await md.GetEntityObject(entityName, contextUser);
104
+ if (!row)
105
+ throw new CompanyIntegrationCatalogSchemaMismatch(entityName, ['<entity not registered>']);
106
+ row.NewRecord();
107
+ return proxyRow(row, entityName, guard, aliases);
108
+ }
109
+ async function loadRow(md, entityName, contextUser, id, guard, aliases) {
110
+ const row = await md.GetEntityObject(entityName, contextUser);
111
+ if (!row)
112
+ return null;
113
+ // `Load(id)` is a generated-subclass convenience; this is the base entry point, and the only
114
+ // one available for an entity a migration registered rather than CodeGen.
115
+ const ok = await row.InnerLoad(CompositeKey.FromID(id)); // first-pk-ok: every caller passes an MJ core catalog entity ('MJ: Integration Objects' / '... Object Fields' / their 'MJ: Company Integration ...' twins), all keyed by ID
116
+ return ok ? proxyRow(row, entityName, guard, aliases) : null;
117
+ }
118
+ async function viewRows(entityName, filter, contextUser, provider, guard, aliases) {
119
+ // Server-side providers are DatabaseProviderBase, which implements IRunViewProvider; the
120
+ // narrower IMetadataProvider we are handed does not declare it. Same narrowing, and the same
121
+ // reason, as IntegrationEngine's own RunView construction in this package.
122
+ const rv = new RunView(provider);
123
+ // BypassCache is MANDATORY here, not an optimisation. The query-result cache is keyed on the
124
+ // query TEXT and, where it is shared and external to the process, survives a restart. Introspect
125
+ // reads each object's fields BEFORE Persist writes them, so on a first discovery the cache holds
126
+ // EMPTY; the classify stage then replays the byte-identical query and is served that empty list,
127
+ // reporting every object keyless while the rows plainly exist. Observed 2026-09-27: the baseline
128
+ // filter returned 0 rows while the same filter with an extra space before '=' returned 8,
129
+ // unchanged across a confirmed restart. Bypassing in the catalog STORE alone changed nothing: the
130
+ // writer is the read on that path. With it here, fields created 207 -> 0 and updated 0 -> 76, and
131
+ // unresolved objects 34 -> 4 — the 4 that genuinely carry no key.
132
+ const res = await rv.RunView({ EntityName: entityName, ExtraFilter: filter, ResultType: 'entity_object', BypassCache: true, Telemetry: CATALOG_READ_TELEMETRY }, contextUser);
133
+ // A failed read is an ERROR, never an empty catalog. Returning [] here was read by every
134
+ // consumer as "this object has no fields": the classifier then reported every object
135
+ // keyless, the schema builder skipped them all, and the run completed green having done
136
+ // nothing — with the provider's own message, the only diagnosis, discarded.
137
+ if (!res?.Success) {
138
+ throw new CompanyIntegrationCatalogReadFailed(entityName, filter, res?.ErrorMessage ?? 'RunView returned no result');
139
+ }
140
+ return (res.Results ?? []).map(r => proxyRow(r, entityName, guard, aliases));
141
+ }
142
+ /**
143
+ * Which of these owner rows already carry a primary key — one two-column scan per 200 owners
144
+ * rather than one entity-object read per owner.
145
+ *
146
+ * The key flag is filtered here rather than in SQL: `IsPrimaryKey = 1` is a bit on SQL Server
147
+ * and a boolean on Postgres, and this code runs on both. Owner ids are compared lowercased —
148
+ * the two dialects return GUID text in different cases.
149
+ */
150
+ async function keyedOwnerIDs(entityName, ownerColumn, ownerIDs, contextUser, provider) {
151
+ const keyed = new Set();
152
+ const CHUNK = 200;
153
+ for (let i = 0; i < ownerIDs.length; i += CHUNK) {
154
+ const slice = ownerIDs.slice(i, i + CHUNK);
155
+ if (slice.length === 0)
156
+ continue;
157
+ const list = slice.map(id => `'${EscapeSQLString(String(id))}'`).join(',');
158
+ const rv = new RunView(provider);
159
+ // Bypasses the query cache for the reason viewRows does: this runs straight after Persist,
160
+ // and the same objects produce byte-identical text on every re-discovery.
161
+ const res = await rv.RunView({
162
+ EntityName: entityName, ExtraFilter: `${ownerColumn} IN (${list})`, Fields: [ownerColumn, 'IsPrimaryKey'],
163
+ ResultType: 'simple', BypassCache: true, Telemetry: CATALOG_READ_TELEMETRY,
164
+ }, contextUser);
165
+ if (!res?.Success) {
166
+ throw new CompanyIntegrationCatalogReadFailed(entityName, `${ownerColumn} IN (${slice.length} ids)`, res?.ErrorMessage ?? 'RunView returned no result');
167
+ }
168
+ for (const row of res.Results ?? []) {
169
+ const flag = row.IsPrimaryKey;
170
+ if (flag === true || flag === 1 || flag === '1' || flag === 'true')
171
+ keyed.add(String(row[ownerColumn]).toLowerCase());
172
+ }
173
+ }
174
+ return keyed;
175
+ }
176
+ /** A catalog read that did not succeed: the entity, the filter and the provider's own message. */
177
+ export class CompanyIntegrationCatalogReadFailed extends Error {
178
+ constructor(entityName, filter, message) {
179
+ super(`[CatalogWriter] ${entityName} read failed (filter: ${filter}): ${message}`);
180
+ this.name = 'CompanyIntegrationCatalogReadFailed';
181
+ this.EntityName = entityName;
182
+ this.Filter = filter;
183
+ }
184
+ }
185
+ /** The catalog shared by every connection of a connector. Today's behaviour, unchanged. */
186
+ /**
187
+ * `MJ_INTEGRATION_CATALOG_STRICT=1` makes the DECLARED catalog read-only at runtime.
188
+ *
189
+ * `MJ: Integration Object(Field)s` are the connector's shipped metadata, and they are not merely
190
+ * reference data: `PerConnectionCatalogWriter.RebaseFromDeclared` copies their columns onto every
191
+ * per-connection row on every discovery, so they are the FLOOR every connection is rebuilt from.
192
+ * A single connection left on the shared catalog writes its own sampled shape into that floor, and
193
+ * every later connection of the same connector then inherits one account's widths and columns as
194
+ * though the vendor had declared them.
195
+ *
196
+ * Observed on the sandbox, 2026-09-11: one discovery on a `Shared` connection added 69 sampled
197
+ * columns and overwrote 4 columns on 487 declared fields. The run reported success and nothing
198
+ * anywhere recorded that the declared catalog had changed — it was only provable because a
199
+ * snapshot had been taken beforehand.
200
+ *
201
+ * Deliberately OFF by default and enabled per environment: a connection legitimately on the shared
202
+ * catalog (one that predates the per-connection tables and has not been backfilled) writes here by
203
+ * design, and would start failing. Turn it on where every connection is already per-connection —
204
+ * the sandbox — so a regression is a loud failure rather than silent corruption. Reads are
205
+ * untouched; only the row-producing calls throw, so the declared floor stays readable.
206
+ */
207
+ const STRICT_ENV = 'MJ_INTEGRATION_CATALOG_STRICT';
208
+ function strictDeclaredCatalog() {
209
+ const v = process.env[STRICT_ENV];
210
+ return v === '1' || (typeof v === 'string' && v.trim().toLowerCase() === 'true');
211
+ }
212
+ export class SharedCatalogWriter {
213
+ static { this.OBJECTS = 'MJ: Integration Objects'; }
214
+ static { this.FIELDS = 'MJ: Integration Object Fields'; }
215
+ constructor(md, integrationID, contextUser) {
216
+ this.md = md;
217
+ this.integrationID = integrationID;
218
+ this.contextUser = contextUser;
219
+ this.Source = 'Shared';
220
+ }
221
+ ObjectsInScope() {
222
+ return viewRows(SharedCatalogWriter.OBJECTS, `IntegrationID = '${EscapeSQLString(this.integrationID)}'`, this.contextUser, this.md, null, null);
223
+ }
224
+ FieldsForObject(objectID) {
225
+ return viewRows(SharedCatalogWriter.FIELDS, `IntegrationObjectID = '${EscapeSQLString(objectID)}'`, this.contextUser, this.md, null, null);
226
+ }
227
+ KeyedObjectIDs(objectIDs) {
228
+ return keyedOwnerIDs(SharedCatalogWriter.FIELDS, 'IntegrationObjectID', objectIDs, this.contextUser, this.md);
229
+ }
230
+ /**
231
+ * The four calls below exist to hand the caller a row it is about to mutate and Save, so they
232
+ * are the write boundary — guarding them, rather than the reads above, keeps the declared floor
233
+ * readable while making a runtime write to it impossible. See `strictDeclaredCatalog`.
234
+ */
235
+ refuseIfStrict(what) {
236
+ if (!strictDeclaredCatalog())
237
+ return;
238
+ throw new Error(`DECLARED_CATALOG_READONLY: refusing to ${what} in the shared/declared catalog for `
239
+ + `integration ${this.integrationID}. ${STRICT_ENV} is set, which makes `
240
+ + `"MJ: Integration Object(Field)s" read-only at runtime — they hold the connector's `
241
+ + `DECLARED metadata, and every per-connection catalog is rebased from them, so a `
242
+ + `discovery writing here would put one account's shape into every other connection of `
243
+ + `this connector. Set this connection's Configuration.catalogSource to "perConnection" `
244
+ + `(MJ Central stamps that at create), or unset ${STRICT_ENV} if this environment still `
245
+ + `has connections that legitimately use the shared catalog.`);
246
+ }
247
+ NewObjectRow() {
248
+ this.refuseIfStrict('create an object');
249
+ return newRow(this.md, SharedCatalogWriter.OBJECTS, this.contextUser, null, null);
250
+ }
251
+ NewFieldRow() {
252
+ this.refuseIfStrict('create a field');
253
+ return newRow(this.md, SharedCatalogWriter.FIELDS, this.contextUser, null, null);
254
+ }
255
+ LoadObject(id) {
256
+ this.refuseIfStrict('modify an object');
257
+ return loadRow(this.md, SharedCatalogWriter.OBJECTS, this.contextUser, id, null, null);
258
+ }
259
+ LoadField(id) {
260
+ this.refuseIfStrict('modify a field');
261
+ return loadRow(this.md, SharedCatalogWriter.FIELDS, this.contextUser, id, null, null);
262
+ }
263
+ /** The shared catalog records ownership as the integration id and nothing else. */
264
+ StampNewObject(row) {
265
+ row.IntegrationID = this.integrationID;
266
+ }
267
+ StampNewField() {
268
+ /* the parent object id is the only ownership a shared field row carries */
269
+ }
270
+ /** The shared row IS the declaration; there is nothing to rebase it from. */
271
+ RebaseFromDeclared() { return []; }
272
+ /** Likewise: the shared row cannot adopt a declaration, because it is one. */
273
+ AdoptDeclaration() { return []; }
274
+ /** Shared rows are the declared floor for every other connection — disable, never delete. */
275
+ async RetireObject(row) {
276
+ row.Status = 'Disabled';
277
+ return { ok: await row.Save(), deleted: false };
278
+ }
279
+ async RetireField(row) {
280
+ row.Status = 'Disabled';
281
+ return { ok: await row.Save(), deleted: false };
282
+ }
283
+ MarkSeen() {
284
+ /* the shared catalog has no seen timestamps */
285
+ }
286
+ }
287
+ /** One connection's own catalog. */
288
+ export class PerConnectionCatalogWriter {
289
+ constructor(md, companyIntegrationID, integrationID, contextUser,
290
+ /** Stamped on every row this run touches, so "when did we last see this" is answerable. */
291
+ seenAt) {
292
+ this.md = md;
293
+ this.companyIntegrationID = companyIntegrationID;
294
+ this.integrationID = integrationID;
295
+ this.contextUser = contextUser;
296
+ this.seenAt = seenAt;
297
+ this.Source = 'PerConnection';
298
+ }
299
+ ObjectsInScope() {
300
+ return viewRows(ENTITY_COMPANY_INTEGRATION_OBJECTS, `CompanyIntegrationID = '${EscapeSQLString(this.companyIntegrationID)}'`, this.contextUser, this.md, CATALOG_OBJECT_COLUMNS, null);
301
+ }
302
+ FieldsForObject(objectID) {
303
+ return viewRows(ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS, `CompanyIntegrationObjectID = '${EscapeSQLString(objectID)}'`, this.contextUser, this.md, CATALOG_FIELD_COLUMNS, FIELD_WRITE_ALIASES);
304
+ }
305
+ KeyedObjectIDs(objectIDs) {
306
+ return keyedOwnerIDs(ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS, 'CompanyIntegrationObjectID', objectIDs, this.contextUser, this.md);
307
+ }
308
+ NewObjectRow() {
309
+ return newRow(this.md, ENTITY_COMPANY_INTEGRATION_OBJECTS, this.contextUser, CATALOG_OBJECT_COLUMNS, null);
310
+ }
311
+ NewFieldRow() {
312
+ return newRow(this.md, ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS, this.contextUser, CATALOG_FIELD_COLUMNS, FIELD_WRITE_ALIASES);
313
+ }
314
+ LoadObject(id) {
315
+ return loadRow(this.md, ENTITY_COMPANY_INTEGRATION_OBJECTS, this.contextUser, id, CATALOG_OBJECT_COLUMNS, null);
316
+ }
317
+ LoadField(id) {
318
+ return loadRow(this.md, ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS, this.contextUser, id, CATALOG_FIELD_COLUMNS, FIELD_WRITE_ALIASES);
319
+ }
320
+ /**
321
+ * A new per-connection object records the connection it belongs to, the declared row it was
322
+ * matched to (null when the object exists only for this connection — the case the shared
323
+ * catalog cannot represent at all), where its shape came from, and when it was first seen.
324
+ *
325
+ * `IsSelected` starts FALSE. Catalog membership is not sync selection, and keeping them apart
326
+ * is the point of the table: conflating them is why a newly-discovered object arriving disabled
327
+ * disappeared from schema introspection, key inference and migration, with no error anywhere.
328
+ */
329
+ StampNewObject(row, declaredObjectID, provenance) {
330
+ const w = row;
331
+ w.CompanyIntegrationID = this.companyIntegrationID;
332
+ w.IntegrationID = this.integrationID;
333
+ w.IntegrationObjectID = declaredObjectID;
334
+ w.Provenance = provenance;
335
+ w.IsSelected = false;
336
+ w.FirstSeenAt = this.seenAt;
337
+ w.LastSeenAt = this.seenAt;
338
+ }
339
+ StampNewField(row, declaredFieldID, provenance) {
340
+ // Written through the raw column name: on the FIELD entity `IntegrationObjectFieldID` is a
341
+ // real provenance column, not one of the aliases above.
342
+ const w = row;
343
+ w.IntegrationObjectFieldID = declaredFieldID;
344
+ w.Provenance = provenance;
345
+ w.IsSelected = false;
346
+ w.FirstSeenAt = this.seenAt;
347
+ w.LastSeenAt = this.seenAt;
348
+ }
349
+ /**
350
+ * Copy the declared columns back over this connection's row so discovery overlays a CURRENT
351
+ * declaration rather than its own previous output. Returns the columns that actually moved,
352
+ * for the merge log. A row with no declared match (an object that exists only for this
353
+ * connection) has nothing to rebase from and is left alone.
354
+ */
355
+ RebaseFromDeclared(row, declared, kind) {
356
+ if (!declared)
357
+ return [];
358
+ const cols = kind === 'object' ? DECLARED_OWNED_OBJECT_COLUMNS : DECLARED_OWNED_FIELD_COLUMNS;
359
+ const target = row;
360
+ const source = declared;
361
+ const moved = [];
362
+ for (const c of cols) {
363
+ const next = source[c] ?? null;
364
+ if ((target[c] ?? null) === next)
365
+ continue;
366
+ target[c] = next;
367
+ moved.push(c);
368
+ }
369
+ return moved;
370
+ }
371
+ AdoptDeclaration(row, declared, kind) {
372
+ if (!declared)
373
+ return [];
374
+ const moved = this.RebaseFromDeclared(row, declared, kind);
375
+ const target = row;
376
+ const source = declared;
377
+ // Deliberately OUTSIDE the rebase. These three sit in NOT_DECLARED_OWNED because discovery
378
+ // owns them for a row discovery created — but a row that now has a declaration is not that
379
+ // row any more, and the seeding path in UpsertField/UpsertObject already stamps exactly
380
+ // these from the declaration when it creates one.
381
+ const link = kind === 'field' ? 'IntegrationObjectFieldID' : 'IntegrationObjectID';
382
+ for (const [col, next] of [
383
+ [link, declared.ID],
384
+ ['MetadataSource', source['MetadataSource'] ?? null],
385
+ ['IsCustom', source['IsCustom'] ?? null],
386
+ ['Provenance', 'Declared'],
387
+ ]) {
388
+ if ((target[col] ?? null) === (next ?? null))
389
+ continue;
390
+ target[col] = next;
391
+ moved.push(col);
392
+ }
393
+ return moved;
394
+ }
395
+ /**
396
+ * Delete, not disable — see the interface comment.
397
+ *
398
+ * Order matters and there is no ON DELETE CASCADE in the migration (deletes are deliberately
399
+ * explicit, so nothing disappears as a side effect of an unrelated write):
400
+ * 1. NULL out inbound dependency edges. `RelatedCompanyIntegrationObjectID` is self-
401
+ * referencing, so another object's field may point at this one; deleting underneath it
402
+ * would violate that FK and abort the whole persist. Nulling drops the edge and keeps the
403
+ * referencing field alive, which is right — the field still exists in the source, only
404
+ * the thing it pointed at is gone.
405
+ * 2. Delete this object's own fields (the FK child rows).
406
+ * 3. Delete the object.
407
+ */
408
+ async RetireObject(row) {
409
+ const inbound = await viewRows(ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS, `RelatedCompanyIntegrationObjectID = '${EscapeSQLString(row.ID)}'`, this.contextUser, this.md, CATALOG_FIELD_COLUMNS, FIELD_WRITE_ALIASES);
410
+ for (const edge of inbound) {
411
+ edge.RelatedCompanyIntegrationObjectID = null;
412
+ if (!(await edge.Save())) {
413
+ LogError(`[CatalogWriter] Could not clear dependency edge ${edge.ID} -> ${row.ID}; not deleting the object.`);
414
+ return { ok: false, deleted: false };
415
+ }
416
+ }
417
+ for (const child of await this.FieldsForObject(row.ID)) {
418
+ if (!(await child.Delete())) {
419
+ LogError(`[CatalogWriter] Could not delete field ${child.ID} of ${row.ID}; not deleting the object.`);
420
+ return { ok: false, deleted: false };
421
+ }
422
+ }
423
+ // `deleted` follows the delete: a refused delete is neither, so the caller's counts stay true.
424
+ const ok = await row.Delete();
425
+ return { ok, deleted: ok };
426
+ }
427
+ /**
428
+ * DISABLE, never delete — unlike the object above.
429
+ *
430
+ * The delete rule is dictated for TABLES and only tables: plan.md says "for tables only, if
431
+ * its not there after discovery algorithm, just removes it", and again "columns that are in
432
+ * MJC already never get removed, tables maybe if discovery objects doesnt find them, NEVER
433
+ * columns".
434
+ *
435
+ * The reason is in everything.txt: "sometimes, a column may be missing. If that is the case,
436
+ * then it doesnt automatically conclude the column no longer exist ... typically just may mean
437
+ * there is no more values". A column absent from one sample is absent from a SAMPLE, not from
438
+ * the source. Deleting the row destroys what only this connection knows about it — the
439
+ * observed width, the provenance, the selection state — so the next sample that does see it
440
+ * starts from nothing instead of reactivating. Disabling keeps all of it and reverses itself
441
+ * on rediscovery, which is what the shared catalog has always done.
442
+ *
443
+ * A field DOES get deleted when its OBJECT is removed; that cascade lives in RetireObject and
444
+ * is the table rule, not this one.
445
+ */
446
+ async RetireField(row) {
447
+ row.Status = 'Disabled';
448
+ return { ok: await row.Save(), deleted: false };
449
+ }
450
+ MarkSeen(row, sampled) {
451
+ const w = row;
452
+ w.LastSeenAt = this.seenAt;
453
+ if (sampled)
454
+ w.LastSampledAt = this.seenAt;
455
+ }
456
+ }
457
+ //# sourceMappingURL=CatalogWriter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CatalogWriter.js","sourceRoot":"","sources":["../src/CatalogWriter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,YAAY,EAA2C,QAAQ,EAAE,OAAO,EAA2B,MAAM,sBAAsB,CAAC;AAErJ,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EACH,qBAAqB,EACrB,sBAAsB,EAEtB,uCAAuC,EACvC,kCAAkC,EAClC,wCAAwC,EACxC,6BAA6B,EAC7B,4BAA4B,GAC/B,MAAM,yCAAyC,CAAC;AAEjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,gGAAgG;AAChG,MAAM,mBAAmB,GAAqC;IAC1D,8FAA8F;IAC9F,+FAA+F;IAC/F,6FAA6F;IAC7F,iFAAiF;IACjF,mBAAmB,EAAE,4BAA4B;IACjD,0BAA0B,EAAE,mCAAmC;CAClE,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,SAAS,QAAQ,CACb,GAAe,EACf,UAAkB,EAClB,QAAkC,EAClC,OAAgD;IAEhD,MAAM,OAAO,GAAG,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IACxF,IAAI,QAAQ,KAAK,IAAI,IA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AAC,EAAE,OAAO,GAAG,CAAC,EAAE,4BAA4B,CAAC,CAAC;gBACtG,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;YACzC,CAAC;QACL,CAAC;QACD,+FAA+F;QAC/F,MAAM,EAAE,GAAG,MAAM,GAAG,CAAC,MAAM,EAAE,CAAC;QAC9B,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IAC/B,CAAC;IAED;;;;;;;;;;;;;;;;;;OAkBG;IACI,KAAK,CAAC,WAAW,CAAC,GAAmC;QACxD,GAAG,CAAC,MAAM,GAAG,UAAU,CAAC;QACxB,OAAO,EAAE,EAAE,EAAE,MAAM,GAAG,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IACpD,CAAC;IAEM,QAAQ,CAAC,GAA+D,EAAE,OAAgB;QAC7F,MAAM,CAAC,GAAG,GAAyC,CAAC;QACpD,CAAC,CAAC,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,IAAI,OAAO;YAAE,CAAC,CAAC,aAAa,GAAG,IAAI,CAAC,MAAM,CAAC;IAC/C,CAAC;CACJ"}
@@ -0,0 +1,109 @@
1
+ import { BaseEntity, IMetadataProvider, UserInfo } from '@memberjunction/core';
2
+ import { ENTITY_COMPANY_INTEGRATION_OBJECTS, ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS } from '@memberjunction/integration-engine-base';
3
+ /**
4
+ * The ONLY write path to the per-connection catalog.
5
+ *
6
+ * These two entities have no generated subclass — deliberately, because generating one means
7
+ * patching a file with thousands of classes in it, and the patch would have to be regenerated on
8
+ * every upstream release. The consequence is a trap with no natural symptom:
9
+ *
10
+ * const row = await md.GetEntityObject('MJ: Company Integration Objects', user);
11
+ * row.Name = 'Contacts'; // creates an own property on a plain object
12
+ * await row.Save(); // succeeds, writes nothing, reports success
13
+ *
14
+ * There is no accessor to intercept the assignment, so the value lands beside the entity's field
15
+ * list instead of in it, the row saves clean, and the column keeps whatever it had. Nothing throws
16
+ * and nothing logs. In a discovery that persists hundreds of rows this reads as a source that
17
+ * returned less than expected.
18
+ *
19
+ * So this wrapper exists, and every write in the engine goes through it. `Set` refuses a column
20
+ * name the entity does not have, which turns that silent no-op into an immediate, named error.
21
+ */
22
+ type CatalogEntityName = typeof ENTITY_COMPANY_INTEGRATION_OBJECTS | typeof ENTITY_COMPANY_INTEGRATION_OBJECT_FIELDS;
23
+ /**
24
+ * A per-connection catalog row, writable only through `Set`.
25
+ *
26
+ * Note `IntegrationObjectID` is virtual on the FIELD entity (a view alias) and REAL on the OBJECT
27
+ * entity (the provenance foreign key). `Set` resolves that from the row's own field list rather
28
+ * than from the name, so the object's provenance link stays writable and the field's alias does
29
+ * not.
30
+ */
31
+ export declare class CatalogRow {
32
+ private readonly entityName;
33
+ private readonly row;
34
+ private constructor();
35
+ /** @internal */
36
+ static Wrap(entityName: CatalogEntityName, row: BaseEntity): CatalogRow;
37
+ get ID(): string;
38
+ /** The underlying row, for a caller that needs to enlist it in a transaction group. */
39
+ get Entity(): BaseEntity;
40
+ Get<T = unknown>(column: string): T;
41
+ /**
42
+ * Write one column.
43
+ *
44
+ * Throws on a column the entity does not have and on a view alias, because both would otherwise
45
+ * be accepted and discarded. That is the whole point of this class: the failure is loud, at the
46
+ * assignment, naming the column.
47
+ */
48
+ Set(column: string, value: unknown): this;
49
+ /** Set several columns. Skips `undefined` so a caller can pass a sparse patch. */
50
+ SetMany(values: Record<string, unknown>): this;
51
+ Save(): Promise<boolean>;
52
+ Delete(): Promise<boolean>;
53
+ /** The row's own error text after a failed Save, for logging. */
54
+ get LastError(): string;
55
+ }
56
+ /** Reads and writes for the per-connection catalog. */
57
+ export declare class CompanyIntegrationCatalogStore {
58
+ private readonly contextUser;
59
+ private readonly provider?;
60
+ /** `provider` is the caller's bound provider; without one the store uses the default. */
61
+ constructor(contextUser: UserInfo, provider?: IMetadataProvider);
62
+ private get md();
63
+ private newRow;
64
+ NewObject(): Promise<CatalogRow>;
65
+ NewField(): Promise<CatalogRow>;
66
+ private loadRow;
67
+ LoadObject(id: string): Promise<CatalogRow | null>;
68
+ LoadField(id: string): Promise<CatalogRow | null>;
69
+ /**
70
+ * Read straight from the database rather than the engine cache — and around the query-result
71
+ * cache too.
72
+ *
73
+ * Used by the write path, which must see rows another pass of the same run just persisted. The
74
+ * engine cache is refreshed between passes, not within one.
75
+ *
76
+ * `BypassCache` is load-bearing, not a tuning knob. The query-result cache is keyed by the exact
77
+ * query text and filled by whoever asks first. Within one discovery that is Introspect, which
78
+ * asks for an object's fields BEFORE Persist has written any, so the cached answer is the empty
79
+ * set; Persist writes the rows; the reads after it issue the byte-identical query and are handed
80
+ * that empty answer. These entities are registered by a migration rather than CodeGen, so
81
+ * nothing invalidates the entry when the rows are saved, and where the cache is shared and
82
+ * external to the process a restart does not clear it either. Observed 2026-09-27: a discovery
83
+ * skipped all 34 objects for having no primary key although the 30 declared ones each had one;
84
+ * on another tenant, fetches aborted reporting "no columns persisted" for objects holding 41,
85
+ * 81, 31 and 704 persisted fields.
86
+ */
87
+ private runView;
88
+ /**
89
+ * A RunView on the store's provider — the one its writes use — so a server with more than one
90
+ * provider never reads from one and writes to another. Server-side providers are
91
+ * DatabaseProviderBase (an IRunViewProvider), which the IMetadataProvider type does not declare;
92
+ * same narrowing as CatalogWriter.
93
+ */
94
+ private newRunView;
95
+ /**
96
+ * Every object row for a connection, INCLUDING disabled ones.
97
+ *
98
+ * Disabled rows are load-bearing here: the overlay reactivates an object that reappeared rather
99
+ * than inserting a second one, and the unique constraint on (connection, name) means matching
100
+ * active rows only would turn a reappearance into a constraint violation.
101
+ */
102
+ ObjectsForConnection(companyIntegrationID: string): Promise<CatalogRow[]>;
103
+ /** Every field row for one object, including disabled ones, for the same reason. */
104
+ FieldsForObject(companyIntegrationObjectID: string): Promise<CatalogRow[]>;
105
+ /** Whether this connection has a per-connection catalog at all. Cheap existence check. */
106
+ HasCatalog(companyIntegrationID: string): Promise<boolean>;
107
+ }
108
+ export {};
109
+ //# sourceMappingURL=CompanyIntegrationCatalogStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CompanyIntegrationCatalogStore.d.ts","sourceRoot":"","sources":["../src/CompanyIntegrationCatalogStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAsC,iBAAiB,EAAqB,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAEtI,OAAO,EAIH,kCAAkC,EAClC,wCAAwC,EAC3C,MAAM,yCAAyC,CAAC;AAGjD;;;;;;;;;;;;;;;;;;GAkBG;AAEH,KAAK,iBAAiB,GAChB,OAAO,kCAAkC,GACzC,OAAO,wCAAwC,CAAC;AA0CtD;;;;;;;GAOG;AACH,qBAAa,UAAU;IAEf,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,GAAG;IAFxB,OAAO;IAKP,gBAAgB;WACF,IAAI,CAAC,UAAU,EAAE,iBAAiB,EAAE,GAAG,EAAE,UAAU,GAAG,UAAU;IAK9E,IAAW,EAAE,IAAI,MAAM,CAEtB;IAED,uFAAuF;IACvF,IAAW,MAAM,IAAI,UAAU,CAE9B;IAEM,GAAG,CAAC,CAAC,GAAG,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,CAAC;IAI1C;;;;;;OAMG;IACI,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAmBhD,kFAAkF;IAC3E,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAKxC,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC;IAIxB,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC;IAIvC,iEAAiE;IACjE,IAAW,SAAS,IAAI,MAAM,CAI7B;CACJ;AAED,uDAAuD;AACvD,qBAAa,8BAA8B;IAE3B,OAAO,CAAC,QAAQ,CAAC,WAAW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