@memberjunction/ng-react 2.95.0 → 2.96.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/components/mj-react-component.component.d.ts +2 -1
- package/dist/lib/components/mj-react-component.component.js +28 -9
- package/dist/lib/components/mj-react-component.component.js.map +1 -1
- package/dist/lib/services/angular-adapter.service.d.ts +4 -1
- package/dist/lib/services/angular-adapter.service.js +5 -5
- package/dist/lib/services/angular-adapter.service.js.map +1 -1
- package/dist/lib/services/react-bridge.service.d.ts +1 -0
- package/dist/lib/services/react-bridge.service.js +13 -4
- package/dist/lib/services/react-bridge.service.js.map +1 -1
- package/dist/lib/services/script-loader.service.d.ts +4 -1
- package/dist/lib/services/script-loader.service.js +3 -2
- package/dist/lib/services/script-loader.service.js.map +1 -1
- package/dist/lib/utilities/runtime-utilities.d.ts +2 -1
- package/dist/lib/utilities/runtime-utilities.js +46 -1
- package/dist/lib/utilities/runtime-utilities.js.map +1 -1
- package/dist/public-api.d.ts +0 -1
- package/dist/public-api.js +0 -2
- package/dist/public-api.js.map +1 -1
- package/package.json +4 -4
- package/dist/lib/default-styles.d.ts +0 -10
- package/dist/lib/default-styles.js +0 -106
- package/dist/lib/default-styles.js.map +0 -1
|
@@ -41,6 +41,7 @@ export declare class MJReactComponent implements AfterViewInit, OnDestroy {
|
|
|
41
41
|
private adapter;
|
|
42
42
|
private cdr;
|
|
43
43
|
component: ComponentSpec;
|
|
44
|
+
debug: boolean;
|
|
44
45
|
private _utilities;
|
|
45
46
|
set utilities(value: any);
|
|
46
47
|
get utilities(): any;
|
|
@@ -192,5 +193,5 @@ export declare class MJReactComponent implements AfterViewInit, OnDestroy {
|
|
|
192
193
|
*/
|
|
193
194
|
static forceClearRegistries(): void;
|
|
194
195
|
static ɵfac: i0.ɵɵFactoryDeclaration<MJReactComponent, never>;
|
|
195
|
-
static ɵcmp: i0.ɵɵComponentDeclaration<MJReactComponent, "mj-react-component", never, { "component": { "alias": "component"; "required": false; }; "utilities": { "alias": "utilities"; "required": false; }; "styles": { "alias": "styles"; "required": false; }; "savedUserSettings": { "alias": "savedUserSettings"; "required": false; }; }, { "stateChange": "stateChange"; "componentEvent": "componentEvent"; "refreshData": "refreshData"; "openEntityRecord": "openEntityRecord"; "userSettingsChanged": "userSettingsChanged"; }, never, never, false, never>;
|
|
196
|
+
static ɵcmp: i0.ɵɵComponentDeclaration<MJReactComponent, "mj-react-component", never, { "component": { "alias": "component"; "required": false; }; "debug": { "alias": "debug"; "required": false; }; "utilities": { "alias": "utilities"; "required": false; }; "styles": { "alias": "styles"; "required": false; }; "savedUserSettings": { "alias": "savedUserSettings"; "required": false; }; }, { "stateChange": "stateChange"; "componentEvent": "componentEvent"; "refreshData": "refreshData"; "openEntityRecord": "openEntityRecord"; "userSettingsChanged": "userSettingsChanged"; }, never, never, false, never>;
|
|
196
197
|
}
|
|
@@ -37,8 +37,10 @@ export class MJReactComponent {
|
|
|
37
37
|
// Lazy initialization - only create default utilities when needed
|
|
38
38
|
if (!this._utilities) {
|
|
39
39
|
const runtimeUtils = createRuntimeUtilities();
|
|
40
|
-
this._utilities = runtimeUtils.buildUtilities();
|
|
41
|
-
|
|
40
|
+
this._utilities = runtimeUtils.buildUtilities(this.debug);
|
|
41
|
+
if (this.debug) {
|
|
42
|
+
console.log('MJReactComponent: Auto-initialized utilities using createRuntimeUtilities()');
|
|
43
|
+
}
|
|
42
44
|
}
|
|
43
45
|
return this._utilities;
|
|
44
46
|
}
|
|
@@ -49,7 +51,9 @@ export class MJReactComponent {
|
|
|
49
51
|
// Lazy initialization - only create default styles when needed
|
|
50
52
|
if (!this._styles) {
|
|
51
53
|
this._styles = SetupStyles();
|
|
52
|
-
|
|
54
|
+
if (this.debug) {
|
|
55
|
+
console.log('MJReactComponent: Auto-initialized styles using SetupStyles()');
|
|
56
|
+
}
|
|
53
57
|
}
|
|
54
58
|
return this._styles;
|
|
55
59
|
}
|
|
@@ -67,6 +71,7 @@ export class MJReactComponent {
|
|
|
67
71
|
this.reactBridge = reactBridge;
|
|
68
72
|
this.adapter = adapter;
|
|
69
73
|
this.cdr = cdr;
|
|
74
|
+
this.debug = true;
|
|
70
75
|
this._savedUserSettings = {};
|
|
71
76
|
this.stateChange = new EventEmitter();
|
|
72
77
|
this.componentEvent = new EventEmitter();
|
|
@@ -87,6 +92,8 @@ export class MJReactComponent {
|
|
|
87
92
|
this.componentId = `mj-react-component-${Date.now()}-${Math.random()}`;
|
|
88
93
|
}
|
|
89
94
|
async ngAfterViewInit() {
|
|
95
|
+
// Set debug flag on the bridge service
|
|
96
|
+
this.reactBridge.debug = this.debug;
|
|
90
97
|
// Trigger change detection to show loading state
|
|
91
98
|
this.cdr.detectChanges();
|
|
92
99
|
await this.initializeComponent();
|
|
@@ -192,11 +199,15 @@ export class MJReactComponent {
|
|
|
192
199
|
async resolveComponentsWithVersion(spec, version, namespace = 'Global') {
|
|
193
200
|
const resolver = this.adapter.getResolver();
|
|
194
201
|
// Debug: Log what dependencies we're trying to resolve
|
|
195
|
-
|
|
202
|
+
if (this.debug) {
|
|
203
|
+
console.log(`Resolving components for ${spec.name}. Dependencies:`, spec.dependencies);
|
|
204
|
+
}
|
|
196
205
|
// Use the runtime's resolver which now handles registry-based components
|
|
197
206
|
const resolved = await resolver.resolveComponents(spec, namespace, Metadata.Provider.CurrentUser // Pass current user context for database operations
|
|
198
207
|
);
|
|
199
|
-
|
|
208
|
+
if (this.debug) {
|
|
209
|
+
console.log(`Resolved ${Object.keys(resolved).length} components for version ${version}:`, Object.keys(resolved));
|
|
210
|
+
}
|
|
200
211
|
return resolved;
|
|
201
212
|
}
|
|
202
213
|
/**
|
|
@@ -206,12 +217,16 @@ export class MJReactComponent {
|
|
|
206
217
|
// Use semantic version from spec or generate hash-based version for uniqueness
|
|
207
218
|
const version = this.component.version || this.generateComponentHash(this.component);
|
|
208
219
|
this.componentVersion = version; // Store for use in resolver
|
|
209
|
-
|
|
220
|
+
if (this.debug) {
|
|
221
|
+
console.log(`Registering ${this.component.name}@${version}`);
|
|
222
|
+
}
|
|
210
223
|
// Check if already registered to avoid duplication
|
|
211
224
|
const registry = this.adapter.getRegistry();
|
|
212
225
|
const existingComponent = registry.get(this.component.name, this.component.namespace || 'Global', version);
|
|
213
226
|
if (existingComponent) {
|
|
214
|
-
|
|
227
|
+
if (this.debug) {
|
|
228
|
+
console.log(`Component ${this.component.name}@${version} already registered`);
|
|
229
|
+
}
|
|
215
230
|
return;
|
|
216
231
|
}
|
|
217
232
|
// Initialize metadata engine
|
|
@@ -230,7 +245,9 @@ export class MJReactComponent {
|
|
|
230
245
|
const errors = result.errors.map(e => e.error).join(', ');
|
|
231
246
|
throw new Error(`Component registration failed: ${errors}`);
|
|
232
247
|
}
|
|
233
|
-
|
|
248
|
+
if (this.debug) {
|
|
249
|
+
console.log(`Registered ${result.registeredComponents.length} components`);
|
|
250
|
+
}
|
|
234
251
|
}
|
|
235
252
|
/**
|
|
236
253
|
* Render the React component
|
|
@@ -571,7 +588,7 @@ export class MJReactComponent {
|
|
|
571
588
|
} if (rf & 2) {
|
|
572
589
|
let _t;
|
|
573
590
|
i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.container = _t.first);
|
|
574
|
-
} }, inputs: { component: "component", utilities: "utilities", styles: "styles", savedUserSettings: "savedUserSettings" }, outputs: { stateChange: "stateChange", componentEvent: "componentEvent", refreshData: "refreshData", openEntityRecord: "openEntityRecord", userSettingsChanged: "userSettingsChanged" }, decls: 4, vars: 3, consts: [["container", ""], [1, "react-component-wrapper"], [1, "react-component-container"], [1, "loading-overlay"], [1, "loading-spinner"], [1, "fa-solid", "fa-spinner", "fa-spin"], [1, "loading-text"]], template: function MJReactComponent_Template(rf, ctx) { if (rf & 1) {
|
|
591
|
+
} }, inputs: { component: "component", debug: "debug", utilities: "utilities", styles: "styles", savedUserSettings: "savedUserSettings" }, outputs: { stateChange: "stateChange", componentEvent: "componentEvent", refreshData: "refreshData", openEntityRecord: "openEntityRecord", userSettingsChanged: "userSettingsChanged" }, decls: 4, vars: 3, consts: [["container", ""], [1, "react-component-wrapper"], [1, "react-component-container"], [1, "loading-overlay"], [1, "loading-spinner"], [1, "fa-solid", "fa-spinner", "fa-spin"], [1, "loading-text"]], template: function MJReactComponent_Template(rf, ctx) { if (rf & 1) {
|
|
575
592
|
i0.ɵɵelementStart(0, "div", 1);
|
|
576
593
|
i0.ɵɵelement(1, "div", 2, 0);
|
|
577
594
|
i0.ɵɵtemplate(3, MJReactComponent_Conditional_3_Template, 5, 0, "div", 3);
|
|
@@ -600,6 +617,8 @@ export class MJReactComponent {
|
|
|
600
617
|
`, changeDetection: ChangeDetectionStrategy.OnPush, styles: ["\n :host {\n display: block;\n width: 100%;\n height: 100%;\n }\n .react-component-wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n }\n .react-component-container {\n width: 100%;\n height: 100%;\n transition: opacity 0.3s ease;\n }\n .react-component-container.loading {\n opacity: 0;\n }\n .loading-overlay {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background-color: rgba(255, 255, 255, 0.9);\n z-index: 1;\n }\n .loading-spinner {\n font-size: 48px;\n color: #5B4FE9;\n margin-bottom: 16px;\n }\n .loading-text {\n font-family: -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", Roboto, sans-serif;\n font-size: 14px;\n color: #64748B;\n margin-top: 8px;\n }\n "] }]
|
|
601
618
|
}], () => [{ type: i1.ReactBridgeService }, { type: i2.AngularAdapterService }, { type: i0.ChangeDetectorRef }], { component: [{
|
|
602
619
|
type: Input
|
|
620
|
+
}], debug: [{
|
|
621
|
+
type: Input
|
|
603
622
|
}], utilities: [{
|
|
604
623
|
type: Input
|
|
605
624
|
}], styles: [{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mj-react-component.component.js","sourceRoot":"","sources":["../../../src/lib/components/mj-react-component.component.ts"],"names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/C,gBAAgB","sourcesContent":["/**\n * @fileoverview Angular component that hosts React components with proper memory management.\n * Provides a bridge between Angular and React ecosystems in MemberJunction applications.\n * @module @memberjunction/ng-react\n */\n\nimport {\n Component,\n Input,\n Output,\n EventEmitter,\n ViewChild,\n ElementRef,\n AfterViewInit,\n OnDestroy,\n ChangeDetectionStrategy,\n ChangeDetectorRef\n} from '@angular/core';\nimport { Subject } from 'rxjs';\nimport { ComponentSpec, ComponentCallbacks, ComponentStyles, ComponentObject } from '@memberjunction/interactive-component-types';\nimport { ReactBridgeService } from '../services/react-bridge.service';\nimport { AngularAdapterService } from '../services/angular-adapter.service';\nimport { \n createErrorBoundary,\n ComponentHierarchyRegistrar,\n resourceManager,\n reactRootManager,\n ResolvedComponents,\n SetupStyles,\n ComponentRegistryService\n} from '@memberjunction/react-runtime';\nimport { createRuntimeUtilities } from '../utilities/runtime-utilities';\nimport { LogError, CompositeKey, KeyValuePair, Metadata, RunView } from '@memberjunction/core';\nimport { ComponentMetadataEngine } from '@memberjunction/core-entities';\n\n/**\n * Event emitted by React components\n */\nexport interface ReactComponentEvent {\n type: string;\n payload: any;\n}\n\n/**\n * State change event emitted when component state updates\n */\nexport interface StateChangeEvent {\n path: string;\n value: any;\n}\n\n/**\n * User settings changed event emitted when component saves user preferences\n */\nexport interface UserSettingsChangedEvent {\n settings: Record<string, any>;\n componentName?: string;\n timestamp: Date;\n}\n\n/**\n * Angular component that hosts React components with proper memory management.\n * This component provides a bridge between Angular and React, allowing React components\n * to be used seamlessly within Angular applications.\n */\n@Component({\n selector: 'mj-react-component',\n template: `\n <div class=\"react-component-wrapper\">\n <div #container class=\"react-component-container\" [class.loading]=\"!isInitialized\"></div>\n @if (!isInitialized && !hasError) {\n <div class=\"loading-overlay\">\n <div class=\"loading-spinner\">\n <i class=\"fa-solid fa-spinner fa-spin\"></i>\n </div>\n <div class=\"loading-text\">Loading component...</div>\n </div>\n }\n </div>\n `,\n styles: [`\n :host {\n display: block;\n width: 100%;\n height: 100%;\n }\n .react-component-wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n }\n .react-component-container {\n width: 100%;\n height: 100%;\n transition: opacity 0.3s ease;\n }\n .react-component-container.loading {\n opacity: 0;\n }\n .loading-overlay {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background-color: rgba(255, 255, 255, 0.9);\n z-index: 1;\n }\n .loading-spinner {\n font-size: 48px;\n color: #5B4FE9;\n margin-bottom: 16px;\n }\n .loading-text {\n font-family: -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", Roboto, sans-serif;\n font-size: 14px;\n color: #64748B;\n margin-top: 8px;\n }\n `],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nexport class MJReactComponent implements AfterViewInit, OnDestroy {\n @Input() component!: ComponentSpec;\n \n // Auto-initialize utilities if not provided\n private _utilities: any;\n @Input()\n set utilities(value: any) {\n this._utilities = value;\n }\n get utilities(): any {\n // Lazy initialization - only create default utilities when needed\n if (!this._utilities) {\n const runtimeUtils = createRuntimeUtilities();\n this._utilities = runtimeUtils.buildUtilities();\n console.log('MJReactComponent: Auto-initialized utilities using createRuntimeUtilities()');\n }\n return this._utilities;\n }\n \n // Auto-initialize styles if not provided\n private _styles?: Partial<ComponentStyles>;\n @Input()\n set styles(value: Partial<ComponentStyles> | undefined) {\n this._styles = value;\n }\n get styles(): Partial<ComponentStyles> {\n // Lazy initialization - only create default styles when needed\n if (!this._styles) {\n this._styles = SetupStyles();\n console.log('MJReactComponent: Auto-initialized styles using SetupStyles()');\n }\n return this._styles;\n }\n \n private _savedUserSettings: any = {};\n @Input()\n set savedUserSettings(value: any) {\n this._savedUserSettings = value || {};\n // Re-render if component is initialized\n if (this.isInitialized) {\n this.renderComponent();\n }\n }\n get savedUserSettings(): any {\n return this._savedUserSettings;\n }\n \n @Output() stateChange = new EventEmitter<StateChangeEvent>();\n @Output() componentEvent = new EventEmitter<ReactComponentEvent>();\n @Output() refreshData = new EventEmitter<void>();\n @Output() openEntityRecord = new EventEmitter<{ entityName: string; key: CompositeKey }>();\n @Output() userSettingsChanged = new EventEmitter<UserSettingsChangedEvent>();\n \n @ViewChild('container', { read: ElementRef, static: true }) container!: ElementRef<HTMLDivElement>;\n \n private reactRootId: string | null = null;\n private compiledComponent: ComponentObject | null = null;\n private destroyed$ = new Subject<void>();\n private currentCallbacks: ComponentCallbacks | null = null;\n isInitialized = false;\n private isRendering = false;\n private pendingRender = false;\n private isDestroying = false;\n private componentId: string;\n private componentVersion: string = ''; // Store the version for resolver\n hasError = false;\n\n constructor(\n private reactBridge: ReactBridgeService,\n private adapter: AngularAdapterService,\n private cdr: ChangeDetectorRef\n ) {\n // Generate unique component ID for resource tracking\n this.componentId = `mj-react-component-${Date.now()}-${Math.random()}`;\n }\n\n async ngAfterViewInit() {\n // Trigger change detection to show loading state\n this.cdr.detectChanges();\n await this.initializeComponent();\n }\n\n ngOnDestroy() {\n // Set destroying flag immediately\n this.isDestroying = true;\n \n // Cancel any pending renders\n this.pendingRender = false;\n \n this.destroyed$.next();\n this.destroyed$.complete();\n this.cleanup();\n }\n\n\n /**\n * Initialize the React component\n */\n private async initializeComponent() {\n try {\n // Ensure React is loaded\n await this.reactBridge.getReactContext();\n \n // Wait for React to be fully ready (handles first-load delay)\n await this.reactBridge.waitForReactReady();\n \n // Register component hierarchy (this compiles and registers all components)\n await this.registerComponentHierarchy();\n \n // Get the already-registered component from the registry\n const registry = this.adapter.getRegistry();\n const componentWrapper = registry.get(\n this.component.name, \n this.component.namespace || 'Global', \n this.componentVersion\n );\n \n if (!componentWrapper) {\n throw new Error(`Component ${this.component.name} was not found in registry after registration`);\n }\n \n // The registry now stores ComponentObjects directly\n // Validate it has the expected structure\n if (!componentWrapper || typeof componentWrapper !== 'object') {\n throw new Error(`Invalid component wrapper returned for ${this.component.name}: ${typeof componentWrapper}`);\n }\n \n if (!componentWrapper.component) {\n throw new Error(`Component wrapper missing 'component' property for ${this.component.name}`);\n }\n \n // Now that we use a regular HOC wrapper, components should always be functions\n if (typeof componentWrapper.component !== 'function') {\n throw new Error(`Component is not a function for ${this.component.name}: ${typeof componentWrapper.component}`);\n }\n \n this.compiledComponent = componentWrapper;\n \n // Create managed React root\n const reactContext = this.reactBridge.getCurrentContext();\n if (!reactContext) {\n throw new Error('React context not available');\n }\n \n this.reactRootId = reactRootManager.createRoot(\n this.container.nativeElement,\n (container: HTMLElement) => reactContext.ReactDOM.createRoot(container),\n this.componentId\n );\n \n // Initial render\n this.renderComponent();\n this.isInitialized = true;\n \n // Trigger change detection since we're using OnPush\n this.cdr.detectChanges();\n \n } catch (error) {\n this.hasError = true;\n LogError(`Failed to initialize React component: ${error}`);\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: error instanceof Error ? error.message : String(error),\n source: 'initialization'\n }\n });\n // Trigger change detection to show error state\n this.cdr.detectChanges();\n }\n }\n\n /**\n * Generate a hash from component code for versioning\n * Uses a simple hash function that's fast and sufficient for version differentiation\n */\n private generateComponentHash(spec: ComponentSpec): string {\n // Collect all code from the component hierarchy\n const codeStrings: string[] = [];\n \n const collectCode = (s: ComponentSpec) => {\n if (s.code) {\n codeStrings.push(s.code);\n }\n if (s.dependencies) {\n for (const dep of s.dependencies) {\n collectCode(dep);\n }\n }\n };\n \n collectCode(spec);\n \n // Generate hash from concatenated code\n const fullCode = codeStrings.join('|');\n let hash = 0;\n for (let i = 0; i < fullCode.length; i++) {\n const char = fullCode.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n \n // Convert to hex string and take first 8 characters for readability\n const hexHash = Math.abs(hash).toString(16).padStart(8, '0').substring(0, 8);\n return `v${hexHash}`;\n }\n\n /**\n * Resolve components using the runtime's resolver\n */\n private async resolveComponentsWithVersion(spec: ComponentSpec, version: string, namespace: string = 'Global'): Promise<ResolvedComponents> {\n const resolver = this.adapter.getResolver();\n \n // Debug: Log what dependencies we're trying to resolve\n console.log(`Resolving components for ${spec.name}. Dependencies:`, spec.dependencies);\n \n // Use the runtime's resolver which now handles registry-based components\n const resolved = await resolver.resolveComponents(\n spec, \n namespace,\n Metadata.Provider.CurrentUser // Pass current user context for database operations\n );\n \n console.log(`Resolved ${Object.keys(resolved).length} components for version ${version}:`, Object.keys(resolved));\n return resolved;\n }\n\n\n /**\n * Register all components in the hierarchy\n */\n private async registerComponentHierarchy() {\n // Use semantic version from spec or generate hash-based version for uniqueness\n const version = this.component.version || this.generateComponentHash(this.component);\n this.componentVersion = version; // Store for use in resolver\n \n console.log(`Registering ${this.component.name}@${version}`);\n \n // Check if already registered to avoid duplication\n const registry = this.adapter.getRegistry();\n const existingComponent = registry.get(this.component.name, this.component.namespace || 'Global', version);\n if (existingComponent) {\n console.log(`Component ${this.component.name}@${version} already registered`);\n return;\n }\n \n // Initialize metadata engine\n await ComponentMetadataEngine.Instance.Config(false, Metadata.Provider.CurrentUser);\n \n // Use the runtime's hierarchy registrar\n const registrar = new ComponentHierarchyRegistrar(\n this.adapter.getCompiler(),\n this.adapter.getRegistry(),\n this.adapter.getRuntimeContext()\n );\n \n // Register with proper configuration\n const result = await registrar.registerHierarchy(\n this.component,\n {\n styles: this.styles as ComponentStyles,\n namespace: this.component.namespace || 'Global',\n version: version,\n allowOverride: false, // Each version is unique\n allLibraries: ComponentMetadataEngine.Instance.ComponentLibraries\n }\n );\n \n if (!result.success) {\n const errors = result.errors.map(e => e.error).join(', ');\n throw new Error(`Component registration failed: ${errors}`);\n }\n \n console.log(`Registered ${result.registeredComponents.length} components`);\n }\n\n /**\n * Render the React component\n */\n private async renderComponent() {\n // Don't render if component is being destroyed\n if (this.isDestroying) {\n return;\n }\n \n if (!this.compiledComponent || !this.reactRootId) {\n return;\n }\n\n // Prevent concurrent renders\n if (this.isRendering) {\n this.pendingRender = true;\n return;\n }\n\n const context = this.reactBridge.getCurrentContext();\n if (!context) {\n return;\n }\n\n this.isRendering = true;\n const { React } = context;\n \n // Resolve components with the correct version using runtime's resolver\n const components = await this.resolveComponentsWithVersion(this.component, this.componentVersion);\n \n // Create callbacks once per component instance\n if (!this.currentCallbacks) {\n this.currentCallbacks = this.createCallbacks();\n }\n \n // Build props with savedUserSettings pattern\n const props = {\n utilities: this.utilities, // Now uses getter which auto-initializes if needed\n callbacks: this.currentCallbacks,\n components,\n styles: this.styles as any,\n savedUserSettings: this._savedUserSettings,\n onSaveUserSettings: this.handleSaveUserSettings.bind(this)\n };\n\n // Validate component before creating element\n if (!this.compiledComponent.component) {\n LogError(`Component is undefined for ${this.component.name} during render`);\n return;\n }\n \n // Components should be functions after HOC wrapping\n if (typeof this.compiledComponent.component !== 'function') {\n LogError(`Component is not a function for ${this.component.name}: ${typeof this.compiledComponent.component}`);\n return;\n }\n\n // Create error boundary\n const ErrorBoundary = createErrorBoundary(React, {\n onError: this.handleReactError.bind(this),\n logErrors: true,\n recovery: 'retry'\n });\n\n // Create element with error boundary\n const element = React.createElement(\n ErrorBoundary,\n null,\n React.createElement(this.compiledComponent.component, props)\n );\n\n // Render with timeout protection using resource manager\n const timeoutId = resourceManager.setTimeout(\n this.componentId,\n () => {\n // Check if still rendering and not destroyed\n if (this.isRendering && !this.isDestroying) {\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: 'Component render timeout - possible infinite loop detected',\n source: 'render'\n }\n });\n }\n },\n 5000,\n { purpose: 'render-timeout-protection' }\n );\n\n // Use managed React root for rendering\n reactRootManager.render(\n this.reactRootId,\n element,\n () => {\n // Clear the timeout as render completed\n resourceManager.clearTimeout(this.componentId, timeoutId);\n \n // Don't update state if component is destroyed\n if (this.isDestroying) {\n return;\n }\n \n this.isRendering = false;\n \n // If there was a pending render request, execute it now\n if (this.pendingRender) {\n this.pendingRender = false;\n this.renderComponent();\n }\n }\n );\n }\n\n /**\n * Create callbacks for the React component\n */\n private createCallbacks(): ComponentCallbacks {\n return {\n RegisterMethod: (_methodName: string, _handler: any) => {\n // The component compiler wrapper will handle this internally\n // This is just a placeholder to satisfy the interface\n // The actual registration happens in the wrapper component\n },\n OpenEntityRecord: async (entityName: string, key: CompositeKey) => {\n let keyToUse: CompositeKey | null = null;\n if (key instanceof Array) {\n keyToUse = CompositeKey.FromKeyValuePairs(key);\n }\n else if (typeof key === 'object' && !!key.GetValueByFieldName) {\n keyToUse = key as CompositeKey;\n }\n else if (typeof key === 'object') {\n //} && !!key.FieldName && !!key.Value) {\n // possible that have an object that is a simple key/value pair with\n // FieldName and value properties\n const keyAny = key as any;\n if (keyAny.FieldName && keyAny.Value) {\n keyToUse = CompositeKey.FromKeyValuePairs([keyAny as KeyValuePair]);\n }\n }\n if (keyToUse) {\n // now in some cases we have key/value pairs that the component we are hosting\n // use, but are not the pkey, so if that is the case, we'll run a quick view to try\n // and get the pkey so that we can emit the openEntityRecord call with the pkey\n const md = new Metadata();\n const e = md.EntityByName(entityName);\n let shouldRunView = false;\n // now check each key in the keyToUse to see if it is a pkey\n for (const singleKey of keyToUse.KeyValuePairs) {\n const field = e.Fields.find(f => f.Name.trim().toLowerCase() === singleKey.FieldName.trim().toLowerCase());\n if (!field) {\n // if we get here this is a problem, the component has given us a non-matching field, this shouldn't ever happen\n // but if it doesn't log warning to console and exit\n console.warn(`Non-matching field found for key: ${JSON.stringify(keyToUse)}`);\n return;\n }\n else if (!field.IsPrimaryKey) {\n // if we get here that means we have a non-pkey so we'll want to do a lookup via a RunView\n // to get the actual pkey value\n shouldRunView = true;\n break;\n }\n }\n\n // if we get here and shouldRunView is true, we need to run a view using the info provided\n // by our contained component to get the pkey\n if (shouldRunView) {\n const rv = new RunView();\n const result = await rv.RunView({\n EntityName: entityName,\n ExtraFilter: keyToUse.ToWhereClause()\n })\n if (result && result.Success && result.Results.length > 0) {\n // we have a match, use the first row and update our keyToUse\n const kvPairs: KeyValuePair[] = [];\n e.PrimaryKeys.forEach(pk => {\n kvPairs.push(\n {\n FieldName: pk.Name,\n Value: result.Results[0][pk.Name]\n }\n )\n })\n keyToUse = CompositeKey.FromKeyValuePairs(kvPairs);\n }\n }\n\n this.openEntityRecord.emit({ entityName, key: keyToUse });\n } \n } \n };\n }\n\n /**\n * Handle React component errors\n */\n private handleReactError(error: any, errorInfo?: any) {\n LogError(`React component error: ${error?.toString() || 'Unknown error'}`, errorInfo);\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: error?.toString() || 'Unknown error',\n errorInfo,\n source: 'react'\n }\n });\n }\n\n /**\n * Handle onSaveUserSettings from components\n * This implements the SavedUserSettings pattern\n */\n private handleSaveUserSettings(newSettings: Record<string, any>) {\n // Just bubble the event up to parent containers for persistence\n // We don't need to store anything here\n this.userSettingsChanged.emit({\n settings: newSettings,\n componentName: this.component?.name,\n timestamp: new Date()\n });\n \n // DO NOT re-render the component!\n // The component already has the correct state - it's the one that told us about the change.\n // Re-rendering would cause unnecessary DOM updates and visual flashing.\n }\n\n /**\n * Clean up resources\n */\n private cleanup() {\n // Clean up all resources managed by resource manager\n resourceManager.cleanupComponent(this.componentId);\n \n // Clean up prop builder subscriptions\n if (this.currentCallbacks) {\n this.currentCallbacks = null;\n }\n \n // Unmount React root using managed unmount\n if (this.reactRootId) {\n // Force stop rendering flags\n this.isRendering = false;\n this.pendingRender = false;\n \n // This will handle waiting for render completion if needed\n reactRootManager.unmountRoot(this.reactRootId);\n this.reactRootId = null;\n }\n\n // Clear references\n this.compiledComponent = null;\n this.isInitialized = false;\n\n // Trigger registry cleanup\n this.adapter.getRegistry().cleanup();\n }\n\n /**\n * Public method to refresh the component\n * @deprecated Components manage their own state and data now\n */\n refresh() {\n // Check if the component has registered a refresh method\n if (this.compiledComponent?.refresh) {\n this.compiledComponent.refresh();\n } else {\n // Fallback: trigger a re-render if needed\n this.renderComponent();\n }\n }\n\n /**\n * Public method to update state programmatically\n * @param path - State path to update\n * @param value - New value\n * @deprecated Components manage their own state now\n */\n updateState(path: string, value: any) {\n // Just emit the event, don't manage state here\n this.stateChange.emit({ path, value });\n }\n\n // =================================================================\n // Standard Component Methods - Strongly Typed\n // =================================================================\n \n /**\n * Gets the current data state of the component\n * Used by AI agents to understand what data is currently displayed\n * @returns The current data state, or undefined if not implemented\n */\n getCurrentDataState(): any {\n return this.compiledComponent?.getCurrentDataState?.();\n }\n \n /**\n * Gets the history of data state changes in the component\n * @returns Array of timestamped state snapshots, or empty array if not implemented\n */\n getDataStateHistory(): Array<{ timestamp: Date; state: any }> {\n return this.compiledComponent?.getDataStateHistory?.() || [];\n }\n \n /**\n * Validates the current state of the component\n * @returns true if valid, false or validation errors otherwise\n */\n validate(): boolean | { valid: boolean; errors?: string[] } {\n return this.compiledComponent?.validate?.() || true;\n }\n \n /**\n * Checks if the component has unsaved changes\n * @returns true if dirty, false otherwise\n */\n isDirty(): boolean {\n return this.compiledComponent?.isDirty?.() || false;\n }\n \n /**\n * Resets the component to its initial state\n */\n reset(): void {\n this.compiledComponent?.reset?.();\n }\n \n /**\n * Scrolls to a specific element or position within the component\n * @param target - Element selector, element reference, or scroll options\n */\n scrollTo(target: string | HTMLElement | { top?: number; left?: number }): void {\n this.compiledComponent?.scrollTo?.(target);\n }\n \n /**\n * Sets focus to a specific element within the component\n * @param target - Element selector or element reference\n */\n focus(target?: string | HTMLElement): void {\n this.compiledComponent?.focus?.(target);\n }\n \n /**\n * Invokes a custom method on the component\n * @param methodName - Name of the method to invoke\n * @param args - Arguments to pass to the method\n * @returns The result of the method call, or undefined if method doesn't exist\n */\n invokeMethod(methodName: string, ...args: any[]): any {\n return this.compiledComponent?.invokeMethod?.(methodName, ...args);\n }\n \n /**\n * Checks if a method is available on the component\n * @param methodName - Name of the method to check\n * @returns true if the method exists\n */\n hasMethod(methodName: string): boolean {\n return this.compiledComponent?.hasMethod?.(methodName) || false;\n }\n \n /**\n * Print the component content\n * Uses component's print method if available, otherwise uses window.print()\n */\n print(): void {\n if (this.compiledComponent?.print) {\n this.compiledComponent.print();\n } else if (typeof window !== 'undefined' && window.print) {\n window.print();\n }\n }\n\n /**\n * Force clear component registries\n * Used by Component Studio for fresh loads\n * This is a static method that can be called without a component instance\n */\n public static forceClearRegistries(): void {\n // Clear React runtime's component registry service\n ComponentRegistryService.reset();\n \n // Clear any cached hierarchy registrar\n if (typeof window !== 'undefined' && (window as any).__MJ_COMPONENT_HIERARCHY_REGISTRAR__) {\n (window as any).__MJ_COMPONENT_HIERARCHY_REGISTRAR__ = null;\n }\n \n console.log('🧹 All component registries cleared for fresh load');\n }\n\n}"]}
|
|
1
|
+
{"version":3,"file":"mj-react-component.component.js","sourceRoot":"","sources":["../../../src/lib/components/mj-react-component.component.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,SAAS,EACT,KAAK,EACL,MAAM,EACN,YAAY,EACZ,SAAS,EACT,UAAU,EAGV,uBAAuB,EACvB,iBAAiB,EAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAwD,MAAM,6CAA6C,CAAC;AAClI,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,EACL,mBAAmB,EACnB,2BAA2B,EAC3B,eAAe,EACf,gBAAgB,EAEhB,WAAW,EACX,wBAAwB,EACzB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAgB,QAAQ,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC/F,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;;;;;;IAuC9D,AADF,8BAA6B,aACE;IAC3B,uBAA2C;IAC7C,iBAAM;IACN,8BAA0B;IAAA,oCAAoB;IAChD,AADgD,iBAAM,EAChD;;AAhBd;;;;GAIG;AA8DH,MAAM,OAAO,gBAAgB;IAM3B,IACI,SAAS,CAAC,KAAU;QACtB,IAAI,CAAC,UAAU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,EAAE,CAAC;QAEjC,uCAAuC;QACvC,IAAI,OAAO,MAAM,KAAK,WAAW,IAAK,MAAc,CAAC,oCAAoC,EAAE,CAAC;YACzF,MAAc,CAAC,oCAAoC,GAAG,IAAI,CAAC;QAC9D,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,oDAAoD,CAAC,CAAC;IACpE,CAAC;iFA3qBU,gBAAgB;oEAAhB,gBAAgB;mCA0DK,UAAU;;;;;YApHxC,8BAAqC;YACnC,4BAAyF;YACzF,yEAAmC;YAQrC,iBAAM;;YAT8C,cAAgC;YAAhC,6CAAgC;YAClF,eAOC;YAPD,8DAOC;;;iFAiDM,gBAAgB;cA7D5B,SAAS;2BACE,oBAAoB,YACpB;;;;;;;;;;;;GAYT,mBA6CgB,uBAAuB,CAAC,MAAM;uHAGtC,SAAS;kBAAjB,KAAK;YACG,KAAK;kBAAb,KAAK;YAKF,SAAS;kBADZ,KAAK;YAmBF,MAAM;kBADT,KAAK;YAiBF,iBAAiB;kBADpB,KAAK;YAYI,WAAW;kBAApB,MAAM;YACG,cAAc;kBAAvB,MAAM;YACG,WAAW;kBAApB,MAAM;YACG,gBAAgB;kBAAzB,MAAM;YACG,mBAAmB;kBAA5B,MAAM;YAEqD,SAAS;kBAApE,SAAS;mBAAC,WAAW,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE;;kFA1D/C,gBAAgB","sourcesContent":["/**\n * @fileoverview Angular component that hosts React components with proper memory management.\n * Provides a bridge between Angular and React ecosystems in MemberJunction applications.\n * @module @memberjunction/ng-react\n */\n\nimport {\n Component,\n Input,\n Output,\n EventEmitter,\n ViewChild,\n ElementRef,\n AfterViewInit,\n OnDestroy,\n ChangeDetectionStrategy,\n ChangeDetectorRef\n} from '@angular/core';\nimport { Subject } from 'rxjs';\nimport { ComponentSpec, ComponentCallbacks, ComponentStyles, ComponentObject } from '@memberjunction/interactive-component-types';\nimport { ReactBridgeService } from '../services/react-bridge.service';\nimport { AngularAdapterService } from '../services/angular-adapter.service';\nimport { \n createErrorBoundary,\n ComponentHierarchyRegistrar,\n resourceManager,\n reactRootManager,\n ResolvedComponents,\n SetupStyles,\n ComponentRegistryService\n} from '@memberjunction/react-runtime';\nimport { createRuntimeUtilities } from '../utilities/runtime-utilities';\nimport { LogError, CompositeKey, KeyValuePair, Metadata, RunView } from '@memberjunction/core';\nimport { ComponentMetadataEngine } from '@memberjunction/core-entities';\n\n/**\n * Event emitted by React components\n */\nexport interface ReactComponentEvent {\n type: string;\n payload: any;\n}\n\n/**\n * State change event emitted when component state updates\n */\nexport interface StateChangeEvent {\n path: string;\n value: any;\n}\n\n/**\n * User settings changed event emitted when component saves user preferences\n */\nexport interface UserSettingsChangedEvent {\n settings: Record<string, any>;\n componentName?: string;\n timestamp: Date;\n}\n\n/**\n * Angular component that hosts React components with proper memory management.\n * This component provides a bridge between Angular and React, allowing React components\n * to be used seamlessly within Angular applications.\n */\n@Component({\n selector: 'mj-react-component',\n template: `\n <div class=\"react-component-wrapper\">\n <div #container class=\"react-component-container\" [class.loading]=\"!isInitialized\"></div>\n @if (!isInitialized && !hasError) {\n <div class=\"loading-overlay\">\n <div class=\"loading-spinner\">\n <i class=\"fa-solid fa-spinner fa-spin\"></i>\n </div>\n <div class=\"loading-text\">Loading component...</div>\n </div>\n }\n </div>\n `,\n styles: [`\n :host {\n display: block;\n width: 100%;\n height: 100%;\n }\n .react-component-wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n }\n .react-component-container {\n width: 100%;\n height: 100%;\n transition: opacity 0.3s ease;\n }\n .react-component-container.loading {\n opacity: 0;\n }\n .loading-overlay {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background-color: rgba(255, 255, 255, 0.9);\n z-index: 1;\n }\n .loading-spinner {\n font-size: 48px;\n color: #5B4FE9;\n margin-bottom: 16px;\n }\n .loading-text {\n font-family: -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", Roboto, sans-serif;\n font-size: 14px;\n color: #64748B;\n margin-top: 8px;\n }\n `],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nexport class MJReactComponent implements AfterViewInit, OnDestroy {\n @Input() component!: ComponentSpec;\n @Input() debug: boolean = true;\n \n // Auto-initialize utilities if not provided\n private _utilities: any;\n @Input()\n set utilities(value: any) {\n this._utilities = value;\n }\n get utilities(): any {\n // Lazy initialization - only create default utilities when needed\n if (!this._utilities) {\n const runtimeUtils = createRuntimeUtilities();\n this._utilities = runtimeUtils.buildUtilities(this.debug);\n if (this.debug) {\n console.log('MJReactComponent: Auto-initialized utilities using createRuntimeUtilities()');\n }\n }\n return this._utilities;\n }\n \n // Auto-initialize styles if not provided\n private _styles?: Partial<ComponentStyles>;\n @Input()\n set styles(value: Partial<ComponentStyles> | undefined) {\n this._styles = value;\n }\n get styles(): Partial<ComponentStyles> {\n // Lazy initialization - only create default styles when needed\n if (!this._styles) {\n this._styles = SetupStyles();\n if (this.debug) {\n console.log('MJReactComponent: Auto-initialized styles using SetupStyles()');\n }\n }\n return this._styles;\n }\n \n private _savedUserSettings: any = {};\n @Input()\n set savedUserSettings(value: any) {\n this._savedUserSettings = value || {};\n // Re-render if component is initialized\n if (this.isInitialized) {\n this.renderComponent();\n }\n }\n get savedUserSettings(): any {\n return this._savedUserSettings;\n }\n \n @Output() stateChange = new EventEmitter<StateChangeEvent>();\n @Output() componentEvent = new EventEmitter<ReactComponentEvent>();\n @Output() refreshData = new EventEmitter<void>();\n @Output() openEntityRecord = new EventEmitter<{ entityName: string; key: CompositeKey }>();\n @Output() userSettingsChanged = new EventEmitter<UserSettingsChangedEvent>();\n \n @ViewChild('container', { read: ElementRef, static: true }) container!: ElementRef<HTMLDivElement>;\n \n private reactRootId: string | null = null;\n private compiledComponent: ComponentObject | null = null;\n private destroyed$ = new Subject<void>();\n private currentCallbacks: ComponentCallbacks | null = null;\n isInitialized = false;\n private isRendering = false;\n private pendingRender = false;\n private isDestroying = false;\n private componentId: string;\n private componentVersion: string = ''; // Store the version for resolver\n hasError = false;\n\n constructor(\n private reactBridge: ReactBridgeService,\n private adapter: AngularAdapterService,\n private cdr: ChangeDetectorRef\n ) {\n // Generate unique component ID for resource tracking\n this.componentId = `mj-react-component-${Date.now()}-${Math.random()}`;\n }\n\n async ngAfterViewInit() {\n // Set debug flag on the bridge service\n this.reactBridge.debug = this.debug;\n \n // Trigger change detection to show loading state\n this.cdr.detectChanges();\n await this.initializeComponent();\n }\n\n ngOnDestroy() {\n // Set destroying flag immediately\n this.isDestroying = true;\n \n // Cancel any pending renders\n this.pendingRender = false;\n \n this.destroyed$.next();\n this.destroyed$.complete();\n this.cleanup();\n }\n\n\n /**\n * Initialize the React component\n */\n private async initializeComponent() {\n try {\n // Ensure React is loaded\n await this.reactBridge.getReactContext();\n \n // Wait for React to be fully ready (handles first-load delay)\n await this.reactBridge.waitForReactReady();\n \n // Register component hierarchy (this compiles and registers all components)\n await this.registerComponentHierarchy();\n \n // Get the already-registered component from the registry\n const registry = this.adapter.getRegistry();\n const componentWrapper = registry.get(\n this.component.name, \n this.component.namespace || 'Global', \n this.componentVersion\n );\n \n if (!componentWrapper) {\n throw new Error(`Component ${this.component.name} was not found in registry after registration`);\n }\n \n // The registry now stores ComponentObjects directly\n // Validate it has the expected structure\n if (!componentWrapper || typeof componentWrapper !== 'object') {\n throw new Error(`Invalid component wrapper returned for ${this.component.name}: ${typeof componentWrapper}`);\n }\n \n if (!componentWrapper.component) {\n throw new Error(`Component wrapper missing 'component' property for ${this.component.name}`);\n }\n \n // Now that we use a regular HOC wrapper, components should always be functions\n if (typeof componentWrapper.component !== 'function') {\n throw new Error(`Component is not a function for ${this.component.name}: ${typeof componentWrapper.component}`);\n }\n \n this.compiledComponent = componentWrapper;\n \n // Create managed React root\n const reactContext = this.reactBridge.getCurrentContext();\n if (!reactContext) {\n throw new Error('React context not available');\n }\n \n this.reactRootId = reactRootManager.createRoot(\n this.container.nativeElement,\n (container: HTMLElement) => reactContext.ReactDOM.createRoot(container),\n this.componentId\n );\n \n // Initial render\n this.renderComponent();\n this.isInitialized = true;\n \n // Trigger change detection since we're using OnPush\n this.cdr.detectChanges();\n \n } catch (error) {\n this.hasError = true;\n LogError(`Failed to initialize React component: ${error}`);\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: error instanceof Error ? error.message : String(error),\n source: 'initialization'\n }\n });\n // Trigger change detection to show error state\n this.cdr.detectChanges();\n }\n }\n\n /**\n * Generate a hash from component code for versioning\n * Uses a simple hash function that's fast and sufficient for version differentiation\n */\n private generateComponentHash(spec: ComponentSpec): string {\n // Collect all code from the component hierarchy\n const codeStrings: string[] = [];\n \n const collectCode = (s: ComponentSpec) => {\n if (s.code) {\n codeStrings.push(s.code);\n }\n if (s.dependencies) {\n for (const dep of s.dependencies) {\n collectCode(dep);\n }\n }\n };\n \n collectCode(spec);\n \n // Generate hash from concatenated code\n const fullCode = codeStrings.join('|');\n let hash = 0;\n for (let i = 0; i < fullCode.length; i++) {\n const char = fullCode.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n \n // Convert to hex string and take first 8 characters for readability\n const hexHash = Math.abs(hash).toString(16).padStart(8, '0').substring(0, 8);\n return `v${hexHash}`;\n }\n\n /**\n * Resolve components using the runtime's resolver\n */\n private async resolveComponentsWithVersion(spec: ComponentSpec, version: string, namespace: string = 'Global'): Promise<ResolvedComponents> {\n const resolver = this.adapter.getResolver();\n \n // Debug: Log what dependencies we're trying to resolve\n if (this.debug) {\n console.log(`Resolving components for ${spec.name}. Dependencies:`, spec.dependencies);\n }\n \n // Use the runtime's resolver which now handles registry-based components\n const resolved = await resolver.resolveComponents(\n spec, \n namespace,\n Metadata.Provider.CurrentUser // Pass current user context for database operations\n );\n \n if (this.debug) {\n console.log(`Resolved ${Object.keys(resolved).length} components for version ${version}:`, Object.keys(resolved));\n }\n return resolved;\n }\n\n\n /**\n * Register all components in the hierarchy\n */\n private async registerComponentHierarchy() {\n // Use semantic version from spec or generate hash-based version for uniqueness\n const version = this.component.version || this.generateComponentHash(this.component);\n this.componentVersion = version; // Store for use in resolver\n \n if (this.debug) {\n console.log(`Registering ${this.component.name}@${version}`);\n }\n \n // Check if already registered to avoid duplication\n const registry = this.adapter.getRegistry();\n const existingComponent = registry.get(this.component.name, this.component.namespace || 'Global', version);\n if (existingComponent) {\n if (this.debug) {\n console.log(`Component ${this.component.name}@${version} already registered`);\n }\n return;\n }\n \n // Initialize metadata engine\n await ComponentMetadataEngine.Instance.Config(false, Metadata.Provider.CurrentUser);\n \n // Use the runtime's hierarchy registrar\n const registrar = new ComponentHierarchyRegistrar(\n this.adapter.getCompiler(),\n this.adapter.getRegistry(),\n this.adapter.getRuntimeContext()\n );\n \n // Register with proper configuration\n const result = await registrar.registerHierarchy(\n this.component,\n {\n styles: this.styles as ComponentStyles,\n namespace: this.component.namespace || 'Global',\n version: version,\n allowOverride: false, // Each version is unique\n allLibraries: ComponentMetadataEngine.Instance.ComponentLibraries\n }\n );\n \n if (!result.success) {\n const errors = result.errors.map(e => e.error).join(', ');\n throw new Error(`Component registration failed: ${errors}`);\n }\n \n if (this.debug) {\n console.log(`Registered ${result.registeredComponents.length} components`);\n }\n }\n\n /**\n * Render the React component\n */\n private async renderComponent() {\n // Don't render if component is being destroyed\n if (this.isDestroying) {\n return;\n }\n \n if (!this.compiledComponent || !this.reactRootId) {\n return;\n }\n\n // Prevent concurrent renders\n if (this.isRendering) {\n this.pendingRender = true;\n return;\n }\n\n const context = this.reactBridge.getCurrentContext();\n if (!context) {\n return;\n }\n\n this.isRendering = true;\n const { React } = context;\n \n // Resolve components with the correct version using runtime's resolver\n const components = await this.resolveComponentsWithVersion(this.component, this.componentVersion);\n \n // Create callbacks once per component instance\n if (!this.currentCallbacks) {\n this.currentCallbacks = this.createCallbacks();\n }\n \n // Build props with savedUserSettings pattern\n const props = {\n utilities: this.utilities, // Now uses getter which auto-initializes if needed\n callbacks: this.currentCallbacks,\n components,\n styles: this.styles as any,\n savedUserSettings: this._savedUserSettings,\n onSaveUserSettings: this.handleSaveUserSettings.bind(this)\n };\n\n // Validate component before creating element\n if (!this.compiledComponent.component) {\n LogError(`Component is undefined for ${this.component.name} during render`);\n return;\n }\n \n // Components should be functions after HOC wrapping\n if (typeof this.compiledComponent.component !== 'function') {\n LogError(`Component is not a function for ${this.component.name}: ${typeof this.compiledComponent.component}`);\n return;\n }\n\n // Create error boundary\n const ErrorBoundary = createErrorBoundary(React, {\n onError: this.handleReactError.bind(this),\n logErrors: true,\n recovery: 'retry'\n });\n\n // Create element with error boundary\n const element = React.createElement(\n ErrorBoundary,\n null,\n React.createElement(this.compiledComponent.component, props)\n );\n\n // Render with timeout protection using resource manager\n const timeoutId = resourceManager.setTimeout(\n this.componentId,\n () => {\n // Check if still rendering and not destroyed\n if (this.isRendering && !this.isDestroying) {\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: 'Component render timeout - possible infinite loop detected',\n source: 'render'\n }\n });\n }\n },\n 5000,\n { purpose: 'render-timeout-protection' }\n );\n\n // Use managed React root for rendering\n reactRootManager.render(\n this.reactRootId,\n element,\n () => {\n // Clear the timeout as render completed\n resourceManager.clearTimeout(this.componentId, timeoutId);\n \n // Don't update state if component is destroyed\n if (this.isDestroying) {\n return;\n }\n \n this.isRendering = false;\n \n // If there was a pending render request, execute it now\n if (this.pendingRender) {\n this.pendingRender = false;\n this.renderComponent();\n }\n }\n );\n }\n\n /**\n * Create callbacks for the React component\n */\n private createCallbacks(): ComponentCallbacks {\n return {\n RegisterMethod: (_methodName: string, _handler: any) => {\n // The component compiler wrapper will handle this internally\n // This is just a placeholder to satisfy the interface\n // The actual registration happens in the wrapper component\n },\n OpenEntityRecord: async (entityName: string, key: CompositeKey) => {\n let keyToUse: CompositeKey | null = null;\n if (key instanceof Array) {\n keyToUse = CompositeKey.FromKeyValuePairs(key);\n }\n else if (typeof key === 'object' && !!key.GetValueByFieldName) {\n keyToUse = key as CompositeKey;\n }\n else if (typeof key === 'object') {\n //} && !!key.FieldName && !!key.Value) {\n // possible that have an object that is a simple key/value pair with\n // FieldName and value properties\n const keyAny = key as any;\n if (keyAny.FieldName && keyAny.Value) {\n keyToUse = CompositeKey.FromKeyValuePairs([keyAny as KeyValuePair]);\n }\n }\n if (keyToUse) {\n // now in some cases we have key/value pairs that the component we are hosting\n // use, but are not the pkey, so if that is the case, we'll run a quick view to try\n // and get the pkey so that we can emit the openEntityRecord call with the pkey\n const md = new Metadata();\n const e = md.EntityByName(entityName);\n let shouldRunView = false;\n // now check each key in the keyToUse to see if it is a pkey\n for (const singleKey of keyToUse.KeyValuePairs) {\n const field = e.Fields.find(f => f.Name.trim().toLowerCase() === singleKey.FieldName.trim().toLowerCase());\n if (!field) {\n // if we get here this is a problem, the component has given us a non-matching field, this shouldn't ever happen\n // but if it doesn't log warning to console and exit\n console.warn(`Non-matching field found for key: ${JSON.stringify(keyToUse)}`);\n return;\n }\n else if (!field.IsPrimaryKey) {\n // if we get here that means we have a non-pkey so we'll want to do a lookup via a RunView\n // to get the actual pkey value\n shouldRunView = true;\n break;\n }\n }\n\n // if we get here and shouldRunView is true, we need to run a view using the info provided\n // by our contained component to get the pkey\n if (shouldRunView) {\n const rv = new RunView();\n const result = await rv.RunView({\n EntityName: entityName,\n ExtraFilter: keyToUse.ToWhereClause()\n })\n if (result && result.Success && result.Results.length > 0) {\n // we have a match, use the first row and update our keyToUse\n const kvPairs: KeyValuePair[] = [];\n e.PrimaryKeys.forEach(pk => {\n kvPairs.push(\n {\n FieldName: pk.Name,\n Value: result.Results[0][pk.Name]\n }\n )\n })\n keyToUse = CompositeKey.FromKeyValuePairs(kvPairs);\n }\n }\n\n this.openEntityRecord.emit({ entityName, key: keyToUse });\n } \n } \n };\n }\n\n /**\n * Handle React component errors\n */\n private handleReactError(error: any, errorInfo?: any) {\n LogError(`React component error: ${error?.toString() || 'Unknown error'}`, errorInfo);\n this.componentEvent.emit({\n type: 'error',\n payload: {\n error: error?.toString() || 'Unknown error',\n errorInfo,\n source: 'react'\n }\n });\n }\n\n /**\n * Handle onSaveUserSettings from components\n * This implements the SavedUserSettings pattern\n */\n private handleSaveUserSettings(newSettings: Record<string, any>) {\n // Just bubble the event up to parent containers for persistence\n // We don't need to store anything here\n this.userSettingsChanged.emit({\n settings: newSettings,\n componentName: this.component?.name,\n timestamp: new Date()\n });\n \n // DO NOT re-render the component!\n // The component already has the correct state - it's the one that told us about the change.\n // Re-rendering would cause unnecessary DOM updates and visual flashing.\n }\n\n /**\n * Clean up resources\n */\n private cleanup() {\n // Clean up all resources managed by resource manager\n resourceManager.cleanupComponent(this.componentId);\n \n // Clean up prop builder subscriptions\n if (this.currentCallbacks) {\n this.currentCallbacks = null;\n }\n \n // Unmount React root using managed unmount\n if (this.reactRootId) {\n // Force stop rendering flags\n this.isRendering = false;\n this.pendingRender = false;\n \n // This will handle waiting for render completion if needed\n reactRootManager.unmountRoot(this.reactRootId);\n this.reactRootId = null;\n }\n\n // Clear references\n this.compiledComponent = null;\n this.isInitialized = false;\n\n // Trigger registry cleanup\n this.adapter.getRegistry().cleanup();\n }\n\n /**\n * Public method to refresh the component\n * @deprecated Components manage their own state and data now\n */\n refresh() {\n // Check if the component has registered a refresh method\n if (this.compiledComponent?.refresh) {\n this.compiledComponent.refresh();\n } else {\n // Fallback: trigger a re-render if needed\n this.renderComponent();\n }\n }\n\n /**\n * Public method to update state programmatically\n * @param path - State path to update\n * @param value - New value\n * @deprecated Components manage their own state now\n */\n updateState(path: string, value: any) {\n // Just emit the event, don't manage state here\n this.stateChange.emit({ path, value });\n }\n\n // =================================================================\n // Standard Component Methods - Strongly Typed\n // =================================================================\n \n /**\n * Gets the current data state of the component\n * Used by AI agents to understand what data is currently displayed\n * @returns The current data state, or undefined if not implemented\n */\n getCurrentDataState(): any {\n return this.compiledComponent?.getCurrentDataState?.();\n }\n \n /**\n * Gets the history of data state changes in the component\n * @returns Array of timestamped state snapshots, or empty array if not implemented\n */\n getDataStateHistory(): Array<{ timestamp: Date; state: any }> {\n return this.compiledComponent?.getDataStateHistory?.() || [];\n }\n \n /**\n * Validates the current state of the component\n * @returns true if valid, false or validation errors otherwise\n */\n validate(): boolean | { valid: boolean; errors?: string[] } {\n return this.compiledComponent?.validate?.() || true;\n }\n \n /**\n * Checks if the component has unsaved changes\n * @returns true if dirty, false otherwise\n */\n isDirty(): boolean {\n return this.compiledComponent?.isDirty?.() || false;\n }\n \n /**\n * Resets the component to its initial state\n */\n reset(): void {\n this.compiledComponent?.reset?.();\n }\n \n /**\n * Scrolls to a specific element or position within the component\n * @param target - Element selector, element reference, or scroll options\n */\n scrollTo(target: string | HTMLElement | { top?: number; left?: number }): void {\n this.compiledComponent?.scrollTo?.(target);\n }\n \n /**\n * Sets focus to a specific element within the component\n * @param target - Element selector or element reference\n */\n focus(target?: string | HTMLElement): void {\n this.compiledComponent?.focus?.(target);\n }\n \n /**\n * Invokes a custom method on the component\n * @param methodName - Name of the method to invoke\n * @param args - Arguments to pass to the method\n * @returns The result of the method call, or undefined if method doesn't exist\n */\n invokeMethod(methodName: string, ...args: any[]): any {\n return this.compiledComponent?.invokeMethod?.(methodName, ...args);\n }\n \n /**\n * Checks if a method is available on the component\n * @param methodName - Name of the method to check\n * @returns true if the method exists\n */\n hasMethod(methodName: string): boolean {\n return this.compiledComponent?.hasMethod?.(methodName) || false;\n }\n \n /**\n * Print the component content\n * Uses component's print method if available, otherwise uses window.print()\n */\n print(): void {\n if (this.compiledComponent?.print) {\n this.compiledComponent.print();\n } else if (typeof window !== 'undefined' && window.print) {\n window.print();\n }\n }\n\n /**\n * Force clear component registries\n * Used by Component Studio for fresh loads\n * This is a static method that can be called without a component instance\n */\n public static forceClearRegistries(): void {\n // Clear React runtime's component registry service\n ComponentRegistryService.reset();\n \n // Clear any cached hierarchy registrar\n if (typeof window !== 'undefined' && (window as any).__MJ_COMPONENT_HIERARCHY_REGISTRAR__) {\n (window as any).__MJ_COMPONENT_HIERARCHY_REGISTRAR__ = null;\n }\n \n console.log('🧹 All component registries cleared for fresh load');\n }\n\n}"]}
|
|
@@ -14,9 +14,12 @@ export declare class AngularAdapterService {
|
|
|
14
14
|
* Initialize the React runtime with Angular-specific configuration
|
|
15
15
|
* @param config Optional library configuration
|
|
16
16
|
* @param additionalLibraries Optional additional libraries to merge
|
|
17
|
+
* @param options Optional options including debug flag
|
|
17
18
|
* @returns Promise resolving when runtime is ready
|
|
18
19
|
*/
|
|
19
|
-
initialize(config?: LibraryConfiguration, additionalLibraries?: ExternalLibraryConfig[]
|
|
20
|
+
initialize(config?: LibraryConfiguration, additionalLibraries?: ExternalLibraryConfig[], options?: {
|
|
21
|
+
debug?: boolean;
|
|
22
|
+
}): Promise<void>;
|
|
20
23
|
/**
|
|
21
24
|
* Get the component compiler
|
|
22
25
|
* @returns Component compiler instance
|
|
@@ -4,9 +4,8 @@
|
|
|
4
4
|
* @module @memberjunction/ng-react
|
|
5
5
|
*/
|
|
6
6
|
import { Injectable } from '@angular/core';
|
|
7
|
-
import { createReactRuntime } from '@memberjunction/react-runtime';
|
|
7
|
+
import { createReactRuntime, SetupStyles } from '@memberjunction/react-runtime';
|
|
8
8
|
import { ScriptLoaderService } from './script-loader.service';
|
|
9
|
-
import { DEFAULT_STYLES } from '../default-styles';
|
|
10
9
|
import * as i0 from "@angular/core";
|
|
11
10
|
import * as i1 from "./script-loader.service";
|
|
12
11
|
/**
|
|
@@ -21,14 +20,15 @@ export class AngularAdapterService {
|
|
|
21
20
|
* Initialize the React runtime with Angular-specific configuration
|
|
22
21
|
* @param config Optional library configuration
|
|
23
22
|
* @param additionalLibraries Optional additional libraries to merge
|
|
23
|
+
* @param options Optional options including debug flag
|
|
24
24
|
* @returns Promise resolving when runtime is ready
|
|
25
25
|
*/
|
|
26
|
-
async initialize(config, additionalLibraries) {
|
|
26
|
+
async initialize(config, additionalLibraries, options) {
|
|
27
27
|
if (this.runtime) {
|
|
28
28
|
return; // Already initialized
|
|
29
29
|
}
|
|
30
30
|
// Load React ecosystem with optional additional libraries
|
|
31
|
-
const ecosystem = await this.scriptLoader.loadReactEcosystem(config, additionalLibraries);
|
|
31
|
+
const ecosystem = await this.scriptLoader.loadReactEcosystem(config, additionalLibraries, options);
|
|
32
32
|
// Create runtime context
|
|
33
33
|
this.runtimeContext = {
|
|
34
34
|
React: ecosystem.React,
|
|
@@ -120,7 +120,7 @@ export class AngularAdapterService {
|
|
|
120
120
|
// Apply default styles if not provided
|
|
121
121
|
const optionsWithDefaults = {
|
|
122
122
|
...options,
|
|
123
|
-
styles: options.styles ||
|
|
123
|
+
styles: options.styles || SetupStyles()
|
|
124
124
|
};
|
|
125
125
|
return this.runtime.compiler.compile(optionsWithDefaults);
|
|
126
126
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"angular-adapter.service.js","sourceRoot":"","sources":["../../../src/lib/services/angular-adapter.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAIL,kBAAkB,EAKnB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;;;AAGnD;;;GAGG;AAEH,MAAM,OAAO,qBAAqB;IAShC,YAAoB,YAAiC;QAAjC,iBAAY,GAAZ,YAAY,CAAqB;IAAG,CAAC;IAEzD;;;;;OAKG;IACH,KAAK,CAAC,UAAU,CACd,MAA6B,EAC7B,mBAA6C;QAE7C,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,OAAO,CAAC,sBAAsB;QAChC,CAAC;QAED,0DAA0D;QAC1D,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;QAE1F,yBAAyB;QACzB,IAAI,CAAC,cAAc,GAAG;YACpB,KAAK,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SAAS,CAAC,IAAI,EAAE;gBACnC,OAAO,EAAE,CAAC,OAAO,CAAC;gBAClB,QAAQ,EAAE,QAAQ,IAAI,eAAe;aACtC,CAAC,CAAC;YACH,OAAO,MAAM,CAAC,IAAI,CAAC;QACrB,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,4BAA4B,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC/D,CAAC;IACH,CAAC;sFAxOU,qBAAqB;uEAArB,qBAAqB,WAArB,qBAAqB,mBADR,MAAM;;iFACnB,qBAAqB;cADjC,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Angular adapter service that bridges the React runtime with Angular.\n * Provides Angular-specific functionality for the platform-agnostic React runtime.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable } from '@angular/core';\nimport { \n ComponentCompiler,\n ComponentRegistry,\n ComponentResolver,\n createReactRuntime,\n CompileOptions,\n RuntimeContext,\n ExternalLibraryConfig,\n LibraryConfiguration\n} from '@memberjunction/react-runtime';\nimport { ScriptLoaderService } from './script-loader.service';\nimport { DEFAULT_STYLES } from '../default-styles';\nimport { ComponentStyles } from '@memberjunction/interactive-component-types';\n\n/**\n * Angular-specific adapter for the React runtime.\n * Manages the integration between Angular services and the platform-agnostic React runtime.\n */\n@Injectable({ providedIn: 'root' })\nexport class AngularAdapterService {\n private runtime?: {\n compiler: ComponentCompiler;\n registry: ComponentRegistry;\n resolver: ComponentResolver;\n version: string;\n };\n private runtimeContext?: RuntimeContext;\n\n constructor(private scriptLoader: ScriptLoaderService) {}\n\n /**\n * Initialize the React runtime with Angular-specific configuration\n * @param config Optional library configuration\n * @param additionalLibraries Optional additional libraries to merge\n * @returns Promise resolving when runtime is ready\n */\n async initialize(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[]\n ): Promise<void> {\n if (this.runtime) {\n return; // Already initialized\n }\n\n // Load React ecosystem with optional additional libraries\n const ecosystem = await this.scriptLoader.loadReactEcosystem(config, additionalLibraries);\n \n // Create runtime context\n this.runtimeContext = {\n React: ecosystem.React,\n ReactDOM: ecosystem.ReactDOM,\n libraries: ecosystem.libraries,\n utilities: {\n // Add any Angular-specific utilities here\n }\n };\n\n // Create the React runtime with runtime context for registry support\n this.runtime = createReactRuntime(ecosystem.Babel, {\n compiler: {\n cache: true,\n maxCacheSize: 100\n },\n registry: {\n maxComponents: 1000,\n cleanupInterval: 60000,\n useLRU: true,\n enableNamespaces: true\n }\n }, this.runtimeContext);\n }\n\n /**\n * Get the component compiler\n * @returns Component compiler instance\n */\n getCompiler(): ComponentCompiler {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.compiler;\n }\n\n /**\n * Get the component registry\n * @returns Component registry instance\n */\n getRegistry(): ComponentRegistry {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry;\n }\n\n /**\n * Get the component resolver\n * @returns Component resolver instance\n */\n getResolver(): ComponentResolver {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.resolver;\n }\n\n /**\n * Get the runtime context\n * @returns Runtime context with React and libraries\n */\n getRuntimeContext(): RuntimeContext {\n if (!this.runtimeContext) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtimeContext;\n }\n\n\n /**\n * Compile a component with Angular-specific defaults\n * @param options - Compilation options\n * @returns Promise resolving to compilation result\n */\n async compileComponent(options: CompileOptions) {\n // Validate options before initialization\n if (!options) {\n throw new Error(\n 'Angular adapter error: No compilation options provided.\\n' +\n 'This usually means the component spec is null or undefined.\\n' +\n 'Please check that:\\n' +\n '1. Your component data is loaded properly\\n' +\n '2. The component spec has \"name\" and \"code\" properties\\n' +\n '3. The component input is not undefined'\n );\n }\n\n if (!options.componentName || options.componentName.trim() === '') {\n throw new Error(\n 'Angular adapter error: Component name is missing or empty.\\n' +\n `Received options: ${JSON.stringify(options, null, 2)}\\n` +\n 'Make sure your component spec includes a \"name\" property.'\n );\n }\n\n if (!options.componentCode || options.componentCode.trim() === '') {\n throw new Error(\n `Angular adapter error: Component code is missing or empty for component \"${options.componentName}\".\\n` +\n 'Make sure your component spec includes a \"code\" property with the React component source.'\n );\n }\n\n await this.initialize();\n \n // Apply default styles if not provided\n const optionsWithDefaults = {\n ...options,\n styles: options.styles || DEFAULT_STYLES\n };\n\n return this.runtime!.compiler.compile(optionsWithDefaults);\n }\n\n /**\n * Register a component in the registry\n * @param name - Component name\n * @param component - Compiled component\n * @param namespace - Component namespace\n * @param version - Component version\n * @returns Component metadata\n */\n registerComponent(\n name: string,\n component: any,\n namespace: string = 'Global',\n version: string = 'v1'\n ) {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry.register(name, component, namespace, version);\n }\n\n /**\n * Get a component from the registry\n * @param name - Component name\n * @param namespace - Component namespace\n * @param version - Component version\n * @returns Component if found\n */\n getComponent(name: string, namespace: string = 'Global', version?: string) {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry.get(name, namespace, version);\n }\n\n /**\n * Check if runtime is initialized\n * @returns true if initialized\n */\n isInitialized(): boolean {\n return !!this.runtime && !!this.runtimeContext;\n }\n\n /**\n * Get runtime version\n * @returns Runtime version string\n */\n getVersion(): string {\n return this.runtime?.version || 'unknown';\n }\n\n /**\n * Clean up resources\n */\n destroy(): void {\n if (this.runtime) {\n this.runtime.registry.destroy();\n this.runtime = undefined;\n this.runtimeContext = undefined;\n }\n }\n\n /**\n * Get Babel instance for direct use\n * @returns Babel instance\n */\n getBabel(): any {\n return this.runtimeContext?.libraries?.Babel || (window as any).Babel;\n }\n\n /**\n * Transpile JSX code directly\n * @param code - JSX code to transpile\n * @param filename - Optional filename for better error messages\n * @returns Transpiled JavaScript code\n */\n transpileJSX(code: string, filename?: string): string {\n const babel = this.getBabel();\n if (!babel) {\n throw new Error('Babel not loaded. Initialize the runtime first.');\n }\n\n try {\n const result = babel.transform(code, {\n presets: ['react'],\n filename: filename || 'component.jsx'\n });\n return result.code;\n } catch (error: any) {\n throw new Error(`Failed to transpile JSX: ${error.message}`);\n }\n }\n}"]}
|
|
1
|
+
{"version":3,"file":"angular-adapter.service.js","sourceRoot":"","sources":["../../../src/lib/services/angular-adapter.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAIL,kBAAkB,EAKlB,WAAW,EACZ,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;;;AAG9D;;;GAGG;AAEH,MAAM,OAAO,qBAAqB;IAShC,YAAoB,YAAiC;QAAjC,iBAAY,GAAZ,YAAY,CAAqB;IAAG,CAAC;IAEzD;;;;;;OAMG;IACH,KAAK,CAAC,UAAU,CACd,MAA6B,EAC7B,mBAA6C,EAC7C,OAA6B;QAE7B,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,OAAO,CAAC,sBAAsB;QAChC,CAAC;QAED,0DAA0D;QAC1D,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,MAAM,EAAE,mBAAmB,EAAE,OAAO,CAAC,CAAC;QAEnG,yBAAyB;QACzB,IAAI,CAAC,cAAc,GAAG;YACpB,KAAK,EAAE,SAAS,CAAC,KAAK;YACtB,QAAQ,EAAE,SAAS,CAAC,QAAQ;YAC5B,SAAS,EAAE,SAAS,CAAC,SAAS;YAC9B,SAAS,EAAE;YACT,0CAA0C;aAC3C;SACF,CAAC;QAEF,qEAAqE;QACrE,IAAI,CAAC,OAAO,GAAG,kBAAkB,CAAC,SAAS,CAAC,KAAK,EAAE;YACjD,QAAQ,EAAE;gBACR,KAAK,EAAE,IAAI;gBACX,YAAY,EAAE,GAAG;aAClB;YACD,QAAQ,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EAArB,qBAAqB,WAArB,qBAAqB,mBADR,MAAM;;iFACnB,qBAAqB;cADjC,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Angular adapter service that bridges the React runtime with Angular.\n * Provides Angular-specific functionality for the platform-agnostic React runtime.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable } from '@angular/core';\nimport { \n ComponentCompiler,\n ComponentRegistry,\n ComponentResolver,\n createReactRuntime,\n CompileOptions,\n RuntimeContext,\n ExternalLibraryConfig,\n LibraryConfiguration,\n SetupStyles\n} from '@memberjunction/react-runtime';\nimport { ScriptLoaderService } from './script-loader.service';\nimport { ComponentStyles } from '@memberjunction/interactive-component-types';\n\n/**\n * Angular-specific adapter for the React runtime.\n * Manages the integration between Angular services and the platform-agnostic React runtime.\n */\n@Injectable({ providedIn: 'root' })\nexport class AngularAdapterService {\n private runtime?: {\n compiler: ComponentCompiler;\n registry: ComponentRegistry;\n resolver: ComponentResolver;\n version: string;\n };\n private runtimeContext?: RuntimeContext;\n\n constructor(private scriptLoader: ScriptLoaderService) {}\n\n /**\n * Initialize the React runtime with Angular-specific configuration\n * @param config Optional library configuration\n * @param additionalLibraries Optional additional libraries to merge\n * @param options Optional options including debug flag\n * @returns Promise resolving when runtime is ready\n */\n async initialize(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[],\n options?: { debug?: boolean }\n ): Promise<void> {\n if (this.runtime) {\n return; // Already initialized\n }\n\n // Load React ecosystem with optional additional libraries\n const ecosystem = await this.scriptLoader.loadReactEcosystem(config, additionalLibraries, options);\n \n // Create runtime context\n this.runtimeContext = {\n React: ecosystem.React,\n ReactDOM: ecosystem.ReactDOM,\n libraries: ecosystem.libraries,\n utilities: {\n // Add any Angular-specific utilities here\n }\n };\n\n // Create the React runtime with runtime context for registry support\n this.runtime = createReactRuntime(ecosystem.Babel, {\n compiler: {\n cache: true,\n maxCacheSize: 100\n },\n registry: {\n maxComponents: 1000,\n cleanupInterval: 60000,\n useLRU: true,\n enableNamespaces: true\n }\n }, this.runtimeContext);\n }\n\n /**\n * Get the component compiler\n * @returns Component compiler instance\n */\n getCompiler(): ComponentCompiler {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.compiler;\n }\n\n /**\n * Get the component registry\n * @returns Component registry instance\n */\n getRegistry(): ComponentRegistry {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry;\n }\n\n /**\n * Get the component resolver\n * @returns Component resolver instance\n */\n getResolver(): ComponentResolver {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.resolver;\n }\n\n /**\n * Get the runtime context\n * @returns Runtime context with React and libraries\n */\n getRuntimeContext(): RuntimeContext {\n if (!this.runtimeContext) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtimeContext;\n }\n\n\n /**\n * Compile a component with Angular-specific defaults\n * @param options - Compilation options\n * @returns Promise resolving to compilation result\n */\n async compileComponent(options: CompileOptions) {\n // Validate options before initialization\n if (!options) {\n throw new Error(\n 'Angular adapter error: No compilation options provided.\\n' +\n 'This usually means the component spec is null or undefined.\\n' +\n 'Please check that:\\n' +\n '1. Your component data is loaded properly\\n' +\n '2. The component spec has \"name\" and \"code\" properties\\n' +\n '3. The component input is not undefined'\n );\n }\n\n if (!options.componentName || options.componentName.trim() === '') {\n throw new Error(\n 'Angular adapter error: Component name is missing or empty.\\n' +\n `Received options: ${JSON.stringify(options, null, 2)}\\n` +\n 'Make sure your component spec includes a \"name\" property.'\n );\n }\n\n if (!options.componentCode || options.componentCode.trim() === '') {\n throw new Error(\n `Angular adapter error: Component code is missing or empty for component \"${options.componentName}\".\\n` +\n 'Make sure your component spec includes a \"code\" property with the React component source.'\n );\n }\n\n await this.initialize();\n \n // Apply default styles if not provided\n const optionsWithDefaults = {\n ...options,\n styles: options.styles || SetupStyles()\n };\n\n return this.runtime!.compiler.compile(optionsWithDefaults);\n }\n\n /**\n * Register a component in the registry\n * @param name - Component name\n * @param component - Compiled component\n * @param namespace - Component namespace\n * @param version - Component version\n * @returns Component metadata\n */\n registerComponent(\n name: string,\n component: any,\n namespace: string = 'Global',\n version: string = 'v1'\n ) {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry.register(name, component, namespace, version);\n }\n\n /**\n * Get a component from the registry\n * @param name - Component name\n * @param namespace - Component namespace\n * @param version - Component version\n * @returns Component if found\n */\n getComponent(name: string, namespace: string = 'Global', version?: string) {\n if (!this.runtime) {\n throw new Error('React runtime not initialized. Call initialize() first.');\n }\n return this.runtime.registry.get(name, namespace, version);\n }\n\n /**\n * Check if runtime is initialized\n * @returns true if initialized\n */\n isInitialized(): boolean {\n return !!this.runtime && !!this.runtimeContext;\n }\n\n /**\n * Get runtime version\n * @returns Runtime version string\n */\n getVersion(): string {\n return this.runtime?.version || 'unknown';\n }\n\n /**\n * Clean up resources\n */\n destroy(): void {\n if (this.runtime) {\n this.runtime.registry.destroy();\n this.runtime = undefined;\n this.runtimeContext = undefined;\n }\n }\n\n /**\n * Get Babel instance for direct use\n * @returns Babel instance\n */\n getBabel(): any {\n return this.runtimeContext?.libraries?.Babel || (window as any).Babel;\n }\n\n /**\n * Transpile JSX code directly\n * @param code - JSX code to transpile\n * @param filename - Optional filename for better error messages\n * @returns Transpiled JavaScript code\n */\n transpileJSX(code: string, filename?: string): string {\n const babel = this.getBabel();\n if (!babel) {\n throw new Error('Babel not loaded. Initialize the runtime first.');\n }\n\n try {\n const result = babel.transform(code, {\n presets: ['react'],\n filename: filename || 'component.jsx'\n });\n return result.code;\n } catch (error: any) {\n throw new Error(`Failed to transpile JSX: ${error.message}`);\n }\n }\n}"]}
|
|
@@ -24,6 +24,8 @@ export class ReactBridgeService {
|
|
|
24
24
|
this.firstComponentAttempted = false;
|
|
25
25
|
this.maxWaitTime = 5000; // Maximum 5 seconds wait time
|
|
26
26
|
this.checkInterval = 200; // Check every 200ms
|
|
27
|
+
// Debug flag that can be set by components
|
|
28
|
+
this.debug = false;
|
|
27
29
|
// Bootstrap React immediately on service initialization
|
|
28
30
|
this.bootstrapReact();
|
|
29
31
|
}
|
|
@@ -35,8 +37,11 @@ export class ReactBridgeService {
|
|
|
35
37
|
*/
|
|
36
38
|
async bootstrapReact() {
|
|
37
39
|
try {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
+
// Pass debug flag to get development builds when debug is enabled
|
|
41
|
+
await this.adapter.initialize(undefined, undefined, { debug: this.debug });
|
|
42
|
+
if (this.debug) {
|
|
43
|
+
console.log('React ecosystem pre-loaded successfully with debug mode:', this.debug);
|
|
44
|
+
}
|
|
40
45
|
}
|
|
41
46
|
catch (error) {
|
|
42
47
|
console.error('Failed to pre-load React ecosystem:', error);
|
|
@@ -55,7 +60,9 @@ export class ReactBridgeService {
|
|
|
55
60
|
this.firstComponentAttempted = true;
|
|
56
61
|
if (isFirstComponent) {
|
|
57
62
|
// First component - check periodically until React is ready
|
|
58
|
-
|
|
63
|
+
if (this.debug) {
|
|
64
|
+
console.log('First React component loading - checking for React initialization');
|
|
65
|
+
}
|
|
59
66
|
const startTime = Date.now();
|
|
60
67
|
while (Date.now() - startTime < this.maxWaitTime) {
|
|
61
68
|
try {
|
|
@@ -68,7 +75,9 @@ export class ReactBridgeService {
|
|
|
68
75
|
testRoot.unmount();
|
|
69
76
|
// React is ready!
|
|
70
77
|
this.reactReadySubject.next(true);
|
|
71
|
-
|
|
78
|
+
if (this.debug) {
|
|
79
|
+
console.log(`React is fully ready after ${Date.now() - startTime}ms`);
|
|
80
|
+
}
|
|
72
81
|
return;
|
|
73
82
|
}
|
|
74
83
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-bridge.service.js","sourceRoot":"","sources":["../../../src/lib/services/react-bridge.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAa,MAAM,eA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H,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAED;;;;;OAKG;IACH,YAAY,CAAC,IAAY,EAAE,QAAgB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACnD,CAAC;IAED;;OAEG;IACK,OAAO;QACb,kCAAkC;QAClC,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACnC,IAAI,CAAC;gBACH,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,KAAK,CAAC,CAAC;YACvD,CAAC;QACH,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QAExB,wBAAwB;QACxB,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnC,IAAI,CAAC,uBAAuB,GAAG,KAAK,CAAC;QAErC,mBAAmB;QACnB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC;IACtC,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;IAC9B,CAAC;mFAvLU,kBAAkB;uEAAlB,kBAAkB,WAAlB,kBAAkB,mBADL,MAAM;;iFACnB,kBAAkB;cAD9B,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Service to manage React and ReactDOM instances with proper lifecycle.\n * Bridges Angular components with React rendering capabilities.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable, OnDestroy } from '@angular/core';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\nimport { filter } from 'rxjs/operators';\nimport { AngularAdapterService } from './angular-adapter.service';\nimport { RuntimeContext } from '@memberjunction/react-runtime';\n\n/**\n * Service to manage React and ReactDOM instances with proper lifecycle.\n * Provides methods for creating and managing React roots in Angular applications.\n */\n@Injectable({ providedIn: 'root' })\nexport class ReactBridgeService implements OnDestroy {\n private reactRoots = new Set<any>();\n \n // Track React readiness state\n private reactReadySubject = new BehaviorSubject<boolean>(false);\n public reactReady$ = this.reactReadySubject.asObservable();\n \n // Track if this is the first component trying to use React\n private firstComponentAttempted = false;\n private maxWaitTime = 5000; // Maximum 5 seconds wait time\n private checkInterval = 200; // Check every 200ms\n\n constructor(private adapter: AngularAdapterService) {\n // Bootstrap React immediately on service initialization\n this.bootstrapReact();\n }\n\n ngOnDestroy(): void {\n this.cleanup();\n }\n\n /**\n * Bootstrap React early during service initialization\n */\n private async bootstrapReact(): Promise<void> {\n try {\n await this.adapter.initialize();\n console.log('React ecosystem pre-loaded successfully');\n } catch (error) {\n console.error('Failed to pre-load React ecosystem:', error);\n }\n }\n\n /**\n * Wait for React to be ready, with special handling for first component\n */\n async waitForReactReady(): Promise<void> {\n // If already ready, return immediately\n if (this.reactReadySubject.value) {\n return;\n }\n\n // Check if this is the first component attempting to use React\n const isFirstComponent = !this.firstComponentAttempted;\n this.firstComponentAttempted = true;\n\n if (isFirstComponent) {\n // First component - check periodically until React is ready\n console.log('First React component loading - checking for React initialization');\n \n const startTime = Date.now();\n \n while (Date.now() - startTime < this.maxWaitTime) {\n try {\n const testDiv = document.createElement('div');\n const context = this.adapter.getRuntimeContext();\n \n if (context.ReactDOM?.createRoot) {\n // Try to create a test root\n const testRoot = context.ReactDOM.createRoot(testDiv);\n if (testRoot) {\n testRoot.unmount();\n // React is ready!\n this.reactReadySubject.next(true);\n console.log(`React is fully ready after ${Date.now() - startTime}ms`);\n return;\n }\n }\n } catch (error) {\n // Not ready yet, continue checking\n }\n \n // Wait before next check\n await new Promise(resolve => setTimeout(resolve, this.checkInterval));\n }\n \n // If we've exhausted the wait time, throw error\n console.error('React readiness test failed after maximum wait time');\n this.firstComponentAttempted = false;\n throw new Error(`ReactDOM.createRoot not available after ${this.maxWaitTime}ms`);\n } else {\n // Subsequent components wait for the ready signal\n await firstValueFrom(this.reactReady$.pipe(filter(ready => ready)));\n }\n }\n\n /**\n * Get the current React context if loaded\n * @returns React context with React, ReactDOM, Babel, and libraries\n */\n async getReactContext(): Promise<RuntimeContext> {\n await this.adapter.initialize();\n return this.adapter.getRuntimeContext();\n }\n\n /**\n * Get the current React context synchronously\n * @returns React context or null if not loaded\n */\n getCurrentContext(): RuntimeContext | null {\n if (!this.adapter.isInitialized()) {\n return null;\n }\n return this.adapter.getRuntimeContext();\n }\n\n /**\n * Create a React root for rendering\n * @param container - DOM element to render into\n * @returns React root instance\n */\n createRoot(container: HTMLElement): any {\n const context = this.getCurrentContext();\n if (!context?.ReactDOM?.createRoot) {\n throw new Error('ReactDOM.createRoot not available');\n }\n\n const root = context.ReactDOM.createRoot(container);\n this.reactRoots.add(root);\n return root;\n }\n\n /**\n * Unmount and clean up a React root\n * @param root - React root to unmount\n */\n unmountRoot(root: any): void {\n if (root && typeof root.unmount === 'function') {\n try {\n root.unmount();\n } catch (error) {\n console.warn('Failed to unmount React root:', error);\n }\n }\n this.reactRoots.delete(root);\n }\n\n /**\n * Transpile JSX code to JavaScript\n * @param code - JSX code to transpile\n * @param filename - Optional filename for error messages\n * @returns Transpiled JavaScript code\n */\n transpileJSX(code: string, filename: string): string {\n return this.adapter.transpileJSX(code, filename);\n }\n\n /**\n * Clean up all React roots and reset context\n */\n private cleanup(): void {\n // Unmount all tracked React roots\n for (const root of this.reactRoots) {\n try {\n root.unmount();\n } catch (error) {\n console.warn('Failed to unmount React root:', error);\n }\n }\n this.reactRoots.clear();\n \n // Reset readiness state\n this.reactReadySubject.next(false);\n this.firstComponentAttempted = false;\n\n // Clean up adapter\n this.adapter.destroy();\n }\n\n /**\n * Check if React is currently ready\n * @returns true if React is ready\n */\n isReady(): boolean {\n return this.reactReadySubject.value;\n }\n\n /**\n * Get the number of active React roots\n * @returns Number of active roots\n */\n getActiveRootsCount(): number {\n return this.reactRoots.size;\n }\n}"]}
|
|
1
|
+
{"version":3,"file":"react-bridge.service.js","sourceRoot":"","sources":["../../../src/lib/services/react-bridge.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAa,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;;;AAGlE;;;GAGG;AAEH,MAAM,OAAO,kBAAkB;IAe7B,YAAoB,OAA8B;QAA9B,YAAO,GAAP,OAAO,CAAuB;QAd1C,eAAU,GAAG,IAAI,GAAG,EAAO,CAAC;QAEpC,8BAA8B;QACtB,sBAAiB,GAAG,IAAI,eAAe,CAAU,KAAK,CAAC,CAAC;QACzD,gBAAW,GAAG,IAAI,CAAC,iBAAiB,CAAC,YAAY,EAAE,CAAC;QAE3D,2DAA2D;QACnD,4BAAuB,GAAG,KAAK,CAAC;QAChC,gBAAW,GAAG,IAAI,CAAC,CAAC,8BAA8B;QAClD,kBAAa,GAAG,GAAG,CAAC,CAAC,oBAAoB;QAEjD,2CAA2C;QACpC,UAAK,GAAY,KAAK,CAAC;QAG5B,wDAAwD;QACxD,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED,WAAW;QACT,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,cAAc;QAC1B,IAAI,CAAC;YACH,kEAAkE;YAClE,MAAM,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;YAC3E,IAAI,IAAI,CAAC,K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K,CAAC;QAErC,mBAAmB;QACnB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC;IACtC,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;IAC9B,CAAC;mFAjMU,kBAAkB;uEAAlB,kBAAkB,WAAlB,kBAAkB,mBADL,MAAM;;iFACnB,kBAAkB;cAD9B,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Service to manage React and ReactDOM instances with proper lifecycle.\n * Bridges Angular components with React rendering capabilities.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable, OnDestroy } from '@angular/core';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\nimport { filter } from 'rxjs/operators';\nimport { AngularAdapterService } from './angular-adapter.service';\nimport { RuntimeContext } from '@memberjunction/react-runtime';\n\n/**\n * Service to manage React and ReactDOM instances with proper lifecycle.\n * Provides methods for creating and managing React roots in Angular applications.\n */\n@Injectable({ providedIn: 'root' })\nexport class ReactBridgeService implements OnDestroy {\n private reactRoots = new Set<any>();\n \n // Track React readiness state\n private reactReadySubject = new BehaviorSubject<boolean>(false);\n public reactReady$ = this.reactReadySubject.asObservable();\n \n // Track if this is the first component trying to use React\n private firstComponentAttempted = false;\n private maxWaitTime = 5000; // Maximum 5 seconds wait time\n private checkInterval = 200; // Check every 200ms\n \n // Debug flag that can be set by components\n public debug: boolean = false;\n\n constructor(private adapter: AngularAdapterService) {\n // Bootstrap React immediately on service initialization\n this.bootstrapReact();\n }\n\n ngOnDestroy(): void {\n this.cleanup();\n }\n\n /**\n * Bootstrap React early during service initialization\n */\n private async bootstrapReact(): Promise<void> {\n try {\n // Pass debug flag to get development builds when debug is enabled\n await this.adapter.initialize(undefined, undefined, { debug: this.debug });\n if (this.debug) {\n console.log('React ecosystem pre-loaded successfully with debug mode:', this.debug);\n }\n } catch (error) {\n console.error('Failed to pre-load React ecosystem:', error);\n }\n }\n\n /**\n * Wait for React to be ready, with special handling for first component\n */\n async waitForReactReady(): Promise<void> {\n // If already ready, return immediately\n if (this.reactReadySubject.value) {\n return;\n }\n\n // Check if this is the first component attempting to use React\n const isFirstComponent = !this.firstComponentAttempted;\n this.firstComponentAttempted = true;\n\n if (isFirstComponent) {\n // First component - check periodically until React is ready\n if (this.debug) {\n console.log('First React component loading - checking for React initialization');\n }\n \n const startTime = Date.now();\n \n while (Date.now() - startTime < this.maxWaitTime) {\n try {\n const testDiv = document.createElement('div');\n const context = this.adapter.getRuntimeContext();\n \n if (context.ReactDOM?.createRoot) {\n // Try to create a test root\n const testRoot = context.ReactDOM.createRoot(testDiv);\n if (testRoot) {\n testRoot.unmount();\n // React is ready!\n this.reactReadySubject.next(true);\n if (this.debug) {\n console.log(`React is fully ready after ${Date.now() - startTime}ms`);\n }\n return;\n }\n }\n } catch (error) {\n // Not ready yet, continue checking\n }\n \n // Wait before next check\n await new Promise(resolve => setTimeout(resolve, this.checkInterval));\n }\n \n // If we've exhausted the wait time, throw error\n console.error('React readiness test failed after maximum wait time');\n this.firstComponentAttempted = false;\n throw new Error(`ReactDOM.createRoot not available after ${this.maxWaitTime}ms`);\n } else {\n // Subsequent components wait for the ready signal\n await firstValueFrom(this.reactReady$.pipe(filter(ready => ready)));\n }\n }\n\n /**\n * Get the current React context if loaded\n * @returns React context with React, ReactDOM, Babel, and libraries\n */\n async getReactContext(): Promise<RuntimeContext> {\n await this.adapter.initialize();\n return this.adapter.getRuntimeContext();\n }\n\n /**\n * Get the current React context synchronously\n * @returns React context or null if not loaded\n */\n getCurrentContext(): RuntimeContext | null {\n if (!this.adapter.isInitialized()) {\n return null;\n }\n return this.adapter.getRuntimeContext();\n }\n\n /**\n * Create a React root for rendering\n * @param container - DOM element to render into\n * @returns React root instance\n */\n createRoot(container: HTMLElement): any {\n const context = this.getCurrentContext();\n if (!context?.ReactDOM?.createRoot) {\n throw new Error('ReactDOM.createRoot not available');\n }\n\n const root = context.ReactDOM.createRoot(container);\n this.reactRoots.add(root);\n return root;\n }\n\n /**\n * Unmount and clean up a React root\n * @param root - React root to unmount\n */\n unmountRoot(root: any): void {\n if (root && typeof root.unmount === 'function') {\n try {\n root.unmount();\n } catch (error) {\n console.warn('Failed to unmount React root:', error);\n }\n }\n this.reactRoots.delete(root);\n }\n\n /**\n * Transpile JSX code to JavaScript\n * @param code - JSX code to transpile\n * @param filename - Optional filename for error messages\n * @returns Transpiled JavaScript code\n */\n transpileJSX(code: string, filename: string): string {\n return this.adapter.transpileJSX(code, filename);\n }\n\n /**\n * Clean up all React roots and reset context\n */\n private cleanup(): void {\n // Unmount all tracked React roots\n for (const root of this.reactRoots) {\n try {\n root.unmount();\n } catch (error) {\n console.warn('Failed to unmount React root:', error);\n }\n }\n this.reactRoots.clear();\n \n // Reset readiness state\n this.reactReadySubject.next(false);\n this.firstComponentAttempted = false;\n\n // Clean up adapter\n this.adapter.destroy();\n }\n\n /**\n * Check if React is currently ready\n * @returns true if React is ready\n */\n isReady(): boolean {\n return this.reactReadySubject.value;\n }\n\n /**\n * Get the number of active React roots\n * @returns Number of active roots\n */\n getActiveRootsCount(): number {\n return this.reactRoots.size;\n }\n}"]}
|
|
@@ -40,9 +40,12 @@ export declare class ScriptLoaderService implements OnDestroy {
|
|
|
40
40
|
* Load common React libraries and UI frameworks
|
|
41
41
|
* @param config Optional library configuration
|
|
42
42
|
* @param additionalLibraries Optional additional libraries to merge
|
|
43
|
+
* @param options Optional options including debug flag
|
|
43
44
|
* @returns Promise resolving to React ecosystem objects
|
|
44
45
|
*/
|
|
45
|
-
loadReactEcosystem(config?: LibraryConfiguration, additionalLibraries?: ExternalLibraryConfig[]
|
|
46
|
+
loadReactEcosystem(config?: LibraryConfiguration, additionalLibraries?: ExternalLibraryConfig[], options?: {
|
|
47
|
+
debug?: boolean;
|
|
48
|
+
}): Promise<{
|
|
46
49
|
React: any;
|
|
47
50
|
ReactDOM: any;
|
|
48
51
|
Babel: any;
|
|
@@ -93,11 +93,12 @@ export class ScriptLoaderService {
|
|
|
93
93
|
* Load common React libraries and UI frameworks
|
|
94
94
|
* @param config Optional library configuration
|
|
95
95
|
* @param additionalLibraries Optional additional libraries to merge
|
|
96
|
+
* @param options Optional options including debug flag
|
|
96
97
|
* @returns Promise resolving to React ecosystem objects
|
|
97
98
|
*/
|
|
98
|
-
async loadReactEcosystem(config, additionalLibraries) {
|
|
99
|
+
async loadReactEcosystem(config, additionalLibraries, options) {
|
|
99
100
|
// Use the new LibraryLoader from react-runtime for consistency
|
|
100
|
-
const result = await LibraryLoader.loadAllLibraries(config, additionalLibraries);
|
|
101
|
+
const result = await LibraryLoader.loadAllLibraries(config, additionalLibraries, options);
|
|
101
102
|
// The LibraryLoader handles all the loading, but we need to ensure
|
|
102
103
|
// ReactDOM.createRoot is available for Angular's specific needs
|
|
103
104
|
// The ReactBridgeService will handle the delayed validation
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"script-loader.service.js","sourceRoot":"","sources":["../../../src/lib/services/script-loader.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAa,MAAM,eAAe,CAAC;AACtD,OAAO,EACL,aAAa,EAGd,MAAM,+BAA+B,CAAC;;AAUvC;;;GAGG;AAEH,MAAM,OAAO,mBAAmB;IADhC;QAEU,oBAAe,GAAG,IAAI,GAAG,EAAwB,CAAC;QACzC,qBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;KAkYvD;IAhYC,WAAW;QACT,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,UAAU,CAAC,GAAW,EAAE,UAAkB,EAAE,WAAW,GAAG,KAAK;QACnE,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/C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AAkB;YAClB,MAAM,WAAW,GAAG,GAAG,EAAE;gBACvB,MAAM,CAAC,mBAAmB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;gBAChD,WAAW,EAAE,CAAC;YAChB,CAAC,CAAC;YACF,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACK,+BAA+B,CACrC,MAAyB,EACzB,UAAkB,EAClB,SAAgC,EAChC,OAA6B,EAC7B,MAA6B;QAE7B,MAAM,WAAW,GAAG,GAAG,EAAE;YACvB,IAAI,CAAC,iBAAiB,CAAC,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QACjE,CAAC,CAAC;QAEF,IAAI,YAAY,IAAI,MAAM,EAAE,CAAC;YAC3B,aAAa;YACZ,MAAc,CAAC,kBAAkB,GAAG,GAAG,EAAE;gBACxC,IAAK,MAAc,CAAC,UAAU,KAAK,QAAQ,IAAK,MAAc,CAAC,UAAU,KAAK,UAAU,EAAE,CAAC;oBACxF,MAAc,CAAC,kBAAkB,GAAG,IAAI,CAAC;oBAC1C,WAAW,EAAE,CAAC;gBAChB,CAAC;YACH,CAAC,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,kBAAkB;YAClB,MAAM,WAAW,GAAG,GAAG,EAAE;gBACvB,MAAM,CAAC,mBAAmB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;gBAChD,WAAW,EAAE,CAAC;YAChB,CAAC,CAAC;YACF,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;oFAnYU,mBAAmB;uEAAnB,mBAAmB,WAAnB,mBAAmB,mBADN,MAAM;;iFACnB,mBAAmB;cAD/B,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Service for loading external scripts and CSS in Angular applications.\n * Manages the lifecycle of dynamically loaded resources with proper cleanup.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable, OnDestroy } from '@angular/core';\nimport { \n LibraryLoader,\n LibraryConfiguration,\n ExternalLibraryConfig\n} from '@memberjunction/react-runtime';\n\n/**\n * Represents a loaded script or CSS resource\n */\ninterface LoadedScript {\n element: HTMLScriptElement | HTMLLinkElement;\n promise: Promise<any>;\n}\n\n/**\n * Service for loading external scripts and CSS with proper cleanup.\n * Provides methods to dynamically load React and related libraries from CDN.\n */\n@Injectable({ providedIn: 'root' })\nexport class ScriptLoaderService implements OnDestroy {\n private loadedResources = new Map<string, LoadedScript>();\n private readonly cleanupOnDestroy = new Set<string>();\n\n ngOnDestroy(): void {\n this.cleanup();\n }\n\n /**\n * Load a script from URL with automatic cleanup tracking\n * @param url - Script URL to load\n * @param globalName - Expected global variable name\n * @param autoCleanup - Whether to cleanup on service destroy\n * @returns Promise resolving to the global object\n */\n async loadScript(url: string, globalName: string, autoCleanup = false): Promise<any> {\n const existing = this.loadedResources.get(url);\n if (existing) {\n return existing.promise;\n }\n\n const promise = this.createScriptPromise(url, globalName);\n const element = document.querySelector(`script[src=\"${url}\"]`) as HTMLScriptElement;\n \n if (element) {\n this.loadedResources.set(url, { element, promise });\n if (autoCleanup) {\n this.cleanupOnDestroy.add(url);\n }\n }\n\n return promise;\n }\n\n /**\n * Load a script with additional validation function\n * @param url - Script URL to load\n * @param globalName - Expected global variable name\n * @param validator - Function to validate the loaded object\n * @param autoCleanup - Whether to cleanup on service destroy\n * @returns Promise resolving to the validated global object\n */\n async loadScriptWithValidation(\n url: string, \n globalName: string, \n validator: (obj: any) => boolean,\n autoCleanup = false\n ): Promise<any> {\n const existing = this.loadedResources.get(url);\n if (existing) {\n const obj = await existing.promise;\n // Re-validate even for cached resources\n if (!validator(obj)) {\n throw new Error(`${globalName} loaded but failed validation`);\n }\n return obj;\n }\n\n const promise = this.createScriptPromiseWithValidation(url, globalName, validator);\n const element = document.querySelector(`script[src=\"${url}\"]`) as HTMLScriptElement;\n \n if (element) {\n this.loadedResources.set(url, { element, promise });\n if (autoCleanup) {\n this.cleanupOnDestroy.add(url);\n }\n }\n\n return promise;\n }\n\n /**\n * Load CSS from URL\n * @param url - CSS URL to load\n */\n loadCSS(url: string): void {\n if (this.loadedResources.has(url)) {\n return;\n }\n\n const existingLink = document.querySelector(`link[href=\"${url}\"]`);\n if (existingLink) {\n return;\n }\n\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = url;\n document.head.appendChild(link);\n\n this.loadedResources.set(url, {\n element: link,\n promise: Promise.resolve()\n });\n }\n\n /**\n * Load common React libraries and UI frameworks\n * @param config Optional library configuration\n * @param additionalLibraries Optional additional libraries to merge\n * @returns Promise resolving to React ecosystem objects\n */\n async loadReactEcosystem(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[]\n ): Promise<{\n React: any;\n ReactDOM: any;\n Babel: any;\n libraries: any;\n }> {\n // Use the new LibraryLoader from react-runtime for consistency\n const result = await LibraryLoader.loadAllLibraries(config, additionalLibraries);\n \n // The LibraryLoader handles all the loading, but we need to ensure\n // ReactDOM.createRoot is available for Angular's specific needs\n // The ReactBridgeService will handle the delayed validation\n \n // Track loaded resources for cleanup\n LibraryLoader.getLoadedResources().forEach((resource, url) => {\n this.loadedResources.set(url, resource);\n });\n \n return result;\n }\n\n /**\n * Get library name from URL for global variable mapping\n * @param url - Library URL\n * @returns Global variable name\n */\n private getLibraryNameFromUrl(url: string): string {\n // Map known URLs to their global variable names\n if (url.includes('lodash')) return '_';\n if (url.includes('d3')) return 'd3';\n if (url.includes('Chart.js') || url.includes('chart')) return 'Chart';\n if (url.includes('dayjs')) return 'dayjs';\n if (url.includes('antd')) return 'antd';\n if (url.includes('react-bootstrap')) return 'ReactBootstrap';\n if (url.includes('react-dom')) return 'ReactDOM';\n if (url.includes('react')) return 'React';\n if (url.includes('babel')) return 'Babel';\n \n // Default: extract library name from filename\n const match = url.match(/\\/([^/]+?)(?:\\.min)?\\.js$/i);\n return match ? match[1] : 'UnknownLibrary';\n }\n\n /**\n * Remove a specific loaded resource\n * @param url - URL of resource to remove\n */\n removeResource(url: string): void {\n const resource = this.loadedResources.get(url);\n if (resource?.element && resource.element.parentNode) {\n resource.element.parentNode.removeChild(resource.element);\n }\n this.loadedResources.delete(url);\n this.cleanupOnDestroy.delete(url);\n }\n\n /**\n * Clean up all resources marked for auto-cleanup\n */\n private cleanup(): void {\n for (const url of this.cleanupOnDestroy) {\n this.removeResource(url);\n }\n this.cleanupOnDestroy.clear();\n }\n\n /**\n * Create a promise that resolves when script loads\n * @param url - Script URL\n * @param globalName - Expected global variable\n * @returns Promise resolving to global object\n */\n private createScriptPromise(url: string, globalName: string): Promise<any> {\n return new Promise((resolve, reject) => {\n // Check if already loaded\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n return;\n }\n\n // Check if script tag exists\n const existingScript = document.querySelector(`script[src=\"${url}\"]`);\n if (existingScript) {\n this.waitForScriptLoad(existingScript as HTMLScriptElement, globalName, resolve, reject);\n return;\n }\n\n // Create new script\n const script = document.createElement('script');\n script.src = url;\n script.async = true;\n\n script.onload = () => {\n const global = (window as any)[globalName];\n if (global) {\n resolve(global);\n } else {\n reject(new Error(`${globalName} not found after script load`));\n }\n };\n\n script.onerror = () => {\n reject(new Error(`Failed to load script: ${url}`));\n };\n\n document.head.appendChild(script);\n this.loadedResources.set(url, { element: script, promise: Promise.resolve() });\n });\n }\n\n /**\n * Create a promise that resolves when script loads and passes validation\n * @param url - Script URL\n * @param globalName - Expected global variable\n * @param validator - Validation function\n * @returns Promise resolving to validated global object\n */\n private createScriptPromiseWithValidation(\n url: string, \n globalName: string, \n validator: (obj: any) => boolean\n ): Promise<any> {\n return new Promise((resolve, reject) => {\n // Check if already loaded and valid\n const existingGlobal = (window as any)[globalName];\n if (existingGlobal && validator(existingGlobal)) {\n resolve(existingGlobal);\n return;\n }\n\n // Check if script tag exists\n const existingScript = document.querySelector(`script[src=\"${url}\"]`);\n if (existingScript) {\n this.waitForScriptLoadWithValidation(\n existingScript as HTMLScriptElement, \n globalName, \n validator,\n resolve, \n reject\n );\n return;\n }\n\n // Create new script\n const script = document.createElement('script');\n script.src = url;\n script.async = true;\n\n script.onload = () => {\n this.waitForValidation(globalName, validator, resolve, reject);\n };\n\n script.onerror = () => {\n reject(new Error(`Failed to load script: ${url}`));\n };\n\n document.head.appendChild(script);\n this.loadedResources.set(url, { element: script, promise: Promise.resolve() });\n });\n }\n\n /**\n * Wait for global object to be available and valid\n * @param globalName - Global variable name\n * @param validator - Validation function\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n * @param attempts - Current attempt number\n * @param maxAttempts - Maximum attempts before failing\n */\n private waitForValidation(\n globalName: string,\n validator: (obj: any) => boolean,\n resolve: (value: any) => void,\n reject: (reason: any) => void,\n attempts = 0,\n maxAttempts = 50 // 5 seconds total with 100ms intervals\n ): void {\n const global = (window as any)[globalName];\n \n if (global && validator(global)) {\n resolve(global);\n return;\n }\n\n if (attempts >= maxAttempts) {\n if (global) {\n reject(new Error(`${globalName} loaded but validation failed after ${maxAttempts} attempts`));\n } else {\n reject(new Error(`${globalName} not found after ${maxAttempts} attempts`));\n }\n return;\n }\n\n // Retry with exponential backoff for first few attempts, then fixed interval\n const delay = attempts < 5 ? Math.min(100 * Math.pow(1.5, attempts), 500) : 100;\n setTimeout(() => {\n this.waitForValidation(globalName, validator, resolve, reject, attempts + 1, maxAttempts);\n }, delay);\n }\n\n /**\n * Wait for existing script to load\n * @param script - Script element\n * @param globalName - Expected global variable\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n */\n private waitForScriptLoad(\n script: HTMLScriptElement,\n globalName: string,\n resolve: (value: any) => void,\n reject: (reason: any) => void\n ): void {\n const checkGlobal = () => {\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n return;\n }\n // Give it a moment for the global to be defined\n setTimeout(() => {\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n } else {\n reject(new Error(`${globalName} not found after script load`));\n }\n }, 100);\n };\n\n if ('readyState' in script) {\n // IE support\n (script as any).onreadystatechange = () => {\n if ((script as any).readyState === 'loaded' || (script as any).readyState === 'complete') {\n (script as any).onreadystatechange = null;\n checkGlobal();\n }\n };\n } else {\n // Modern browsers\n const loadHandler = () => {\n script.removeEventListener('load', loadHandler);\n checkGlobal();\n };\n script.addEventListener('load', loadHandler);\n }\n }\n\n /**\n * Wait for existing script to load with validation\n * @param script - Script element\n * @param globalName - Expected global variable\n * @param validator - Validation function\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n */\n private waitForScriptLoadWithValidation(\n script: HTMLScriptElement,\n globalName: string,\n validator: (obj: any) => boolean,\n resolve: (value: any) => void,\n reject: (reason: any) => void\n ): void {\n const checkGlobal = () => {\n this.waitForValidation(globalName, validator, resolve, reject);\n };\n\n if ('readyState' in script) {\n // IE support\n (script as any).onreadystatechange = () => {\n if ((script as any).readyState === 'loaded' || (script as any).readyState === 'complete') {\n (script as any).onreadystatechange = null;\n checkGlobal();\n }\n };\n } else {\n // Modern browsers\n const loadHandler = () => {\n script.removeEventListener('load', loadHandler);\n checkGlobal();\n };\n script.addEventListener('load', loadHandler);\n }\n }\n}"]}
|
|
1
|
+
{"version":3,"file":"script-loader.service.js","sourceRoot":"","sources":["../../../src/lib/services/script-loader.service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAa,MAAM,eAAe,CAAC;AACtD,OAAO,EACL,aAAa,EAGd,MAAM,+BAA+B,CAAC;;AAUvC;;;GAGG;AAEH,MAAM,OAAO,mBAAmB;IADhC;QAEU,oBAAe,GAAG,IAAI,GAAG,EAAwB,CAAC;QACzC,qBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;KAoYvD;IAlYC,WAAW;QACT,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,UAAU,CAAC,GAAW,EAAE,UAAkB,EAAE,WAA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mBAAmB;cAD/B,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["/**\n * @fileoverview Service for loading external scripts and CSS in Angular applications.\n * Manages the lifecycle of dynamically loaded resources with proper cleanup.\n * @module @memberjunction/ng-react\n */\n\nimport { Injectable, OnDestroy } from '@angular/core';\nimport { \n LibraryLoader,\n LibraryConfiguration,\n ExternalLibraryConfig\n} from '@memberjunction/react-runtime';\n\n/**\n * Represents a loaded script or CSS resource\n */\ninterface LoadedScript {\n element: HTMLScriptElement | HTMLLinkElement;\n promise: Promise<any>;\n}\n\n/**\n * Service for loading external scripts and CSS with proper cleanup.\n * Provides methods to dynamically load React and related libraries from CDN.\n */\n@Injectable({ providedIn: 'root' })\nexport class ScriptLoaderService implements OnDestroy {\n private loadedResources = new Map<string, LoadedScript>();\n private readonly cleanupOnDestroy = new Set<string>();\n\n ngOnDestroy(): void {\n this.cleanup();\n }\n\n /**\n * Load a script from URL with automatic cleanup tracking\n * @param url - Script URL to load\n * @param globalName - Expected global variable name\n * @param autoCleanup - Whether to cleanup on service destroy\n * @returns Promise resolving to the global object\n */\n async loadScript(url: string, globalName: string, autoCleanup = false): Promise<any> {\n const existing = this.loadedResources.get(url);\n if (existing) {\n return existing.promise;\n }\n\n const promise = this.createScriptPromise(url, globalName);\n const element = document.querySelector(`script[src=\"${url}\"]`) as HTMLScriptElement;\n \n if (element) {\n this.loadedResources.set(url, { element, promise });\n if (autoCleanup) {\n this.cleanupOnDestroy.add(url);\n }\n }\n\n return promise;\n }\n\n /**\n * Load a script with additional validation function\n * @param url - Script URL to load\n * @param globalName - Expected global variable name\n * @param validator - Function to validate the loaded object\n * @param autoCleanup - Whether to cleanup on service destroy\n * @returns Promise resolving to the validated global object\n */\n async loadScriptWithValidation(\n url: string, \n globalName: string, \n validator: (obj: any) => boolean,\n autoCleanup = false\n ): Promise<any> {\n const existing = this.loadedResources.get(url);\n if (existing) {\n const obj = await existing.promise;\n // Re-validate even for cached resources\n if (!validator(obj)) {\n throw new Error(`${globalName} loaded but failed validation`);\n }\n return obj;\n }\n\n const promise = this.createScriptPromiseWithValidation(url, globalName, validator);\n const element = document.querySelector(`script[src=\"${url}\"]`) as HTMLScriptElement;\n \n if (element) {\n this.loadedResources.set(url, { element, promise });\n if (autoCleanup) {\n this.cleanupOnDestroy.add(url);\n }\n }\n\n return promise;\n }\n\n /**\n * Load CSS from URL\n * @param url - CSS URL to load\n */\n loadCSS(url: string): void {\n if (this.loadedResources.has(url)) {\n return;\n }\n\n const existingLink = document.querySelector(`link[href=\"${url}\"]`);\n if (existingLink) {\n return;\n }\n\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = url;\n document.head.appendChild(link);\n\n this.loadedResources.set(url, {\n element: link,\n promise: Promise.resolve()\n });\n }\n\n /**\n * Load common React libraries and UI frameworks\n * @param config Optional library configuration\n * @param additionalLibraries Optional additional libraries to merge\n * @param options Optional options including debug flag\n * @returns Promise resolving to React ecosystem objects\n */\n async loadReactEcosystem(\n config?: LibraryConfiguration,\n additionalLibraries?: ExternalLibraryConfig[],\n options?: { debug?: boolean }\n ): Promise<{\n React: any;\n ReactDOM: any;\n Babel: any;\n libraries: any;\n }> {\n // Use the new LibraryLoader from react-runtime for consistency\n const result = await LibraryLoader.loadAllLibraries(config, additionalLibraries, options);\n \n // The LibraryLoader handles all the loading, but we need to ensure\n // ReactDOM.createRoot is available for Angular's specific needs\n // The ReactBridgeService will handle the delayed validation\n \n // Track loaded resources for cleanup\n LibraryLoader.getLoadedResources().forEach((resource, url) => {\n this.loadedResources.set(url, resource);\n });\n \n return result;\n }\n\n /**\n * Get library name from URL for global variable mapping\n * @param url - Library URL\n * @returns Global variable name\n */\n private getLibraryNameFromUrl(url: string): string {\n // Map known URLs to their global variable names\n if (url.includes('lodash')) return '_';\n if (url.includes('d3')) return 'd3';\n if (url.includes('Chart.js') || url.includes('chart')) return 'Chart';\n if (url.includes('dayjs')) return 'dayjs';\n if (url.includes('antd')) return 'antd';\n if (url.includes('react-bootstrap')) return 'ReactBootstrap';\n if (url.includes('react-dom')) return 'ReactDOM';\n if (url.includes('react')) return 'React';\n if (url.includes('babel')) return 'Babel';\n \n // Default: extract library name from filename\n const match = url.match(/\\/([^/]+?)(?:\\.min)?\\.js$/i);\n return match ? match[1] : 'UnknownLibrary';\n }\n\n /**\n * Remove a specific loaded resource\n * @param url - URL of resource to remove\n */\n removeResource(url: string): void {\n const resource = this.loadedResources.get(url);\n if (resource?.element && resource.element.parentNode) {\n resource.element.parentNode.removeChild(resource.element);\n }\n this.loadedResources.delete(url);\n this.cleanupOnDestroy.delete(url);\n }\n\n /**\n * Clean up all resources marked for auto-cleanup\n */\n private cleanup(): void {\n for (const url of this.cleanupOnDestroy) {\n this.removeResource(url);\n }\n this.cleanupOnDestroy.clear();\n }\n\n /**\n * Create a promise that resolves when script loads\n * @param url - Script URL\n * @param globalName - Expected global variable\n * @returns Promise resolving to global object\n */\n private createScriptPromise(url: string, globalName: string): Promise<any> {\n return new Promise((resolve, reject) => {\n // Check if already loaded\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n return;\n }\n\n // Check if script tag exists\n const existingScript = document.querySelector(`script[src=\"${url}\"]`);\n if (existingScript) {\n this.waitForScriptLoad(existingScript as HTMLScriptElement, globalName, resolve, reject);\n return;\n }\n\n // Create new script\n const script = document.createElement('script');\n script.src = url;\n script.async = true;\n\n script.onload = () => {\n const global = (window as any)[globalName];\n if (global) {\n resolve(global);\n } else {\n reject(new Error(`${globalName} not found after script load`));\n }\n };\n\n script.onerror = () => {\n reject(new Error(`Failed to load script: ${url}`));\n };\n\n document.head.appendChild(script);\n this.loadedResources.set(url, { element: script, promise: Promise.resolve() });\n });\n }\n\n /**\n * Create a promise that resolves when script loads and passes validation\n * @param url - Script URL\n * @param globalName - Expected global variable\n * @param validator - Validation function\n * @returns Promise resolving to validated global object\n */\n private createScriptPromiseWithValidation(\n url: string, \n globalName: string, \n validator: (obj: any) => boolean\n ): Promise<any> {\n return new Promise((resolve, reject) => {\n // Check if already loaded and valid\n const existingGlobal = (window as any)[globalName];\n if (existingGlobal && validator(existingGlobal)) {\n resolve(existingGlobal);\n return;\n }\n\n // Check if script tag exists\n const existingScript = document.querySelector(`script[src=\"${url}\"]`);\n if (existingScript) {\n this.waitForScriptLoadWithValidation(\n existingScript as HTMLScriptElement, \n globalName, \n validator,\n resolve, \n reject\n );\n return;\n }\n\n // Create new script\n const script = document.createElement('script');\n script.src = url;\n script.async = true;\n\n script.onload = () => {\n this.waitForValidation(globalName, validator, resolve, reject);\n };\n\n script.onerror = () => {\n reject(new Error(`Failed to load script: ${url}`));\n };\n\n document.head.appendChild(script);\n this.loadedResources.set(url, { element: script, promise: Promise.resolve() });\n });\n }\n\n /**\n * Wait for global object to be available and valid\n * @param globalName - Global variable name\n * @param validator - Validation function\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n * @param attempts - Current attempt number\n * @param maxAttempts - Maximum attempts before failing\n */\n private waitForValidation(\n globalName: string,\n validator: (obj: any) => boolean,\n resolve: (value: any) => void,\n reject: (reason: any) => void,\n attempts = 0,\n maxAttempts = 50 // 5 seconds total with 100ms intervals\n ): void {\n const global = (window as any)[globalName];\n \n if (global && validator(global)) {\n resolve(global);\n return;\n }\n\n if (attempts >= maxAttempts) {\n if (global) {\n reject(new Error(`${globalName} loaded but validation failed after ${maxAttempts} attempts`));\n } else {\n reject(new Error(`${globalName} not found after ${maxAttempts} attempts`));\n }\n return;\n }\n\n // Retry with exponential backoff for first few attempts, then fixed interval\n const delay = attempts < 5 ? Math.min(100 * Math.pow(1.5, attempts), 500) : 100;\n setTimeout(() => {\n this.waitForValidation(globalName, validator, resolve, reject, attempts + 1, maxAttempts);\n }, delay);\n }\n\n /**\n * Wait for existing script to load\n * @param script - Script element\n * @param globalName - Expected global variable\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n */\n private waitForScriptLoad(\n script: HTMLScriptElement,\n globalName: string,\n resolve: (value: any) => void,\n reject: (reason: any) => void\n ): void {\n const checkGlobal = () => {\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n return;\n }\n // Give it a moment for the global to be defined\n setTimeout(() => {\n if ((window as any)[globalName]) {\n resolve((window as any)[globalName]);\n } else {\n reject(new Error(`${globalName} not found after script load`));\n }\n }, 100);\n };\n\n if ('readyState' in script) {\n // IE support\n (script as any).onreadystatechange = () => {\n if ((script as any).readyState === 'loaded' || (script as any).readyState === 'complete') {\n (script as any).onreadystatechange = null;\n checkGlobal();\n }\n };\n } else {\n // Modern browsers\n const loadHandler = () => {\n script.removeEventListener('load', loadHandler);\n checkGlobal();\n };\n script.addEventListener('load', loadHandler);\n }\n }\n\n /**\n * Wait for existing script to load with validation\n * @param script - Script element\n * @param globalName - Expected global variable\n * @param validator - Validation function\n * @param resolve - Promise resolve function\n * @param reject - Promise reject function\n */\n private waitForScriptLoadWithValidation(\n script: HTMLScriptElement,\n globalName: string,\n validator: (obj: any) => boolean,\n resolve: (value: any) => void,\n reject: (reason: any) => void\n ): void {\n const checkGlobal = () => {\n this.waitForValidation(globalName, validator, resolve, reject);\n };\n\n if ('readyState' in script) {\n // IE support\n (script as any).onreadystatechange = () => {\n if ((script as any).readyState === 'loaded' || (script as any).readyState === 'complete') {\n (script as any).onreadystatechange = null;\n checkGlobal();\n }\n };\n } else {\n // Modern browsers\n const loadHandler = () => {\n script.removeEventListener('load', loadHandler);\n checkGlobal();\n };\n script.addEventListener('load', loadHandler);\n }\n }\n}"]}
|
|
@@ -9,11 +9,12 @@ import { ComponentUtilities } from '@memberjunction/interactive-component-types'
|
|
|
9
9
|
* to provide custom implementations of data access methods.
|
|
10
10
|
*/
|
|
11
11
|
export declare class RuntimeUtilities {
|
|
12
|
+
private debug;
|
|
12
13
|
/**
|
|
13
14
|
* Builds the complete utilities object for React components
|
|
14
15
|
* This is the main method that components will use
|
|
15
16
|
*/
|
|
16
|
-
buildUtilities(): ComponentUtilities;
|
|
17
|
+
buildUtilities(debug?: boolean): ComponentUtilities;
|
|
17
18
|
/**
|
|
18
19
|
* Sets up the utilities object - copied from skip-chat implementation
|
|
19
20
|
*/
|
|
@@ -13,11 +13,15 @@ import { SimpleVectorService } from '@memberjunction/ai-vectors-memory';
|
|
|
13
13
|
* to provide custom implementations of data access methods.
|
|
14
14
|
*/
|
|
15
15
|
let RuntimeUtilities = class RuntimeUtilities {
|
|
16
|
+
constructor() {
|
|
17
|
+
this.debug = false;
|
|
18
|
+
}
|
|
16
19
|
/**
|
|
17
20
|
* Builds the complete utilities object for React components
|
|
18
21
|
* This is the main method that components will use
|
|
19
22
|
*/
|
|
20
|
-
buildUtilities() {
|
|
23
|
+
buildUtilities(debug = false) {
|
|
24
|
+
this.debug = debug;
|
|
21
25
|
const md = new Metadata();
|
|
22
26
|
return this.SetupUtilities(md);
|
|
23
27
|
}
|
|
@@ -53,6 +57,11 @@ let RuntimeUtilities = class RuntimeUtilities {
|
|
|
53
57
|
preferredModels: params.preferredModels,
|
|
54
58
|
modelPower: params.modelPower
|
|
55
59
|
});
|
|
60
|
+
console.log(`🤖 ExecutePrompt succeeded!`);
|
|
61
|
+
if (this.debug) {
|
|
62
|
+
console.log(' > params', params);
|
|
63
|
+
console.log(' > result:', result);
|
|
64
|
+
}
|
|
56
65
|
return {
|
|
57
66
|
success: result.success,
|
|
58
67
|
result: result.result || '',
|
|
@@ -79,6 +88,12 @@ let RuntimeUtilities = class RuntimeUtilities {
|
|
|
79
88
|
if (result.error) {
|
|
80
89
|
throw new Error(result.error || 'Failed to generate embeddings');
|
|
81
90
|
}
|
|
91
|
+
const numEmbeddings = Array.isArray(params.textToEmbed) ? result.embeddings?.length : 1;
|
|
92
|
+
console.log(`🤖 EmbedText succeeded! ${numEmbeddings} embeddings returned`);
|
|
93
|
+
if (this.debug) {
|
|
94
|
+
console.log(' > params', params);
|
|
95
|
+
console.log(' > result:', result);
|
|
96
|
+
}
|
|
82
97
|
return {
|
|
83
98
|
result: result.embeddings,
|
|
84
99
|
modelName: result.modelName,
|
|
@@ -107,9 +122,20 @@ let RuntimeUtilities = class RuntimeUtilities {
|
|
|
107
122
|
// Run a single query and return the results
|
|
108
123
|
try {
|
|
109
124
|
const result = await rq.RunQuery(params);
|
|
125
|
+
if (result.Success) {
|
|
126
|
+
console.log(`✅ RunQuery "${params.QueryName}" succeeded: ${result.RowCount} rows returned`);
|
|
127
|
+
if (this.debug) {
|
|
128
|
+
console.log(' > params', params);
|
|
129
|
+
console.log(' > result:', result);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
console.error(`❌ RunQuery failed: ${result.ErrorMessage}`);
|
|
134
|
+
}
|
|
110
135
|
return result;
|
|
111
136
|
}
|
|
112
137
|
catch (error) {
|
|
138
|
+
console.error(`❌ RunQuery threw exception:`, error);
|
|
113
139
|
LogError(error);
|
|
114
140
|
throw error; // Re-throw to handle it in the caller
|
|
115
141
|
}
|
|
@@ -122,9 +148,20 @@ let RuntimeUtilities = class RuntimeUtilities {
|
|
|
122
148
|
// Run a single view and return the results
|
|
123
149
|
try {
|
|
124
150
|
const result = await rv.RunView(params);
|
|
151
|
+
if (result.Success) {
|
|
152
|
+
console.log(`✅ RunView succeeded for ${params.EntityName}: ${result.TotalRowCount} rows returned`);
|
|
153
|
+
if (this.debug) {
|
|
154
|
+
console.log(' > params', params);
|
|
155
|
+
console.log(' > result:', result);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
console.error(`❌ RunView failed for ${params.EntityName}: ${result.ErrorMessage}`);
|
|
160
|
+
}
|
|
125
161
|
return result;
|
|
126
162
|
}
|
|
127
163
|
catch (error) {
|
|
164
|
+
console.error(`❌ RunView threw exception:`, error);
|
|
128
165
|
LogError(error);
|
|
129
166
|
throw error; // Re-throw to handle it in the caller
|
|
130
167
|
}
|
|
@@ -133,9 +170,17 @@ let RuntimeUtilities = class RuntimeUtilities {
|
|
|
133
170
|
// Runs multiple views and returns the results
|
|
134
171
|
try {
|
|
135
172
|
const results = await rv.RunViews(params);
|
|
173
|
+
const entityNames = params.map(p => p.EntityName).join(', ');
|
|
174
|
+
const totalRows = results.reduce((sum, r) => sum + (r.TotalRowCount || 0), 0);
|
|
175
|
+
console.log(`✅ RunViews succeeded for [${entityNames}]: ${totalRows} total rows returned`);
|
|
176
|
+
if (this.debug) {
|
|
177
|
+
console.log(' > params', params);
|
|
178
|
+
console.log(' > results:', results);
|
|
179
|
+
}
|
|
136
180
|
return results;
|
|
137
181
|
}
|
|
138
182
|
catch (error) {
|
|
183
|
+
console.error(`❌ RunViews threw exception:`, error);
|
|
139
184
|
LogError(error);
|
|
140
185
|
throw error; // Re-throw to handle it in the caller
|
|
141
186
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-utilities.js","sourceRoot":"","sources":["../../../src/lib/utilities/runtime-utilities.ts"],"names":[],"mappings":"AAAA;;;GAGG;;AAEH,OAAO,EACL,QAAQ,EACR,OAAO,EACP,QAAQ,EAGR,QAAQ,EACR,UAAU,EAEX,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAYjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,sCAAsC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAExE;;;;GAIG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAC3B;;;OAGG;IACI,cAAc;QACnB,MAAM,EAAE,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC1B,OAAO,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC;IACjC,CAAC;IAED;;OAEG;IACK,cAAc,CAAC,EAAY;QACjC,MAAM,EAAE,GAAG,IAAI,OAAO,EAAE,CAAC;QACzB,MAAM,EAAE,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC1B,MAAM,CAAC,GAAuB;YAC5B,EAAE,EAAE,IAAI,CAAC,oBAAoB,CAAC,EA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B,CAAC,CAAC;YAC9F,IAAI,CAAC,GAAG,EAAE,CAAC;gBACT,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;YAChE,CAAC;YAED,uDAAuD;YACvD,OAAO,GAAG,CAAC;QACb,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,0BAA0B;QAC5B,CAAC;IACH,CAAC;IAED,mCAAmC;IACnC,OAAO,IAAI,gBAAgB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["/**\n * @fileoverview Runtime utilities for React components providing access to MemberJunction core functionality\n * @module @memberjunction/ng-react/utilities\n */\n\nimport { \n Metadata, \n RunView, \n RunQuery, \n RunViewParams, \n RunQueryParams,\n LogError,\n BaseEntity,\n IEntityDataProvider\n} from '@memberjunction/core';\n\nimport { MJGlobal, RegisterClass } from '@memberjunction/global';\nimport { \n ComponentUtilities, \n SimpleAITools, \n SimpleMetadata, \n SimpleRunQuery, \n SimpleRunView,\n SimpleExecutePromptParams,\n SimpleExecutePromptResult,\n SimpleEmbedTextParams,\n SimpleEmbedTextResult\n} from '@memberjunction/interactive-component-types';\nimport { GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { SimpleVectorService } from '@memberjunction/ai-vectors-memory';\n\n/**\n * Base class for providing runtime utilities to React components in Angular.\n * This class can be extended and registered with MJ's ClassFactory\n * to provide custom implementations of data access methods.\n */\n@RegisterClass(RuntimeUtilities, 'RuntimeUtilities')\nexport class RuntimeUtilities {\n /**\n * Builds the complete utilities object for React components\n * This is the main method that components will use\n */\n public buildUtilities(): ComponentUtilities {\n const md = new Metadata();\n return this.SetupUtilities(md);\n }\n\n /**\n * Sets up the utilities object - copied from skip-chat implementation\n */\n private SetupUtilities(md: Metadata): ComponentUtilities {\n const rv = new RunView();\n const rq = new RunQuery();\n const u: ComponentUtilities = {\n md: this.CreateSimpleMetadata(md),\n rv: this.CreateSimpleRunView(rv),\n rq: this.CreateSimpleRunQuery(rq),\n ai: this.CreateSimpleAITools()\n }; \n return u;\n }\n\n private CreateSimpleAITools(): SimpleAITools {\n // Get the GraphQL provider - it's the same as the BaseEntity provider\n const provider = BaseEntity.Provider;\n \n // Check if it's a GraphQLDataProvider\n if (!(provider instanceof GraphQLDataProvider)) {\n throw new Error('Current data provider is not a GraphQLDataProvider. AI tools require GraphQL provider.');\n }\n\n const graphQLProvider = provider as GraphQLDataProvider;\n \n return {\n ExecutePrompt: async (params: SimpleExecutePromptParams): Promise<SimpleExecutePromptResult> => {\n try {\n // Use the AI client from GraphQLDataProvider to execute simple prompt\n const result = await graphQLProvider.AI.ExecuteSimplePrompt({\n systemPrompt: params.systemPrompt,\n messages: params.messages,\n preferredModels: params.preferredModels,\n modelPower: params.modelPower\n });\n \n return {\n success: result.success,\n result: result.result || '',\n resultObject: result.resultObject,\n modelName: result.modelName || ''\n };\n } catch (error) {\n LogError(error);\n return {\n success: false,\n result: 'Failed to execute prompt: ' + (error instanceof Error ? error.message : String(error)),\n modelName: ''\n };\n }\n },\n \n EmbedText: async (params: SimpleEmbedTextParams): Promise<SimpleEmbedTextResult> => {\n try {\n // Use the AI client from GraphQLDataProvider to generate embeddings\n const result = await graphQLProvider.AI.EmbedText({\n textToEmbed: params.textToEmbed,\n modelSize: params.modelSize\n });\n \n if (result.error) {\n throw new Error(result.error || 'Failed to generate embeddings');\n }\n \n return {\n result: result.embeddings,\n modelName: result.modelName,\n vectorDimensions: result.vectorDimensions\n };\n } catch (error) {\n LogError(error);\n throw error; // Re-throw for embeddings as they're critical\n }\n },\n \n VectorService: new SimpleVectorService()\n };\n }\n\n private CreateSimpleMetadata(md: Metadata): SimpleMetadata {\n return {\n Entities: md.Entities,\n GetEntityObject: (entityName: string) => {\n return md.GetEntityObject(entityName)\n }\n }\n }\n\n private CreateSimpleRunQuery(rq: RunQuery): SimpleRunQuery {\n return {\n RunQuery: async (params: RunQueryParams) => {\n // Run a single query and return the results\n try {\n const result = await rq.RunQuery(params);\n return result;\n } catch (error) {\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n }\n }\n }\n\n private CreateSimpleRunView(rv: RunView): SimpleRunView {\n return {\n RunView: async (params: RunViewParams) => {\n // Run a single view and return the results\n try {\n const result = await rv.RunView(params);\n return result;\n } catch (error) {\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n },\n RunViews: async (params: RunViewParams[]) => {\n // Runs multiple views and returns the results\n try {\n const results = await rv.RunViews(params);\n return results;\n } catch (error) {\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n }\n }\n }\n}\n\n/**\n * Factory function to create RuntimeUtilities\n * In a Node.js environment, this will use MJ's ClassFactory for runtime substitution\n * In a browser environment, it will use the base class directly\n */\nexport function createRuntimeUtilities(): RuntimeUtilities {\n // Check if we're in a Node.js environment with MJGlobal available\n if (typeof window === 'undefined') {\n try {\n // Use ClassFactory to get the registered class, defaulting to base RuntimeUtilities\n const obj = MJGlobal.Instance.ClassFactory.CreateInstance<RuntimeUtilities>(RuntimeUtilities);\n if (!obj) {\n throw new Error('Failed to create RuntimeUtilities instance');\n }\n\n // Ensure the object is an instance of RuntimeUtilities\n return obj;\n } catch (e) {\n // Fall through to default\n }\n }\n \n // Default: just use the base class\n return new RuntimeUtilities();\n}"]}
|
|
1
|
+
{"version":3,"file":"runtime-utilities.js","sourceRoot":"","sources":["../../../src/lib/utilities/runtime-utilities.ts"],"names":[],"mappings":"AAAA;;;GAGG;;AAEH,OAAO,EACL,QAAQ,EACR,OAAO,EACP,QAAQ,EAGR,QAAQ,EACR,UAAU,EAEX,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAYjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,sCAAsC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAExE;;;;GAIG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAAtB;QACG,UAAK,GAAY,KAAK,CAAC;IAoL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B,CAAC;GACvC,gBAAgB,CAqL5B;;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB;IACpC,kEAAkE;IAClE,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,IAAI,CAAC;YACH,oFAAoF;YACpF,MAAM,GAAG,GAAG,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,cAAc,CAAmB,gBAAgB,CAAC,CAAC;YAC9F,IAAI,CAAC,GAAG,EAAE,CAAC;gBACT,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;YAChE,CAAC;YAED,uDAAuD;YACvD,OAAO,GAAG,CAAC;QACb,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,0BAA0B;QAC5B,CAAC;IACH,CAAC;IAED,mCAAmC;IACnC,OAAO,IAAI,gBAAgB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["/**\n * @fileoverview Runtime utilities for React components providing access to MemberJunction core functionality\n * @module @memberjunction/ng-react/utilities\n */\n\nimport { \n Metadata, \n RunView, \n RunQuery, \n RunViewParams, \n RunQueryParams,\n LogError,\n BaseEntity,\n IEntityDataProvider\n} from '@memberjunction/core';\n\nimport { MJGlobal, RegisterClass } from '@memberjunction/global';\nimport { \n ComponentUtilities, \n SimpleAITools, \n SimpleMetadata, \n SimpleRunQuery, \n SimpleRunView,\n SimpleExecutePromptParams,\n SimpleExecutePromptResult,\n SimpleEmbedTextParams,\n SimpleEmbedTextResult\n} from '@memberjunction/interactive-component-types';\nimport { GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { SimpleVectorService } from '@memberjunction/ai-vectors-memory';\n\n/**\n * Base class for providing runtime utilities to React components in Angular.\n * This class can be extended and registered with MJ's ClassFactory\n * to provide custom implementations of data access methods.\n */\n@RegisterClass(RuntimeUtilities, 'RuntimeUtilities')\nexport class RuntimeUtilities {\n private debug: boolean = false;\n \n /**\n * Builds the complete utilities object for React components\n * This is the main method that components will use\n */\n public buildUtilities(debug: boolean = false): ComponentUtilities {\n this.debug = debug;\n const md = new Metadata();\n return this.SetupUtilities(md);\n }\n\n /**\n * Sets up the utilities object - copied from skip-chat implementation\n */\n private SetupUtilities(md: Metadata): ComponentUtilities {\n const rv = new RunView();\n const rq = new RunQuery();\n const u: ComponentUtilities = {\n md: this.CreateSimpleMetadata(md),\n rv: this.CreateSimpleRunView(rv),\n rq: this.CreateSimpleRunQuery(rq),\n ai: this.CreateSimpleAITools()\n }; \n return u;\n }\n\n private CreateSimpleAITools(): SimpleAITools {\n // Get the GraphQL provider - it's the same as the BaseEntity provider\n const provider = BaseEntity.Provider;\n \n // Check if it's a GraphQLDataProvider\n if (!(provider instanceof GraphQLDataProvider)) {\n throw new Error('Current data provider is not a GraphQLDataProvider. AI tools require GraphQL provider.');\n }\n\n const graphQLProvider = provider as GraphQLDataProvider;\n \n return {\n ExecutePrompt: async (params: SimpleExecutePromptParams): Promise<SimpleExecutePromptResult> => {\n try {\n // Use the AI client from GraphQLDataProvider to execute simple prompt\n const result = await graphQLProvider.AI.ExecuteSimplePrompt({\n systemPrompt: params.systemPrompt,\n messages: params.messages,\n preferredModels: params.preferredModels,\n modelPower: params.modelPower\n });\n\n console.log(`🤖 ExecutePrompt succeeded!`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n\n return {\n success: result.success,\n result: result.result || '',\n resultObject: result.resultObject,\n modelName: result.modelName || ''\n };\n } catch (error) {\n LogError(error);\n return {\n success: false,\n result: 'Failed to execute prompt: ' + (error instanceof Error ? error.message : String(error)),\n modelName: ''\n };\n }\n },\n \n EmbedText: async (params: SimpleEmbedTextParams): Promise<SimpleEmbedTextResult> => {\n try {\n // Use the AI client from GraphQLDataProvider to generate embeddings\n const result = await graphQLProvider.AI.EmbedText({\n textToEmbed: params.textToEmbed,\n modelSize: params.modelSize\n });\n \n if (result.error) {\n throw new Error(result.error || 'Failed to generate embeddings');\n }\n\n const numEmbeddings: number = Array.isArray(params.textToEmbed) ? result.embeddings?.length : 1;\n console.log(`🤖 EmbedText succeeded! ${numEmbeddings} embeddings returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n return {\n result: result.embeddings,\n modelName: result.modelName,\n vectorDimensions: result.vectorDimensions\n };\n } catch (error) {\n LogError(error);\n throw error; // Re-throw for embeddings as they're critical\n }\n },\n \n VectorService: new SimpleVectorService()\n };\n }\n\n private CreateSimpleMetadata(md: Metadata): SimpleMetadata {\n return {\n Entities: md.Entities,\n GetEntityObject: (entityName: string) => {\n return md.GetEntityObject(entityName)\n }\n }\n }\n\n private CreateSimpleRunQuery(rq: RunQuery): SimpleRunQuery {\n return {\n RunQuery: async (params: RunQueryParams) => {\n // Run a single query and return the results\n try {\n const result = await rq.RunQuery(params);\n if (result.Success) {\n console.log(`✅ RunQuery \"${params.QueryName}\" succeeded: ${result.RowCount} rows returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n } else {\n console.error(`❌ RunQuery failed: ${result.ErrorMessage}`);\n }\n return result;\n } catch (error) {\n console.error(`❌ RunQuery threw exception:`, error);\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n }\n }\n }\n\n private CreateSimpleRunView(rv: RunView): SimpleRunView {\n return {\n RunView: async (params: RunViewParams) => {\n // Run a single view and return the results\n try {\n const result = await rv.RunView(params);\n if (result.Success) {\n console.log(`✅ RunView succeeded for ${params.EntityName}: ${result.TotalRowCount} rows returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > result:', result);\n }\n } else {\n console.error(`❌ RunView failed for ${params.EntityName}: ${result.ErrorMessage}`);\n }\n return result;\n } catch (error) {\n console.error(`❌ RunView threw exception:`, error);\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n },\n RunViews: async (params: RunViewParams[]) => {\n // Runs multiple views and returns the results\n try {\n const results = await rv.RunViews(params);\n const entityNames = params.map(p => p.EntityName).join(', ');\n const totalRows = results.reduce((sum, r) => sum + (r.TotalRowCount || 0), 0);\n console.log(`✅ RunViews succeeded for [${entityNames}]: ${totalRows} total rows returned`);\n if (this.debug) {\n console.log(' > params', params);\n console.log(' > results:', results);\n }\n return results;\n } catch (error) {\n console.error(`❌ RunViews threw exception:`, error);\n LogError(error);\n throw error; // Re-throw to handle it in the caller\n }\n }\n }\n }\n}\n\n/**\n * Factory function to create RuntimeUtilities\n * In a Node.js environment, this will use MJ's ClassFactory for runtime substitution\n * In a browser environment, it will use the base class directly\n */\nexport function createRuntimeUtilities(): RuntimeUtilities {\n // Check if we're in a Node.js environment with MJGlobal available\n if (typeof window === 'undefined') {\n try {\n // Use ClassFactory to get the registered class, defaulting to base RuntimeUtilities\n const obj = MJGlobal.Instance.ClassFactory.CreateInstance<RuntimeUtilities>(RuntimeUtilities);\n if (!obj) {\n throw new Error('Failed to create RuntimeUtilities instance');\n }\n\n // Ensure the object is an instance of RuntimeUtilities\n return obj;\n } catch (e) {\n // Fall through to default\n }\n }\n \n // Default: just use the base class\n return new RuntimeUtilities();\n}"]}
|
package/dist/public-api.d.ts
CHANGED
package/dist/public-api.js
CHANGED
|
@@ -11,6 +11,4 @@ export * from './lib/components/mj-react-component.component';
|
|
|
11
11
|
export * from './lib/services/script-loader.service';
|
|
12
12
|
export * from './lib/services/react-bridge.service';
|
|
13
13
|
export * from './lib/services/angular-adapter.service';
|
|
14
|
-
// Constants
|
|
15
|
-
export * from './lib/default-styles';
|
|
16
14
|
//# sourceMappingURL=public-api.js.map
|
package/dist/public-api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public-api.js","sourceRoot":"","sources":["../src/public-api.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,SAAS;AACT,cAAc,cAAc,CAAC;AAE7B,aAAa;AACb,cAAc,+CAA+C,CAAC;AAE9D,WAAW;AACX,cAAc,sCAAsC,CAAC;AACrD,cAAc,qCAAqC,CAAC;AACpD,cAAc,wCAAwC,CAAC
|
|
1
|
+
{"version":3,"file":"public-api.js","sourceRoot":"","sources":["../src/public-api.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,SAAS;AACT,cAAc,cAAc,CAAC;AAE7B,aAAa;AACb,cAAc,+CAA+C,CAAC;AAE9D,WAAW;AACX,cAAc,sCAAsC,CAAC;AACrD,cAAc,qCAAqC,CAAC;AACpD,cAAc,wCAAwC,CAAC","sourcesContent":["/**\n * @fileoverview Public API Surface of @memberjunction/ng-react\n * This file exports all public APIs from the Angular React integration library.\n * @module @memberjunction/ng-react\n */\n\n// Module\nexport * from './lib/module';\n\n// Components\nexport * from './lib/components/mj-react-component.component';\n\n// Services\nexport * from './lib/services/script-loader.service';\nexport * from './lib/services/react-bridge.service';\nexport * from './lib/services/angular-adapter.service';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@memberjunction/ng-react",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.96.0",
|
|
4
4
|
"description": "Angular components for hosting React components in MemberJunction applications",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"build": "ngc -p tsconfig.json",
|
|
@@ -40,9 +40,9 @@
|
|
|
40
40
|
"styles"
|
|
41
41
|
],
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@memberjunction/core": "2.
|
|
44
|
-
"@memberjunction/react-runtime": "2.
|
|
45
|
-
"@memberjunction/interactive-component-types": "^2.
|
|
43
|
+
"@memberjunction/core": "2.96.0",
|
|
44
|
+
"@memberjunction/react-runtime": "2.96.0",
|
|
45
|
+
"@memberjunction/interactive-component-types": "^2.96.0",
|
|
46
46
|
"@angular/common": ">=18.0.0",
|
|
47
47
|
"@angular/core": ">=18.0.0",
|
|
48
48
|
"@angular/platform-browser": ">=18.0.0",
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @fileoverview Default styles for React components in MemberJunction.
|
|
3
|
-
* These styles provide a consistent design system for React components.
|
|
4
|
-
* @module @memberjunction/ng-react
|
|
5
|
-
*/
|
|
6
|
-
import { ComponentStyles } from '@memberjunction/interactive-component-types';
|
|
7
|
-
/**
|
|
8
|
-
* Default styles that match the Skip design system
|
|
9
|
-
*/
|
|
10
|
-
export declare const DEFAULT_STYLES: ComponentStyles;
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @fileoverview Default styles for React components in MemberJunction.
|
|
3
|
-
* These styles provide a consistent design system for React components.
|
|
4
|
-
* @module @memberjunction/ng-react
|
|
5
|
-
*/
|
|
6
|
-
/**
|
|
7
|
-
* Default styles that match the Skip design system
|
|
8
|
-
*/
|
|
9
|
-
export const DEFAULT_STYLES = {
|
|
10
|
-
colors: {
|
|
11
|
-
// Primary colors - modern purple/blue gradient feel
|
|
12
|
-
primary: '#5B4FE9',
|
|
13
|
-
primaryHover: '#4940D4',
|
|
14
|
-
primaryLight: '#E8E6FF',
|
|
15
|
-
// Secondary colors - sophisticated gray
|
|
16
|
-
secondary: '#64748B',
|
|
17
|
-
secondaryHover: '#475569',
|
|
18
|
-
// Status colors
|
|
19
|
-
success: '#10B981',
|
|
20
|
-
successLight: '#D1FAE5',
|
|
21
|
-
warning: '#F59E0B',
|
|
22
|
-
warningLight: '#FEF3C7',
|
|
23
|
-
error: '#EF4444',
|
|
24
|
-
errorLight: '#FEE2E2',
|
|
25
|
-
info: '#3B82F6',
|
|
26
|
-
infoLight: '#DBEAFE',
|
|
27
|
-
// Base colors
|
|
28
|
-
background: '#FFFFFF',
|
|
29
|
-
surface: '#F8FAFC',
|
|
30
|
-
surfaceHover: '#F1F5F9',
|
|
31
|
-
// Text colors with better contrast
|
|
32
|
-
text: '#1E293B',
|
|
33
|
-
textSecondary: '#64748B',
|
|
34
|
-
textTertiary: '#94A3B8',
|
|
35
|
-
textInverse: '#FFFFFF',
|
|
36
|
-
// Border colors
|
|
37
|
-
border: '#E2E8F0',
|
|
38
|
-
borderLight: '#F1F5F9',
|
|
39
|
-
borderFocus: '#5B4FE9',
|
|
40
|
-
// Shadows (as color strings for easy use)
|
|
41
|
-
shadow: 'rgba(0, 0, 0, 0.05)',
|
|
42
|
-
shadowMedium: 'rgba(0, 0, 0, 0.1)',
|
|
43
|
-
shadowLarge: 'rgba(0, 0, 0, 0.15)',
|
|
44
|
-
},
|
|
45
|
-
spacing: {
|
|
46
|
-
xs: '4px',
|
|
47
|
-
sm: '8px',
|
|
48
|
-
md: '16px',
|
|
49
|
-
lg: '24px',
|
|
50
|
-
xl: '32px',
|
|
51
|
-
xxl: '48px',
|
|
52
|
-
xxxl: '64px',
|
|
53
|
-
},
|
|
54
|
-
typography: {
|
|
55
|
-
fontFamily: '-apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, sans-serif',
|
|
56
|
-
fontSize: {
|
|
57
|
-
xs: '11px',
|
|
58
|
-
sm: '12px',
|
|
59
|
-
md: '14px',
|
|
60
|
-
lg: '16px',
|
|
61
|
-
xl: '20px',
|
|
62
|
-
xxl: '24px',
|
|
63
|
-
xxxl: '32px',
|
|
64
|
-
},
|
|
65
|
-
fontWeight: {
|
|
66
|
-
light: '300',
|
|
67
|
-
regular: '400',
|
|
68
|
-
medium: '500',
|
|
69
|
-
semibold: '600',
|
|
70
|
-
bold: '700',
|
|
71
|
-
},
|
|
72
|
-
lineHeight: {
|
|
73
|
-
tight: '1.25',
|
|
74
|
-
normal: '1.5',
|
|
75
|
-
relaxed: '1.75',
|
|
76
|
-
},
|
|
77
|
-
},
|
|
78
|
-
borders: {
|
|
79
|
-
radius: {
|
|
80
|
-
sm: '6px',
|
|
81
|
-
md: '8px',
|
|
82
|
-
lg: '12px',
|
|
83
|
-
xl: '16px',
|
|
84
|
-
full: '9999px',
|
|
85
|
-
},
|
|
86
|
-
width: {
|
|
87
|
-
thin: '1px',
|
|
88
|
-
medium: '2px',
|
|
89
|
-
thick: '3px',
|
|
90
|
-
},
|
|
91
|
-
},
|
|
92
|
-
shadows: {
|
|
93
|
-
sm: '0 1px 2px 0 rgba(0, 0, 0, 0.05)',
|
|
94
|
-
md: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
|
|
95
|
-
lg: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
|
|
96
|
-
xl: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
|
|
97
|
-
inner: 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)',
|
|
98
|
-
},
|
|
99
|
-
transitions: {
|
|
100
|
-
fast: '150ms ease-in-out',
|
|
101
|
-
normal: '250ms ease-in-out',
|
|
102
|
-
slow: '350ms ease-in-out',
|
|
103
|
-
},
|
|
104
|
-
overflow: 'auto'
|
|
105
|
-
};
|
|
106
|
-
//# sourceMappingURL=default-styles.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"default-styles.js","sourceRoot":"","sources":["../../src/lib/default-styles.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH;;GAEG;AACH,MAAM,CAAC,MAAM,cAAc,GAAoB;IAC7C,MAAM,EAAE;QACN,oDAAoD;QACpD,OAAO,EAAE,SAAS;QAClB,YAAY,EAAE,SAAS;QACvB,YAAY,EAAE,SAAS;QAEvB,wCAAwC;QACxC,SAAS,EAAE,SAAS;QACpB,cAAc,EAAE,SAAS;QAEzB,gBAAgB;QAChB,OAAO,EAAE,SAAS;QAClB,YAAY,EAAE,SAAS;QACvB,OAAO,EAAE,SAAS;QAClB,YAAY,EAAE,SAAS;QACvB,KAAK,EAAE,SAAS;QAChB,UAAU,EAAE,SAAS;QACrB,IAAI,EAAE,SAAS;QACf,SAAS,EAAE,SAAS;QAEpB,cAAc;QACd,UAAU,EAAE,SAAS;QACrB,OAAO,EAAE,SAAS;QAClB,YAAY,EAAE,SAAS;QAEvB,mCAAmC;QACnC,IAAI,EAAE,SAAS;QACf,aAAa,EAAE,SAAS;QACxB,YA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,EAAE,2EAA2E;QAC/E,KAAK,EAAE,uCAAuC;KAC/C;IACD,WAAW,EAAE;QACX,IAAI,EAAE,mBAAmB;QACzB,MAAM,EAAE,mBAAmB;QAC3B,IAAI,EAAE,mBAAmB;KAC1B;IACD,QAAQ,EAAE,MAAM;CACjB,CAAC","sourcesContent":["/**\n * @fileoverview Default styles for React components in MemberJunction.\n * These styles provide a consistent design system for React components.\n * @module @memberjunction/ng-react\n */\n\nimport { ComponentStyles } from '@memberjunction/interactive-component-types';\n\n/**\n * Default styles that match the Skip design system\n */\nexport const DEFAULT_STYLES: ComponentStyles = {\n colors: {\n // Primary colors - modern purple/blue gradient feel\n primary: '#5B4FE9',\n primaryHover: '#4940D4',\n primaryLight: '#E8E6FF',\n \n // Secondary colors - sophisticated gray\n secondary: '#64748B',\n secondaryHover: '#475569',\n \n // Status colors\n success: '#10B981',\n successLight: '#D1FAE5',\n warning: '#F59E0B',\n warningLight: '#FEF3C7',\n error: '#EF4444',\n errorLight: '#FEE2E2',\n info: '#3B82F6',\n infoLight: '#DBEAFE',\n \n // Base colors\n background: '#FFFFFF',\n surface: '#F8FAFC',\n surfaceHover: '#F1F5F9',\n \n // Text colors with better contrast\n text: '#1E293B',\n textSecondary: '#64748B',\n textTertiary: '#94A3B8',\n textInverse: '#FFFFFF',\n \n // Border colors\n border: '#E2E8F0',\n borderLight: '#F1F5F9',\n borderFocus: '#5B4FE9',\n \n // Shadows (as color strings for easy use)\n shadow: 'rgba(0, 0, 0, 0.05)',\n shadowMedium: 'rgba(0, 0, 0, 0.1)',\n shadowLarge: 'rgba(0, 0, 0, 0.15)',\n },\n spacing: {\n xs: '4px',\n sm: '8px',\n md: '16px',\n lg: '24px',\n xl: '32px',\n xxl: '48px',\n xxxl: '64px',\n },\n typography: {\n fontFamily: '-apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", Roboto, sans-serif',\n fontSize: {\n xs: '11px',\n sm: '12px',\n md: '14px',\n lg: '16px',\n xl: '20px',\n xxl: '24px',\n xxxl: '32px',\n },\n fontWeight: {\n light: '300',\n regular: '400',\n medium: '500',\n semibold: '600',\n bold: '700',\n },\n lineHeight: {\n tight: '1.25',\n normal: '1.5',\n relaxed: '1.75',\n },\n },\n borders: {\n radius: {\n sm: '6px',\n md: '8px',\n lg: '12px',\n xl: '16px',\n full: '9999px',\n },\n width: {\n thin: '1px',\n medium: '2px',\n thick: '3px',\n },\n },\n shadows: {\n sm: '0 1px 2px 0 rgba(0, 0, 0, 0.05)',\n md: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',\n lg: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',\n xl: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',\n inner: 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)',\n },\n transitions: {\n fast: '150ms ease-in-out',\n normal: '250ms ease-in-out',\n slow: '350ms ease-in-out',\n },\n overflow: 'auto'\n};"]}
|