@memberjunction/record-graph 0.0.1-seed.1 → 6.2.0-edge.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,183 @@
1
+ Business Source License 1.1
2
+
3
+ License text copyright (c) 2024 MariaDB plc, All Rights Reserved.
4
+ "Business Source License" is a trademark of MariaDB plc.
5
+
6
+ -----------------------------------------------------------------------------
7
+
8
+ Parameters
9
+
10
+ Licensor: Blue Cypress, Inc.
11
+
12
+ Licensed Work: MemberJunction.
13
+ The Licensed Work is (c) 2023-2026 Blue Cypress, Inc.
14
+
15
+ Additional Use Grant: Subject to the terms of this License, Licensor grants
16
+ you the following additional rights to make Production
17
+ Use of the Licensed Work.
18
+
19
+ 1. Internal Use
20
+
21
+ You may make production use of the Licensed Work for
22
+ your own internal business or organizational operations.
23
+
24
+ 2. Nonprofit Use
25
+
26
+ If you are a Nonprofit, you may make production use of
27
+ the Licensed Work for the operations and activities of
28
+ your Organizational Family.
29
+
30
+ 3. MemberJunction Certified Program Use
31
+
32
+ If you are authorized by Licensor under the
33
+ MemberJunction Certified Program to provide professional
34
+ services using the Licensed Work, you may make
35
+ production use of the Licensed Work in providing such
36
+ professional services to a client, provided that:
37
+
38
+ (a) the Licensed Work is deployed in, and the applicable
39
+ production use occurs within, an environment owned,
40
+ leased, licensed, subscribed to, or otherwise controlled
41
+ by that client; and
42
+
43
+ (b) the production use is for that client's own internal
44
+ business or organizational operations or is otherwise
45
+ independently permitted to that client under this
46
+ Additional Use Grant.
47
+
48
+ 4. Definitions Applicable to the Additional Use Grant
49
+
50
+ "Affiliate" means, with respect to a specified Person,
51
+ any other Person that directly or indirectly Controls,
52
+ is Controlled by, or is under common Control with such
53
+ specified Person.
54
+
55
+ "Control" (including the terms "Controls," "Controlled
56
+ by," and "under common Control with") means the direct
57
+ or indirect possession of the power to direct or cause
58
+ the direction of the management and policies of a
59
+ Person, whether through ownership of voting interests,
60
+ by contract, or otherwise.
61
+
62
+ "Organizational Family" means, with respect to a Person,
63
+ (a) such Person and its Affiliates, and (b) any
64
+ nonprofit organization, governmental entity, chapter,
65
+ division, local affiliate, regional affiliate, state
66
+ affiliate, national affiliate, or other entity that is
67
+ formally affiliated with such Person through governing
68
+ documents, a charter, bylaws, a membership agreement, or
69
+ another written organizational instrument, and is
70
+ recognized under such documents as part of the same
71
+ organizational structure.
72
+
73
+ "Nonprofit" means a Person recognized by the Internal
74
+ Revenue Service as exempt from federal income taxation
75
+ under Section 501(c)(3), 501(c)(4), 501(c)(5), or
76
+ 501(c)(6) of the Internal Revenue Code, or a foreign
77
+ organization recognized under substantially equivalent
78
+ laws.
79
+
80
+ A Person claiming eligibility as a Nonprofit shall, upon
81
+ Licensor's reasonable request, provide documentation
82
+ reasonably sufficient to demonstrate that it qualifies
83
+ as a Nonprofit. If such Person materially misrepresents,
84
+ or is unable to demonstrate, its qualification as a
85
+ Nonprofit, the rights granted to such Person under
86
+ Section 2 of this Additional Use Grant shall terminate.
87
+
88
+ "MemberJunction Certified Program" means Licensor's
89
+ then-current program for certifying and authorizing a
90
+ Person to provide professional services using the
91
+ Licensed Work.
92
+
93
+ "Person" means any individual, corporation, limited
94
+ liability company, partnership, association, nonprofit
95
+ organization, governmental entity, or other legal or
96
+ organizational entity.
97
+
98
+ Change Date: Four (4) years from the date the Licensed Work is first
99
+ made available.
100
+
101
+ Change License: MIT License.
102
+
103
+ For information about alternative licensing arrangements for the Licensed
104
+ Work, please contact Blue Cypress, Inc.
105
+
106
+ -----------------------------------------------------------------------------
107
+
108
+ Terms
109
+
110
+ The Licensor hereby grants you the right to copy, modify, create derivative
111
+ works, redistribute, and make non-production use of the Licensed Work. The
112
+ Licensor may make an Additional Use Grant, above, permitting limited
113
+ production use.
114
+
115
+ Effective on the Change Date, or the fourth anniversary of the first publicly
116
+ available distribution of a specific version of the Licensed Work under this
117
+ License, whichever comes first, the Licensor hereby grants you rights under
118
+ the terms of the Change License, and the rights granted in the paragraph
119
+ above terminate.
120
+
121
+ If your use of the Licensed Work does not comply with the requirements
122
+ currently in effect as described in this License, you must purchase a
123
+ commercial license from the Licensor, its affiliated entities, or authorized
124
+ resellers, or you must refrain from using the Licensed Work.
125
+
126
+ All copies of the original and modified Licensed Work, and derivative works
127
+ of the Licensed Work, are subject to this License. This License applies
128
+ separately for each version of the Licensed Work and the Change Date may vary
129
+ for each version of the Licensed Work released by Licensor.
130
+
131
+ You must conspicuously display this License on each original or modified copy
132
+ of the Licensed Work. If you receive the Licensed Work in original or
133
+ modified form from a third party, the terms and conditions set forth in this
134
+ License apply to your use of that work.
135
+
136
+ Any use of the Licensed Work in violation of this License will automatically
137
+ terminate your rights under this License for the current and all other
138
+ versions of the Licensed Work.
139
+
140
+ This License does not grant you any right in any trademark or logo of
141
+ Licensor or its affiliates (provided that you may use a trademark or logo of
142
+ Licensor as expressly required by this License).
143
+
144
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
145
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
146
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
147
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
148
+ TITLE.
149
+
150
+ MariaDB hereby grants you permission to use this License's text to license
151
+ your works, and to refer to it using the trademark "Business Source License",
152
+ as long as you comply with the Covenants of Licensor below.
153
+
154
+ -----------------------------------------------------------------------------
155
+
156
+ Covenants of Licensor
157
+
158
+ In consideration of the right to use this License's text and the "Business
159
+ Source License" name and trademark, Licensor covenants to MariaDB, and to all
160
+ other recipients of the licensed work to be provided by Licensor:
161
+
162
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
163
+ or a license that is compatible with GPL Version 2.0 or a later version,
164
+ where "compatible" means that software provided under the Change License
165
+ can be included in a program with software provided under GPL Version 2.0
166
+ or a later version. Licensor may specify additional Change Licenses without
167
+ limitation.
168
+
169
+ 2. To either: (a) specify an additional grant of rights to use that does not
170
+ impose any additional restriction on the right granted in this License, as
171
+ the Additional Use Grant; or (b) insert the text "None".
172
+
173
+ 3. To specify a Change Date.
174
+
175
+ 4. Not to modify this License in any other way.
176
+
177
+ -----------------------------------------------------------------------------
178
+
179
+ Notice
180
+
181
+ The Business Source License (this document, or the "License") is not an Open
182
+ Source license. However, the Licensed Work will eventually be made available
183
+ under an Open Source License, as stated in this License.
package/README.md CHANGED
@@ -1,4 +1,88 @@
1
1
  # @memberjunction/record-graph
2
- Seed release published over OIDC to prove trusted publishing is configured for
3
- this package. It contains no code and is tagged `seed`, never `latest`.
4
- Real releases are published by .github/workflows/publish.yml.
2
+
3
+ Generalized record dependency graph traversal, relationship collection resolution, topological sorting, link value encoding, and graph models for MemberJunction.
4
+
5
+ Shared across:
6
+ - **Version History**: Snapshot creation, dependency tracking, rollback / restore topological ordering.
7
+ - **Record Cloning**: Deep copying of record graphs, subtype rows, child collections, and soft-link rewriting.
8
+ - **Metadata Sync**: Deterministic 4-tier collection resolution and schema composition.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install @memberjunction/record-graph
14
+ ```
15
+
16
+ ## Key Components
17
+
18
+ ### 1. `DependencyGraphWalker`
19
+
20
+ Walks an entity record's relationships to discover all dependent and referenced records.
21
+
22
+ ```typescript
23
+ import { CompositeKey } from '@memberjunction/core';
24
+ import { DependencyGraphWalker } from '@memberjunction/record-graph';
25
+
26
+ const walker = new DependencyGraphWalker(provider); // provider is optional; defaults to Metadata.Provider
27
+ const userKey = CompositeKey.FromID(userId);
28
+ const rootNode = await walker.WalkDependents(
29
+ 'MJ: Users',
30
+ userKey,
31
+ {
32
+ MaxDepth: 3,
33
+ RequireTrackRecordChanges: false, // Set false for cloning, true for Version History
34
+ IncludeSubtypes: true, // Include IS-A subtype rows
35
+ FollowHierarchies: true, // Recurse self-referencing hierarchy fields
36
+ EdgePolicy: (candidate) => {
37
+ if (candidate.TargetEntityName === 'MJ: Audit Logs') return 'Skip';
38
+ if (candidate.Kind === 'ForwardFK') return 'Reference';
39
+ return 'Deep';
40
+ },
41
+ },
42
+ contextUser
43
+ );
44
+
45
+ const flatNodes = walker.FlattenTopological(rootNode);
46
+ ```
47
+
48
+ #### Traversal Rules & Discovery Modes
49
+
50
+ - **Reverse Walk (Owned Children)**: Curated One-To-Many relationships (`EntityRelationshipInfo`) are walked with full discovery (both reverse and forward), discovering all dependent child records.
51
+ - **Forward Walk (Referenced Records)**: Foreign key fields are walked in `forward-only` mode so referenced entities (e.g., shared lookup tables) do not traverse their own children, preventing graph explosion.
52
+ - **Subtypes (`IncludeSubtypes`)**: Discovers IS-A subtype rows via `FindISAChildEntities`.
53
+ - **Hierarchies (`FollowHierarchies`)**: Allows controlled recursion on fields whose `Configuration.Hierarchy.IsHierarchy` is true.
54
+ - **Soft Links (`IncludeSoftLinks`)**: Traverses polymorphic `EntityID`/`RecordID` pairs via `EntityIDFieldName`.
55
+ - **Non-Curated Inbound FKs (`ListNonCuratedInbound`)**: Discovers database foreign keys pointing to the record that lack a curated `EntityRelationship`.
56
+ - **Edge Policy (`EdgePolicy`)**: Pre-traversal callback returning `'Deep'`, `'Reference'`, or `'Skip'`.
57
+ - **Cycle Prevention**: Global `visited` set and entity-type `ancestorStack` to prevent infinite loops and backtracking.
58
+
59
+ ### 2. Topological Sorting (`sort.ts`)
60
+
61
+ - `SortByEntityDependencyOrder<T>(items, getEntityID, provider?)`:
62
+ Computes DAG levels from foreign keys and sorts parent entities before child entities. Handles cycles safely.
63
+ - `SortEntitiesByDependency`:
64
+ Backward-compatible alias for `SortByEntityDependencyOrder`.
65
+ - `SortNodesTopologically(root: DependencyNode)`:
66
+ Breadth-first traversal flattening a dependency tree into an execution-safe array where parents precede children.
67
+
68
+ ### 3. Link Value Encoding (`links.ts`)
69
+
70
+ - `ResolveLinkValue(kindOrIsSoft, targetKey)`:
71
+ Resolves the value to write into a pointer or foreign key column:
72
+ - Hard link (`'hard'` or `false`): bare primary key value (`targetKey.GetValueByIndex(0)`).
73
+ - Soft link (`'soft'` or `true`): canonical prefixed polymorphic encoding (`targetKey.ToRecordID()`).
74
+
75
+ ### 4. Collection Resolver (`collection-resolver.ts`)
76
+
77
+ - `ResolveCollectionRelationship(entityInfo, colName)` (`resolveCollectionRelationship` is a deprecated alias):
78
+ Resolves a collection name to its matching relationship on the entity using strict 4-tier rule strength:
79
+ 1. Explicit collection name in `RelatedRecordCollection` JSON (`"Name": "..."`)
80
+ 2. Relationship `DisplayName`
81
+ 3. `RelatedEntity` full name
82
+ 4. Stripped `RelatedEntity` name (with singular/plural tolerance)
83
+
84
+ ### 5. SQL & Key Utilities (`sql.ts`, `keys.ts`)
85
+
86
+ - `SqlEquals`, `SqlContains`, `SqlIn`, `SqlNotIn`: Safe SQL filter builders (they escape with `EscapeSQLString` from `@memberjunction/global`).
87
+ - `BuildCompositeKeyFromRecord`, `BuildPrimaryKeyForLoad`, `BuildIdKey`: CompositeKey construction utilities.
88
+ - The camelCase names (`sqlEquals`, `buildIdKey`, …) and `escapeSqlString` are deprecated aliases. Use `EscapeSQLString` from `@memberjunction/global` directly.
@@ -0,0 +1,129 @@
1
+ import { CompositeKey, EntityInfo, IMetadataProvider, UserInfo } from '@memberjunction/core';
2
+ import { DependencyNode, WalkOptions } from './types.js';
3
+ /**
4
+ * Extended metadata provider interface with optional FindISAChildEntities
5
+ */
6
+ interface IExtendedMetadataProvider extends IMetadataProvider {
7
+ FindISAChildEntities?(entityInfo: EntityInfo, recordPKValue: string, contextUser?: UserInfo): Promise<{
8
+ ChildEntityName: string;
9
+ }[]>;
10
+ }
11
+ /**
12
+ * Walks a record's relationship graph to discover all dependent and referenced records.
13
+ *
14
+ * Traversal rules:
15
+ * - Reverse walk: follows curated One-To-Many relationships (where child points to parent).
16
+ * Recurses with 'full' mode (both reverse + forward).
17
+ * - Forward walk: follows foreign keys on the parent (where parent points to another entity).
18
+ * Recurses with 'forward-only' mode — targets do NOT discover their own reverse children,
19
+ * preventing graph explosion from shared/hub entities.
20
+ * - Subtypes: follows IS-A inheritance if IncludeSubtypes is true.
21
+ * - Hierarchies: follows self-referencing hierarchy FKs if FollowHierarchies is true.
22
+ * - Soft links: follows inbound polymorphic EntityID/RecordID links if IncludeSoftLinks is true.
23
+ * - Non-curated inbound FKs: discovers non-curated inbound FKs if ListNonCuratedInbound is true.
24
+ * - EdgePolicy: callers can supply an EdgePolicy callback to dictate Deep / Reference / Skip per edge.
25
+ * - Cycle prevention: uses ancestorStack (entity types) to prevent backtracking and a global visited set (records).
26
+ */
27
+ export declare class DependencyGraphWalker {
28
+ /** Cache: entityID → reverse relationships from EntityRelationship metadata */
29
+ private reverseRelCache;
30
+ /** Cache: entityID → forward FK references from field metadata */
31
+ private forwardRefCache;
32
+ /** Optional provider override; falls back to Metadata.Provider when not set. */
33
+ private _provider?;
34
+ constructor(provider?: IMetadataProvider);
35
+ /** Returns the active provider — explicit override if set, otherwise the global default. */
36
+ protected get ProviderToUse(): IExtendedMetadataProvider;
37
+ /**
38
+ * Walk from a root record through its relationships, building a tree of
39
+ * all records that should be included in a version label or clone plan.
40
+ *
41
+ * @param entityName - The starting entity name
42
+ * @param recordKey - The starting record's primary key
43
+ * @param options - Controls depth, filtering, policies, etc.
44
+ * @param contextUser - Server-side user context
45
+ * @returns The root DependencyNode with all descendants populated
46
+ */
47
+ WalkDependents(entityName: string, recordKey: CompositeKey, options: WalkOptions, contextUser: UserInfo): Promise<DependencyNode>;
48
+ /**
49
+ * Flatten a dependency tree into a topologically sorted list.
50
+ * Parents appear before their children, ensuring safe restore or clone execution ordering.
51
+ */
52
+ FlattenTopological(root: DependencyNode): DependencyNode[];
53
+ /**
54
+ * Recursively discover and attach child nodes for a given parent node.
55
+ */
56
+ private walkChildren;
57
+ /**
58
+ * Walk reverse relationships: for each EntityRelationship on the parent
59
+ * entity, load matching child records and recurse into them.
60
+ */
61
+ private walkReverseRelationships;
62
+ /**
63
+ * Discovers inbound foreign keys that are not registered as curated EntityRelationships.
64
+ * Evaluated when ListNonCuratedInbound is true.
65
+ */
66
+ private walkNonCuratedInbound;
67
+ /**
68
+ * Discovers records pointing to the parent via polymorphic EntityID/RecordID soft links.
69
+ */
70
+ private walkSoftLinks;
71
+ /**
72
+ * Discover and attach IS-A subtype rows for a given parent record.
73
+ */
74
+ private walkSubtypes;
75
+ /**
76
+ * Walk forward FK references: for each FK field on the parent entity that
77
+ * points to another entity, load the referenced record and recurse.
78
+ */
79
+ private walkForwardReferences;
80
+ /**
81
+ * Discover reverse relationships for an entity using EntityRelationship metadata.
82
+ */
83
+ private discoverReverseRelationships;
84
+ /**
85
+ * Discover forward FK references on an entity.
86
+ */
87
+ private discoverForwardReferences;
88
+ /**
89
+ * Load child records for a reverse relationship.
90
+ */
91
+ private loadChildRecords;
92
+ /**
93
+ * Load a single record's data by primary key.
94
+ */
95
+ private loadRecordData;
96
+ /**
97
+ * Build a DependencyNode from record data, register it in the visited set,
98
+ * and attach it as a child of the parent. Returns null if already visited.
99
+ */
100
+ private registerNode;
101
+ /** Create an empty stats accumulator. */
102
+ private createEmptyStats;
103
+ /** Increment the per-entity record counter. */
104
+ private incrementEntityCount;
105
+ /**
106
+ * Log a detailed summary of the walk.
107
+ */
108
+ private logWalkSummary;
109
+ /** Build a unique key for the visited set: "EntityName::recordID" */
110
+ private visitKey;
111
+ /**
112
+ * Determine the parent key field from an EntityRelationship record.
113
+ */
114
+ private resolveParentKeyFieldFromRelationship;
115
+ /**
116
+ * Determine the target key field from a FK field definition.
117
+ */
118
+ private resolveParentKeyFieldFromFK;
119
+ /** Check if a field name matches a system/infrastructure FK pattern. */
120
+ private isSystemFKField;
121
+ /** Check if an entity should be skipped based on filter options. */
122
+ private shouldSkipEntity;
123
+ /** Check if an entity has a soft delete field. */
124
+ private entityHasSoftDelete;
125
+ /** Apply defaults to walk options. */
126
+ private resolveDefaults;
127
+ }
128
+ export {};
129
+ //# sourceMappingURL=DependencyGraphWalker.d.ts.map
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