@memberjunction/integration-connectors 5.50.0 → 6.1.0-edge.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/LICENSE +7 -0
- package/README.md +109 -277
- package/dist/index.d.ts +0 -36
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -38
- package/dist/index.js.map +1 -1
- package/package.json +14 -19
- package/dist/AptifyConnector.d.ts +0 -95
- package/dist/AptifyConnector.d.ts.map +0 -1
- package/dist/AptifyConnector.js +0 -760
- package/dist/AptifyConnector.js.map +0 -1
- package/dist/BlackbaudConnector.d.ts +0 -64
- package/dist/BlackbaudConnector.d.ts.map +0 -1
- package/dist/BlackbaudConnector.js +0 -916
- package/dist/BlackbaudConnector.js.map +0 -1
- package/dist/ConstantContactConnector.d.ts +0 -137
- package/dist/ConstantContactConnector.d.ts.map +0 -1
- package/dist/ConstantContactConnector.js +0 -663
- package/dist/ConstantContactConnector.js.map +0 -1
- package/dist/CventConnector.d.ts +0 -146
- package/dist/CventConnector.d.ts.map +0 -1
- package/dist/CventConnector.js +0 -540
- package/dist/CventConnector.js.map +0 -1
- package/dist/DynamicsDataverseConnector.d.ts +0 -296
- package/dist/DynamicsDataverseConnector.d.ts.map +0 -1
- package/dist/DynamicsDataverseConnector.js +0 -790
- package/dist/DynamicsDataverseConnector.js.map +0 -1
- package/dist/FileFeedConnector.d.ts +0 -64
- package/dist/FileFeedConnector.d.ts.map +0 -1
- package/dist/FileFeedConnector.js +0 -190
- package/dist/FileFeedConnector.js.map +0 -1
- package/dist/FontevaConnector.d.ts +0 -153
- package/dist/FontevaConnector.d.ts.map +0 -1
- package/dist/FontevaConnector.js +0 -421
- package/dist/FontevaConnector.js.map +0 -1
- package/dist/GrowthZoneConnector.d.ts +0 -183
- package/dist/GrowthZoneConnector.d.ts.map +0 -1
- package/dist/GrowthZoneConnector.js +0 -702
- package/dist/GrowthZoneConnector.js.map +0 -1
- package/dist/HivebriteConnector.d.ts +0 -151
- package/dist/HivebriteConnector.d.ts.map +0 -1
- package/dist/HivebriteConnector.js +0 -533
- package/dist/HivebriteConnector.js.map +0 -1
- package/dist/HubSpotConnector.d.ts +0 -523
- package/dist/HubSpotConnector.d.ts.map +0 -1
- package/dist/HubSpotConnector.js +0 -3110
- package/dist/HubSpotConnector.js.map +0 -1
- package/dist/IMISConnector.d.ts +0 -171
- package/dist/IMISConnector.d.ts.map +0 -1
- package/dist/IMISConnector.js +0 -695
- package/dist/IMISConnector.js.map +0 -1
- package/dist/MJToMJConnector.d.ts +0 -279
- package/dist/MJToMJConnector.d.ts.map +0 -1
- package/dist/MJToMJConnector.js +0 -893
- package/dist/MJToMJConnector.js.map +0 -1
- package/dist/MagnetMailConnector.d.ts +0 -163
- package/dist/MagnetMailConnector.d.ts.map +0 -1
- package/dist/MagnetMailConnector.js +0 -823
- package/dist/MagnetMailConnector.js.map +0 -1
- package/dist/MailchimpConnector.d.ts +0 -197
- package/dist/MailchimpConnector.d.ts.map +0 -1
- package/dist/MailchimpConnector.js +0 -791
- package/dist/MailchimpConnector.js.map +0 -1
- package/dist/MemberSuiteConnector.d.ts +0 -185
- package/dist/MemberSuiteConnector.d.ts.map +0 -1
- package/dist/MemberSuiteConnector.js +0 -762
- package/dist/MemberSuiteConnector.js.map +0 -1
- package/dist/NeonCRMConnector.d.ts +0 -273
- package/dist/NeonCRMConnector.d.ts.map +0 -1
- package/dist/NeonCRMConnector.js +0 -1039
- package/dist/NeonCRMConnector.js.map +0 -1
- package/dist/NetForumConnector.d.ts +0 -170
- package/dist/NetForumConnector.d.ts.map +0 -1
- package/dist/NetForumConnector.js +0 -778
- package/dist/NetForumConnector.js.map +0 -1
- package/dist/NetSuiteConnector.d.ts +0 -136
- package/dist/NetSuiteConnector.d.ts.map +0 -1
- package/dist/NetSuiteConnector.js +0 -703
- package/dist/NetSuiteConnector.js.map +0 -1
- package/dist/NimbleAMSConnector.d.ts +0 -142
- package/dist/NimbleAMSConnector.d.ts.map +0 -1
- package/dist/NimbleAMSConnector.js +0 -703
- package/dist/NimbleAMSConnector.js.map +0 -1
- package/dist/NoviConnector.d.ts +0 -178
- package/dist/NoviConnector.d.ts.map +0 -1
- package/dist/NoviConnector.js +0 -566
- package/dist/NoviConnector.js.map +0 -1
- package/dist/ORCIDConnector.d.ts +0 -207
- package/dist/ORCIDConnector.d.ts.map +0 -1
- package/dist/ORCIDConnector.js +0 -708
- package/dist/ORCIDConnector.js.map +0 -1
- package/dist/OpenWaterConnector.d.ts +0 -173
- package/dist/OpenWaterConnector.d.ts.map +0 -1
- package/dist/OpenWaterConnector.js +0 -893
- package/dist/OpenWaterConnector.js.map +0 -1
- package/dist/PathLMSConnector.d.ts +0 -395
- package/dist/PathLMSConnector.d.ts.map +0 -1
- package/dist/PathLMSConnector.js +0 -1281
- package/dist/PathLMSConnector.js.map +0 -1
- package/dist/PheedLoopConnector.d.ts +0 -119
- package/dist/PheedLoopConnector.d.ts.map +0 -1
- package/dist/PheedLoopConnector.js +0 -429
- package/dist/PheedLoopConnector.js.map +0 -1
- package/dist/PropFuelConnector.d.ts +0 -153
- package/dist/PropFuelConnector.d.ts.map +0 -1
- package/dist/PropFuelConnector.js +0 -450
- package/dist/PropFuelConnector.js.map +0 -1
- package/dist/QuickBooksConnector.d.ts +0 -92
- package/dist/QuickBooksConnector.d.ts.map +0 -1
- package/dist/QuickBooksConnector.js +0 -713
- package/dist/QuickBooksConnector.js.map +0 -1
- package/dist/RasaConnector.d.ts +0 -152
- package/dist/RasaConnector.d.ts.map +0 -1
- package/dist/RasaConnector.js +0 -929
- package/dist/RasaConnector.js.map +0 -1
- package/dist/Reach360Connector.d.ts +0 -175
- package/dist/Reach360Connector.d.ts.map +0 -1
- package/dist/Reach360Connector.js +0 -796
- package/dist/Reach360Connector.js.map +0 -1
- package/dist/RelationalDBConnector.d.ts +0 -108
- package/dist/RelationalDBConnector.d.ts.map +0 -1
- package/dist/RelationalDBConnector.js +0 -228
- package/dist/RelationalDBConnector.js.map +0 -1
- package/dist/RhythmConnector.d.ts +0 -188
- package/dist/RhythmConnector.d.ts.map +0 -1
- package/dist/RhythmConnector.js +0 -784
- package/dist/RhythmConnector.js.map +0 -1
- package/dist/SageIntacctConnector.d.ts +0 -337
- package/dist/SageIntacctConnector.d.ts.map +0 -1
- package/dist/SageIntacctConnector.js +0 -2081
- package/dist/SageIntacctConnector.js.map +0 -1
- package/dist/SalesforceConnector.d.ts +0 -461
- package/dist/SalesforceConnector.d.ts.map +0 -1
- package/dist/SalesforceConnector.js +0 -1862
- package/dist/SalesforceConnector.js.map +0 -1
- package/dist/SharePointConnector.d.ts +0 -188
- package/dist/SharePointConnector.d.ts.map +0 -1
- package/dist/SharePointConnector.js +0 -716
- package/dist/SharePointConnector.js.map +0 -1
- package/dist/WicketConnector.d.ts +0 -252
- package/dist/WicketConnector.d.ts.map +0 -1
- package/dist/WicketConnector.js +0 -938
- package/dist/WicketConnector.js.map +0 -1
- package/dist/WildApricotConnector.d.ts +0 -201
- package/dist/WildApricotConnector.d.ts.map +0 -1
- package/dist/WildApricotConnector.js +0 -1129
- package/dist/WildApricotConnector.js.map +0 -1
- package/dist/YourMembershipConnector.d.ts +0 -349
- package/dist/YourMembershipConnector.d.ts.map +0 -1
- package/dist/YourMembershipConnector.js +0 -4062
- package/dist/YourMembershipConnector.js.map +0 -1
- package/dist/generate-integration-actions.d.ts +0 -23
- package/dist/generate-integration-actions.d.ts.map +0 -1
- package/dist/generate-integration-actions.js +0 -201
- package/dist/generate-integration-actions.js.map +0 -1
package/dist/IMISConnector.js
DELETED
|
@@ -1,695 +0,0 @@
|
|
|
1
|
-
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
-
};
|
|
7
|
-
/**
|
|
8
|
-
* IMISConnector — Integration connector for iMIS EMS (Advanced Solutions International)
|
|
9
|
-
* REST API.
|
|
10
|
-
*
|
|
11
|
-
* ── Auth: OAuth 2.0 PASSWORD grant (resource-owner) ─────────────────────────
|
|
12
|
-
* Mints/refreshes a bearer ACCESS TOKEN via the shared {@link OAuth2TokenManager}
|
|
13
|
-
* (no inlined token/crypto logic). iMIS issues tokens via the resource-owner
|
|
14
|
-
* `grant_type=password` flow — username + password POSTed to the token endpoint:
|
|
15
|
-
* - default = `{BaseURL}/token`
|
|
16
|
-
* - override = the credential's `TokenURL` (when supplied)
|
|
17
|
-
* - fallback = the legacy `{BaseURL}/asiScheduler/token` path (older iMIS builds)
|
|
18
|
-
* iMIS does NOT require client_id/client_secret for the password grant, so the
|
|
19
|
-
* OAuth2TokenManager request is configured with empty client credentials in the
|
|
20
|
-
* body. Every API request sends `Authorization: Bearer {accessToken}`.
|
|
21
|
-
*
|
|
22
|
-
* ── Base URL ────────────────────────────────────────────────────────────────
|
|
23
|
-
* Comes from the credential's `BaseURL` (the tenant's iMIS API endpoint) — never
|
|
24
|
-
* a hardcoded host. Credential bytes are resolved at runtime, never at build.
|
|
25
|
-
*
|
|
26
|
-
* ── Catalog (metadata-driven, NOT hardcoded) ───────────────────────────────
|
|
27
|
-
* The Declared core object/field set comes from the seeded metadata loaded into
|
|
28
|
-
* the IntegrationEngineBase cache. The connector NEVER bakes an object/field catalog
|
|
29
|
-
* into code. DiscoverObjects/DiscoverFields express only the MECHANISM: they call the
|
|
30
|
-
* auth-gated /EntityDefinition + /{entity}/metadata endpoints at runtime to enumerate
|
|
31
|
-
* the tenant's Business-Object catalog + per-object fields, ADDITIVE to the Declared
|
|
32
|
-
* baseline. DiscoveryIsAuthoritative stays false (default) — these scoped enumerations
|
|
33
|
-
* never deactivate Declared metadata on absence.
|
|
34
|
-
*
|
|
35
|
-
* ── Pagination & incremental ───────────────────────────────────────────────
|
|
36
|
-
* iMIS uses the PagedResult envelope (`{ Items, Offset, Limit, Count, HasNext }`) with
|
|
37
|
-
* capitalized `Offset`/`Limit` query params; ExtractPaginationInfo reads HasNext/Offset/Limit
|
|
38
|
-
* and advances Offset by the returned count until HasNext is false. NormalizeResponse
|
|
39
|
-
* unwraps the Items collection. Incremental sync is metadata-driven: an IO with
|
|
40
|
-
* SupportsIncrementalSync=true emits its `IncrementalWatermarkField` as a `gt:` filter.
|
|
41
|
-
*
|
|
42
|
-
* ── Write ───────────────────────────────────────────────────────────────────
|
|
43
|
-
* CRUD rides the generic BaseRESTIntegrationConnector per-operation path: Create/Update/Delete
|
|
44
|
-
* read the per-operation IO columns (CreateAPIPath/Method/BodyShape/BodyKey/IDLocation, Update*,
|
|
45
|
-
* Delete*), creates route through BuildCreatedResult (fail loudly on empty ID), and DeleteMethod
|
|
46
|
-
* is metadata-driven (not assumed DELETE). Capability flags follow the per-operation columns the
|
|
47
|
-
* metadata declares — no hardcoded `true`, no 501 stubs. Full-record pass-through (Fields=raw).
|
|
48
|
-
*
|
|
49
|
-
* Reference: https://developer.imis.com/docs/imis-rest-api-data-models-and-swagger-json-files
|
|
50
|
-
*/
|
|
51
|
-
import { RegisterClass } from '@memberjunction/global';
|
|
52
|
-
import { Metadata } from '@memberjunction/core';
|
|
53
|
-
import { BaseIntegrationConnector, BaseRESTIntegrationConnector, OAuth2TokenManager, } from '@memberjunction/integration-engine';
|
|
54
|
-
import { IntegrationEngineBase } from '@memberjunction/integration-engine-base';
|
|
55
|
-
// ─── Constants ───────────────────────────────────────────────────────
|
|
56
|
-
/** The canonical MJ: Integrations.Name — part of the three-way invariant. */
|
|
57
|
-
const INTEGRATION_NAME = 'iMIS';
|
|
58
|
-
/** Default token endpoint path appended to the base when no TokenURL override is supplied. */
|
|
59
|
-
const DEFAULT_TOKEN_PATH = '/token';
|
|
60
|
-
/** Legacy token endpoint path for older iMIS deployments (documented fallback). */
|
|
61
|
-
const LEGACY_TOKEN_PATH = '/asiScheduler/token';
|
|
62
|
-
const DEFAULT_MAX_RETRIES = 3;
|
|
63
|
-
const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
|
|
64
|
-
const DEFAULT_MIN_REQUEST_INTERVAL_MS = 200;
|
|
65
|
-
const DEFAULT_PAGE_SIZE = 100;
|
|
66
|
-
/** iMIS-to-generic type mapping used when merging live-discovered field metadata. */
|
|
67
|
-
const IMIS_TYPE_MAP = {
|
|
68
|
-
'string': 'string',
|
|
69
|
-
'datetime': 'datetime',
|
|
70
|
-
'date': 'date',
|
|
71
|
-
'boolean': 'boolean',
|
|
72
|
-
'int32': 'integer',
|
|
73
|
-
'int64': 'integer',
|
|
74
|
-
'integer': 'integer',
|
|
75
|
-
'long': 'integer',
|
|
76
|
-
'decimal': 'decimal',
|
|
77
|
-
'double': 'decimal',
|
|
78
|
-
'float': 'decimal',
|
|
79
|
-
'guid': 'uuid',
|
|
80
|
-
'uuid': 'uuid',
|
|
81
|
-
'monetaryamountdata': 'decimal',
|
|
82
|
-
};
|
|
83
|
-
// ─── Connector Implementation ────────────────────────────────────────
|
|
84
|
-
let IMISConnector = class IMISConnector extends BaseRESTIntegrationConnector {
|
|
85
|
-
constructor() {
|
|
86
|
-
super(...arguments);
|
|
87
|
-
/** Cached auth context for the current sync run. */
|
|
88
|
-
this.authCache = null;
|
|
89
|
-
/** Shared OAuth2 token manager — owns the token round-trip + cache. */
|
|
90
|
-
this.tokenManager = new OAuth2TokenManager();
|
|
91
|
-
/** Timestamp of the last API request, for client-side throttling. */
|
|
92
|
-
this.lastRequestTime = 0;
|
|
93
|
-
}
|
|
94
|
-
// Returns the EXACT MJ: Integrations.Name string LITERAL so the T1 ThreeWayName invariant can
|
|
95
|
-
// statically parse the getter's returned value from connector source.
|
|
96
|
-
get IntegrationName() { return 'iMIS'; }
|
|
97
|
-
// ── Capability getters: METADATA-DRIVEN (no hardcoded answer) ─────
|
|
98
|
-
//
|
|
99
|
-
// Write capability FOLLOWS the per-operation CRUD columns on the cached IntegrationObjects
|
|
100
|
-
// (Declared metadata). An object is create-capable when it declares both CreateAPIPath +
|
|
101
|
-
// CreateMethod; same for update/delete. With no write metadata authored the surface is
|
|
102
|
-
// read-only (returns false) — but the moment a writable object's per-operation columns are
|
|
103
|
-
// populated, the capability flips on and the base generic CRUD path executes it.
|
|
104
|
-
get SupportsCreate() {
|
|
105
|
-
return this.anyObjectDeclares(o => !!o.CreateAPIPath && !!o.CreateMethod);
|
|
106
|
-
}
|
|
107
|
-
get SupportsUpdate() {
|
|
108
|
-
return this.anyObjectDeclares(o => !!o.UpdateAPIPath && !!o.UpdateMethod);
|
|
109
|
-
}
|
|
110
|
-
get SupportsDelete() {
|
|
111
|
-
return this.anyObjectDeclares(o => !!o.DeleteAPIPath && !!o.DeleteMethod);
|
|
112
|
-
}
|
|
113
|
-
get SupportsSearch() { return false; }
|
|
114
|
-
get SupportsListing() { return false; }
|
|
115
|
-
/** True when any cached IntegrationObject satisfies the predicate. []→false when the engine
|
|
116
|
-
* cache is unavailable (e.g. capability probed before configuration) — fail-safe read-only. */
|
|
117
|
-
anyObjectDeclares(pred) {
|
|
118
|
-
const integration = IntegrationEngineBase.Instance.GetIntegrationByName(INTEGRATION_NAME);
|
|
119
|
-
if (!integration)
|
|
120
|
-
return false;
|
|
121
|
-
return IntegrationEngineBase.Instance.GetActiveIntegrationObjects(integration.ID).some(pred);
|
|
122
|
-
}
|
|
123
|
-
// ─── BaseRESTIntegrationConnector abstract methods ──────────────
|
|
124
|
-
/**
|
|
125
|
-
* OAuth 2.0 password-grant authentication. Mints/refreshes the access token via the shared
|
|
126
|
-
* {@link OAuth2TokenManager} (no inlined token/crypto logic). One token exchange per run is
|
|
127
|
-
* cached and reused across every request.
|
|
128
|
-
*/
|
|
129
|
-
async Authenticate(companyIntegration, contextUser) {
|
|
130
|
-
if (this.authCache)
|
|
131
|
-
return this.authCache;
|
|
132
|
-
const config = await this.ParseConfig(companyIntegration, contextUser);
|
|
133
|
-
const baseUrl = this.ResolveBaseUrl(config);
|
|
134
|
-
const token = await this.MintToken(config, baseUrl);
|
|
135
|
-
const auth = { Token: token, BaseUrl: baseUrl, Config: config };
|
|
136
|
-
this.authCache = auth;
|
|
137
|
-
return auth;
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Runs the password-grant token round-trip through OAuth2TokenManager. Tries the resolved
|
|
141
|
-
* token endpoint first, then the legacy `/asiScheduler/token` path on failure (older iMIS).
|
|
142
|
-
*/
|
|
143
|
-
async MintToken(config, baseUrl) {
|
|
144
|
-
const primaryURL = this.ResolveTokenURL(config, baseUrl);
|
|
145
|
-
const req = this.BuildTokenRequest(config, primaryURL);
|
|
146
|
-
try {
|
|
147
|
-
const token = await this.tokenManager.GetAccessToken(req, 'password');
|
|
148
|
-
return token.AccessToken;
|
|
149
|
-
}
|
|
150
|
-
catch (primaryErr) {
|
|
151
|
-
// Legacy fallback only when no explicit override was given and the legacy path differs.
|
|
152
|
-
const legacyURL = `${baseUrl}${LEGACY_TOKEN_PATH}`;
|
|
153
|
-
if (config.TokenURL || legacyURL === primaryURL)
|
|
154
|
-
throw primaryErr;
|
|
155
|
-
this.tokenManager.Reset();
|
|
156
|
-
const token = await this.tokenManager.GetAccessToken({ ...req, TokenURL: legacyURL }, 'password');
|
|
157
|
-
return token.AccessToken;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
/** Builds the OAuth2 password-grant request. iMIS does not require client credentials. */
|
|
161
|
-
BuildTokenRequest(config, tokenURL) {
|
|
162
|
-
return {
|
|
163
|
-
TokenURL: tokenURL,
|
|
164
|
-
ClientId: config.ClientId ?? '',
|
|
165
|
-
ClientSecret: config.ClientSecret ?? '',
|
|
166
|
-
Username: config.Username,
|
|
167
|
-
Password: config.Password,
|
|
168
|
-
TimeoutMs: config.RequestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Extracts the new record's external ID from a create response. iMIS returns the created
|
|
173
|
-
* object with a vendor-specific ID field (Id / PartyId / EventId / InvoiceId / …); the base
|
|
174
|
-
* scanner only knows the generic `id` family, so widen it for iMIS's `{Object}Id` convention.
|
|
175
|
-
* The empty-ID case still routes through BuildCreatedResult, which fails loudly.
|
|
176
|
-
*/
|
|
177
|
-
ExtractIDFromResponse(response, idLocation) {
|
|
178
|
-
if ((!idLocation || idLocation === 'body') && response.Body && typeof response.Body === 'object') {
|
|
179
|
-
const b = response.Body;
|
|
180
|
-
const candidates = ['Id', 'ID', 'PartyId', 'UniformId', 'EventId', 'InvoiceId', 'PaymentId', 'id', 'externalID', 'ExternalID'];
|
|
181
|
-
for (const k of candidates) {
|
|
182
|
-
const v = b[k];
|
|
183
|
-
if (typeof v === 'string' || typeof v === 'number') {
|
|
184
|
-
const s = String(v).trim();
|
|
185
|
-
if (s.length > 0)
|
|
186
|
-
return s;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
return undefined;
|
|
190
|
-
}
|
|
191
|
-
return super.ExtractIDFromResponse(response, idLocation);
|
|
192
|
-
}
|
|
193
|
-
/** Sends the OAuth2 bearer token on every request. */
|
|
194
|
-
BuildHeaders(auth) {
|
|
195
|
-
const token = auth.Token ?? auth.Token ?? '';
|
|
196
|
-
return {
|
|
197
|
-
'Authorization': `Bearer ${token}`,
|
|
198
|
-
'Accept': 'application/json',
|
|
199
|
-
'Content-Type': 'application/json',
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
GetBaseURL(_companyIntegration, auth) {
|
|
203
|
-
return auth.BaseUrl;
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Unwraps the iMIS PagedResult envelope to the Items collection. Handles the envelope,
|
|
207
|
-
* an explicit responseDataKey, a raw array, and a single-object detail response. The FULL
|
|
208
|
-
* source record passes through (no field filtering) so the framework's custom-column capture
|
|
209
|
-
* sees everything the source returned.
|
|
210
|
-
*/
|
|
211
|
-
NormalizeResponse(rawBody, responseDataKey) {
|
|
212
|
-
if (rawBody == null)
|
|
213
|
-
return [];
|
|
214
|
-
// PagedResult envelope → Items (ResponseDataKey is typically "Items")
|
|
215
|
-
if (this.IsPagedResult(rawBody)) {
|
|
216
|
-
return rawBody.Items ?? [];
|
|
217
|
-
}
|
|
218
|
-
if (responseDataKey) {
|
|
219
|
-
const record = rawBody;
|
|
220
|
-
const data = record[responseDataKey];
|
|
221
|
-
if (Array.isArray(data))
|
|
222
|
-
return data;
|
|
223
|
-
}
|
|
224
|
-
if (Array.isArray(rawBody))
|
|
225
|
-
return rawBody;
|
|
226
|
-
// Single-object detail response (GET /{Entity}/{id}).
|
|
227
|
-
return [rawBody];
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* Derives Offset/Limit pagination state from the iMIS PagedResult envelope: advance Offset by
|
|
231
|
-
* the number of Items returned and continue while HasNext is true (terminate when HasNext is false).
|
|
232
|
-
*/
|
|
233
|
-
ExtractPaginationInfo(rawBody, paginationType, currentPage, currentOffset, _pageSize) {
|
|
234
|
-
if (paginationType === 'None')
|
|
235
|
-
return { HasMore: false };
|
|
236
|
-
const envelope = this.IsPagedResult(rawBody) ? rawBody : null;
|
|
237
|
-
if (!envelope) {
|
|
238
|
-
// No PagedResult envelope → cannot advance → no more pages.
|
|
239
|
-
return { HasMore: false };
|
|
240
|
-
}
|
|
241
|
-
const returnedCount = envelope.Items?.length ?? 0;
|
|
242
|
-
const hasMore = (envelope.HasNext ?? false) && returnedCount > 0;
|
|
243
|
-
const nextOffset = (envelope.Offset ?? currentOffset) + returnedCount;
|
|
244
|
-
return {
|
|
245
|
-
HasMore: hasMore,
|
|
246
|
-
NextOffset: paginationType === 'Offset' ? nextOffset : undefined,
|
|
247
|
-
NextPage: paginationType === 'PageNumber' ? currentPage + 1 : undefined,
|
|
248
|
-
TotalRecords: envelope.Count,
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
/**
|
|
252
|
-
* iMIS pagination uses capitalized `Offset` / `Limit` query parameters. Override the base
|
|
253
|
-
* helper to match iMIS's param names.
|
|
254
|
-
*/
|
|
255
|
-
BuildPaginatedURL(basePath, obj, page, offset, cursor, effectivePageSize) {
|
|
256
|
-
const pageSize = effectivePageSize ?? obj.DefaultPageSize ?? DEFAULT_PAGE_SIZE;
|
|
257
|
-
const separator = basePath.includes('?') ? '&' : '?';
|
|
258
|
-
switch (obj.PaginationType) {
|
|
259
|
-
case 'PageNumber':
|
|
260
|
-
return `${basePath}${separator}Page=${page}&Limit=${pageSize}`;
|
|
261
|
-
case 'Offset':
|
|
262
|
-
return `${basePath}${separator}Offset=${offset}&Limit=${pageSize}`;
|
|
263
|
-
case 'Cursor':
|
|
264
|
-
return cursor
|
|
265
|
-
? `${basePath}${separator}cursor=${encodeURIComponent(cursor)}&Limit=${pageSize}`
|
|
266
|
-
: `${basePath}${separator}Limit=${pageSize}`;
|
|
267
|
-
default:
|
|
268
|
-
return basePath;
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
/**
|
|
272
|
-
* Injects the incremental watermark filter when a sync is active. The param NAME is fully
|
|
273
|
-
* METADATA-DRIVEN: it comes from the IO's `IncrementalWatermarkField` and is emitted only when
|
|
274
|
-
* SupportsIncrementalSync=true AND a watermark value is in context. iMIS accepts operator-prefixed
|
|
275
|
-
* filter values (`gt:`) on list endpoints.
|
|
276
|
-
*/
|
|
277
|
-
AppendDefaultQueryParams(url, obj) {
|
|
278
|
-
let result = super.AppendDefaultQueryParams(url, obj);
|
|
279
|
-
const watermarkField = obj.IncrementalWatermarkField;
|
|
280
|
-
if (obj.SupportsIncrementalSync && watermarkField && this.currentWatermark) {
|
|
281
|
-
const separator = result.includes('?') ? '&' : '?';
|
|
282
|
-
const param = `${encodeURIComponent(watermarkField)}=${encodeURIComponent('gt:' + this.currentWatermark)}`;
|
|
283
|
-
result = `${result}${separator}${param}`;
|
|
284
|
-
}
|
|
285
|
-
return result;
|
|
286
|
-
}
|
|
287
|
-
/** Executes an HTTP request with client-side throttling + retry for 401/429/5xx. */
|
|
288
|
-
async MakeHTTPRequest(auth, url, method, headers, body) {
|
|
289
|
-
const imisAuth = auth;
|
|
290
|
-
const maxRetries = imisAuth.Config.MaxRetries ?? DEFAULT_MAX_RETRIES;
|
|
291
|
-
const timeoutMs = imisAuth.Config.RequestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
292
|
-
const minInterval = imisAuth.Config.MinRequestIntervalMs ?? DEFAULT_MIN_REQUEST_INTERVAL_MS;
|
|
293
|
-
const effectiveHeaders = { ...headers };
|
|
294
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
295
|
-
await this.ThrottleIfNeeded(minInterval);
|
|
296
|
-
const fetchOptions = {
|
|
297
|
-
method,
|
|
298
|
-
headers: effectiveHeaders,
|
|
299
|
-
signal: AbortSignal.timeout(timeoutMs),
|
|
300
|
-
};
|
|
301
|
-
if (body !== undefined && method !== 'GET') {
|
|
302
|
-
fetchOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
|
|
303
|
-
}
|
|
304
|
-
let response;
|
|
305
|
-
try {
|
|
306
|
-
response = await fetch(url, fetchOptions);
|
|
307
|
-
}
|
|
308
|
-
catch (err) {
|
|
309
|
-
if (attempt < maxRetries && this.IsTransientNetworkError(err)) {
|
|
310
|
-
await this.Sleep(this.BackoffDelay(attempt));
|
|
311
|
-
continue;
|
|
312
|
-
}
|
|
313
|
-
throw err;
|
|
314
|
-
}
|
|
315
|
-
this.lastRequestTime = Date.now();
|
|
316
|
-
// Token expired mid-run — force a fresh mint and retry once with the new bearer.
|
|
317
|
-
if (response.status === 401 && attempt < maxRetries) {
|
|
318
|
-
this.tokenManager.Reset();
|
|
319
|
-
this.authCache = null;
|
|
320
|
-
const fresh = await this.MintToken(imisAuth.Config, imisAuth.BaseUrl);
|
|
321
|
-
imisAuth.Token = fresh;
|
|
322
|
-
this.authCache = imisAuth;
|
|
323
|
-
effectiveHeaders['Authorization'] = `Bearer ${fresh}`;
|
|
324
|
-
continue;
|
|
325
|
-
}
|
|
326
|
-
if ((response.status === 429 || response.status >= 500) && attempt < maxRetries) {
|
|
327
|
-
console.warn(`[iMIS] HTTP ${response.status} from ${url} — backing off`);
|
|
328
|
-
await this.Sleep(this.RetryAfterMs(response) ?? this.BackoffDelay(attempt));
|
|
329
|
-
continue;
|
|
330
|
-
}
|
|
331
|
-
return this.BuildRESTResponse(response);
|
|
332
|
-
}
|
|
333
|
-
throw new Error(`iMIS request failed after ${maxRetries + 1} attempts: ${url}`);
|
|
334
|
-
}
|
|
335
|
-
// ─── TestConnection ──────────────────────────────────────────────
|
|
336
|
-
/**
|
|
337
|
-
* Tests connectivity by minting a password-grant token and listing one Party record. A 2xx
|
|
338
|
-
* confirms the OAuth2 credentials + base URL are valid against the live API.
|
|
339
|
-
*/
|
|
340
|
-
async TestConnection(companyIntegration, contextUser) {
|
|
341
|
-
try {
|
|
342
|
-
const auth = (await this.Authenticate(companyIntegration, contextUser));
|
|
343
|
-
const headers = this.BuildHeaders(auth);
|
|
344
|
-
const url = `${auth.BaseUrl}/Party?Limit=1`;
|
|
345
|
-
const response = await this.MakeHTTPRequest(auth, url, 'GET', headers);
|
|
346
|
-
if (response.Status < 200 || response.Status >= 300) {
|
|
347
|
-
return { Success: false, Message: `iMIS returned HTTP ${response.Status} from ${url}` };
|
|
348
|
-
}
|
|
349
|
-
return {
|
|
350
|
-
Success: true,
|
|
351
|
-
Message: `Connected to iMIS EMS at ${auth.BaseUrl}`,
|
|
352
|
-
ServerVersion: this.ExtractServerVersion(response.Headers),
|
|
353
|
-
};
|
|
354
|
-
}
|
|
355
|
-
catch (err) {
|
|
356
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
357
|
-
return { Success: false, Message: `Connection failed: ${message}` };
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
// ─── Discovery (metadata-driven baseline + runtime mechanism) ────
|
|
361
|
-
/**
|
|
362
|
-
* Discovers objects: the Declared core baseline from the IntegrationEngineBase cache, ADDITIVELY
|
|
363
|
-
* extended at runtime via the auth-gated /EntityDefinition endpoint (the tenant's customer
|
|
364
|
-
* Business-Object catalog). The catalog is NEVER baked into code — DiscoverObjects expresses only
|
|
365
|
-
* the discovery MECHANISM. Failures degrade gracefully to the Declared baseline.
|
|
366
|
-
*/
|
|
367
|
-
async DiscoverObjects(companyIntegration, contextUser) {
|
|
368
|
-
const declared = await super.DiscoverObjects(companyIntegration, contextUser);
|
|
369
|
-
const declaredNames = new Set(declared.map(o => o.Name.toLowerCase()));
|
|
370
|
-
try {
|
|
371
|
-
const discovered = await this.DiscoverEntityDefinitions(companyIntegration, contextUser);
|
|
372
|
-
const additive = discovered.filter(d => !declaredNames.has(d.Name.toLowerCase()));
|
|
373
|
-
return [...declared, ...additive];
|
|
374
|
-
}
|
|
375
|
-
catch (err) {
|
|
376
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
377
|
-
console.warn(`[iMIS] EntityDefinition discovery failed, returning declared objects only: ${message}`);
|
|
378
|
-
return declared;
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
/**
|
|
382
|
-
* Discovers fields: the Declared baseline from the cache, ADDITIVELY extended at runtime via the
|
|
383
|
-
* auth-gated /{entity}/metadata endpoint (the tenant's PropertyDefinitions). The field set is
|
|
384
|
-
* NEVER baked in code. Failures degrade gracefully to the Declared baseline.
|
|
385
|
-
*/
|
|
386
|
-
async DiscoverFields(companyIntegration, objectName, contextUser) {
|
|
387
|
-
const declared = await super.DiscoverFields(companyIntegration, objectName, contextUser);
|
|
388
|
-
try {
|
|
389
|
-
const live = await this.DiscoverFieldsFromLiveAPI(companyIntegration, objectName, contextUser);
|
|
390
|
-
return this.MergeFieldSchemas(declared, live);
|
|
391
|
-
}
|
|
392
|
-
catch (err) {
|
|
393
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
394
|
-
console.warn(`[iMIS] Live field discovery failed for "${objectName}", returning declared fields: ${message}`);
|
|
395
|
-
return declared;
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
// ─── FetchChanges override (watermark wiring) ────────────────────
|
|
399
|
-
/**
|
|
400
|
-
* Sets the watermark context the URL builder needs, delegates the walk to the base (which handles
|
|
401
|
-
* pagination + nested template-var paths), then advances the watermark from the returned records
|
|
402
|
-
* on the FINAL batch only (partial-failure-safe — a mid-stream failure leaves the watermark unchanged).
|
|
403
|
-
*/
|
|
404
|
-
async FetchChanges(ctx) {
|
|
405
|
-
this.currentWatermark = ctx.WatermarkValue ?? undefined;
|
|
406
|
-
try {
|
|
407
|
-
const result = await super.FetchChanges(ctx);
|
|
408
|
-
const isFinal = !result.HasMore;
|
|
409
|
-
result.NewWatermarkValue = isFinal
|
|
410
|
-
? this.ComputeNewWatermark(result.Records, ctx.WatermarkValue)
|
|
411
|
-
: undefined;
|
|
412
|
-
return result;
|
|
413
|
-
}
|
|
414
|
-
finally {
|
|
415
|
-
this.currentWatermark = undefined;
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
// ── Default configuration / field mappings ──────────────────────
|
|
419
|
-
GetDefaultConfiguration() {
|
|
420
|
-
return {
|
|
421
|
-
DefaultSchemaName: 'iMIS',
|
|
422
|
-
DefaultObjects: [],
|
|
423
|
-
};
|
|
424
|
-
}
|
|
425
|
-
GetDefaultFieldMappings(objectName, _entityName) {
|
|
426
|
-
switch (objectName) {
|
|
427
|
-
case 'Party':
|
|
428
|
-
case 'Person':
|
|
429
|
-
return [
|
|
430
|
-
{ SourceFieldName: 'PartyId', DestinationFieldName: 'ExternalID', IsKeyField: true },
|
|
431
|
-
{ SourceFieldName: 'FullName', DestinationFieldName: 'Name' },
|
|
432
|
-
{ SourceFieldName: 'PrimaryEmail', DestinationFieldName: 'Email' },
|
|
433
|
-
{ SourceFieldName: 'PrimaryPhone', DestinationFieldName: 'Phone' },
|
|
434
|
-
];
|
|
435
|
-
case 'Event':
|
|
436
|
-
return [
|
|
437
|
-
{ SourceFieldName: 'EventId', DestinationFieldName: 'ExternalID', IsKeyField: true },
|
|
438
|
-
{ SourceFieldName: 'Name', DestinationFieldName: 'Name' },
|
|
439
|
-
{ SourceFieldName: 'StartDate', DestinationFieldName: 'StartDate' },
|
|
440
|
-
{ SourceFieldName: 'EndDate', DestinationFieldName: 'EndDate' },
|
|
441
|
-
];
|
|
442
|
-
default:
|
|
443
|
-
return [];
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
// ─────────────────────────────────────────────────────────────────
|
|
447
|
-
// Private helpers
|
|
448
|
-
// ─────────────────────────────────────────────────────────────────
|
|
449
|
-
// ── Runtime discovery (Business Objects + field metadata) ───────
|
|
450
|
-
async DiscoverEntityDefinitions(companyIntegration, contextUser) {
|
|
451
|
-
const auth = (await this.Authenticate(companyIntegration, contextUser));
|
|
452
|
-
const url = `${auth.BaseUrl}/EntityDefinition?Limit=500`;
|
|
453
|
-
const headers = this.BuildHeaders(auth);
|
|
454
|
-
const response = await this.MakeHTTPRequest(auth, url, 'GET', headers);
|
|
455
|
-
if (response.Status < 200 || response.Status >= 300)
|
|
456
|
-
return [];
|
|
457
|
-
const records = this.NormalizeResponse(response.Body, 'Items');
|
|
458
|
-
return records
|
|
459
|
-
.filter(d => !!d.Name)
|
|
460
|
-
.map(d => ({
|
|
461
|
-
Name: String(d.Name),
|
|
462
|
-
Label: d.DisplayName ?? String(d.Name),
|
|
463
|
-
Description: d.Description ?? 'Tenant-defined Business Object (runtime-discovered)',
|
|
464
|
-
SupportsIncrementalSync: true,
|
|
465
|
-
SupportsWrite: false,
|
|
466
|
-
}));
|
|
467
|
-
}
|
|
468
|
-
async DiscoverFieldsFromLiveAPI(companyIntegration, objectName, contextUser) {
|
|
469
|
-
const auth = (await this.Authenticate(companyIntegration, contextUser));
|
|
470
|
-
const path = this.ResolveObjectPath(companyIntegration.IntegrationID, objectName);
|
|
471
|
-
const url = `${auth.BaseUrl}${path}/metadata`;
|
|
472
|
-
const headers = this.BuildHeaders(auth);
|
|
473
|
-
const response = await this.MakeHTTPRequest(auth, url, 'GET', headers);
|
|
474
|
-
if (response.Status < 200 || response.Status >= 300)
|
|
475
|
-
return [];
|
|
476
|
-
const meta = response.Body;
|
|
477
|
-
const propDefs = meta?.PropertyDefinitions ?? [];
|
|
478
|
-
return propDefs
|
|
479
|
-
.filter(p => !!p.Name)
|
|
480
|
-
.map(p => this.PropertyDefinitionToFieldSchema(p));
|
|
481
|
-
}
|
|
482
|
-
PropertyDefinitionToFieldSchema(prop) {
|
|
483
|
-
const rawType = (prop.PropertyType ?? prop.PropertyTypeData?.Name ?? 'string').toLowerCase();
|
|
484
|
-
const genericType = IMIS_TYPE_MAP[rawType] ?? 'string';
|
|
485
|
-
return {
|
|
486
|
-
Name: String(prop.Name),
|
|
487
|
-
Label: prop.DisplayName ?? String(prop.Name),
|
|
488
|
-
Description: prop.Description,
|
|
489
|
-
DataType: genericType,
|
|
490
|
-
IsRequired: !!prop.IsRequired,
|
|
491
|
-
// Provable-only: the source explicitly distinguishes PK; only set PK when stated.
|
|
492
|
-
IsPrimaryKey: prop.IsPrimaryKey === true ? true : undefined,
|
|
493
|
-
IsUniqueKey: !!prop.IsPrimaryKey,
|
|
494
|
-
IsReadOnly: !!prop.IsReadOnly,
|
|
495
|
-
MaxLength: prop.MaxLength ?? undefined,
|
|
496
|
-
};
|
|
497
|
-
}
|
|
498
|
-
/**
|
|
499
|
-
* Merge live-discovered fields with the Declared baseline. Live-only fields are appended;
|
|
500
|
-
* Declared fields win on matching names (the curated MJ schema is authoritative for the baseline).
|
|
501
|
-
*/
|
|
502
|
-
MergeFieldSchemas(declared, live) {
|
|
503
|
-
const declaredNames = new Set(declared.map(f => f.Name.toLowerCase()));
|
|
504
|
-
const liveOnly = live.filter(f => !declaredNames.has(f.Name.toLowerCase()));
|
|
505
|
-
return [...declared, ...liveOnly];
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* Resolve an object name to its API path. Prefers the configured APIPath from IntegrationObject
|
|
509
|
-
* metadata; falls back to `/{ObjectName}` for runtime-discovered Business Objects.
|
|
510
|
-
*/
|
|
511
|
-
ResolveObjectPath(integrationID, objectName) {
|
|
512
|
-
try {
|
|
513
|
-
const obj = this.GetCachedObject(integrationID, objectName);
|
|
514
|
-
if (obj.APIPath) {
|
|
515
|
-
return obj.APIPath.startsWith('/') ? obj.APIPath : `/${obj.APIPath}`;
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
catch {
|
|
519
|
-
// Not in Declared metadata — a runtime-discovered Business Object.
|
|
520
|
-
}
|
|
521
|
-
return `/${objectName}`;
|
|
522
|
-
}
|
|
523
|
-
// ── Config parsing ──────────────────────────────────────────────
|
|
524
|
-
/**
|
|
525
|
-
* Parses the connection config, preferring the attached MJ Credential over the raw Configuration
|
|
526
|
-
* JSON. Credential bytes are resolved at runtime — never at build.
|
|
527
|
-
*/
|
|
528
|
-
async ParseConfig(companyIntegration, contextUser) {
|
|
529
|
-
if (companyIntegration.CredentialID) {
|
|
530
|
-
return this.ParseConfigFromCredential(companyIntegration.CredentialID, contextUser);
|
|
531
|
-
}
|
|
532
|
-
if (companyIntegration.Configuration) {
|
|
533
|
-
return this.ValidateConfig(JSON.parse(companyIntegration.Configuration));
|
|
534
|
-
}
|
|
535
|
-
throw new Error('iMIS connector requires either CredentialID or Configuration JSON');
|
|
536
|
-
}
|
|
537
|
-
/** Loads the config from the MJ: Credentials entity Values JSON. */
|
|
538
|
-
async ParseConfigFromCredential(credentialID, contextUser, provider) {
|
|
539
|
-
const md = provider ?? new Metadata();
|
|
540
|
-
const cred = await md.GetEntityObject('MJ: Credentials', contextUser);
|
|
541
|
-
const loaded = await cred.Load(credentialID);
|
|
542
|
-
if (!loaded || !cred.Values) {
|
|
543
|
-
throw new Error('iMIS credential could not be loaded or has no Values JSON');
|
|
544
|
-
}
|
|
545
|
-
return this.ValidateConfig(JSON.parse(cred.Values));
|
|
546
|
-
}
|
|
547
|
-
/** Validates the parsed config + applies defaults. Field names are case-insensitive. */
|
|
548
|
-
ValidateConfig(raw) {
|
|
549
|
-
if (!raw || typeof raw !== 'object') {
|
|
550
|
-
throw new Error('iMIS configuration is not a valid object');
|
|
551
|
-
}
|
|
552
|
-
const obj = raw;
|
|
553
|
-
const getStr = (...keys) => {
|
|
554
|
-
for (const key of keys) {
|
|
555
|
-
const lower = key.toLowerCase();
|
|
556
|
-
for (const [k, v] of Object.entries(obj)) {
|
|
557
|
-
if (k.toLowerCase() === lower && typeof v === 'string' && v.length > 0)
|
|
558
|
-
return v;
|
|
559
|
-
}
|
|
560
|
-
}
|
|
561
|
-
return undefined;
|
|
562
|
-
};
|
|
563
|
-
const getNum = (...keys) => {
|
|
564
|
-
for (const key of keys) {
|
|
565
|
-
const lower = key.toLowerCase();
|
|
566
|
-
for (const [k, v] of Object.entries(obj)) {
|
|
567
|
-
if (k.toLowerCase() === lower && typeof v === 'number')
|
|
568
|
-
return v;
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
return undefined;
|
|
572
|
-
};
|
|
573
|
-
const baseURL = getStr('baseurl', 'base_url');
|
|
574
|
-
if (!baseURL)
|
|
575
|
-
throw new Error('iMIS configuration missing required field: BaseURL');
|
|
576
|
-
const username = getStr('username', 'user');
|
|
577
|
-
const password = getStr('password', 'pass');
|
|
578
|
-
if (!username)
|
|
579
|
-
throw new Error('iMIS configuration missing required field: Username');
|
|
580
|
-
if (!password)
|
|
581
|
-
throw new Error('iMIS configuration missing required field: Password');
|
|
582
|
-
return {
|
|
583
|
-
BaseURL: baseURL,
|
|
584
|
-
Username: username,
|
|
585
|
-
Password: password,
|
|
586
|
-
TokenURL: getStr('tokenurl', 'token_url'),
|
|
587
|
-
ClientId: getStr('clientid', 'client_id'),
|
|
588
|
-
ClientSecret: getStr('clientsecret', 'client_secret'),
|
|
589
|
-
MaxRetries: getNum('maxretries') ?? DEFAULT_MAX_RETRIES,
|
|
590
|
-
RequestTimeoutMs: getNum('requesttimeoutms') ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
591
|
-
MinRequestIntervalMs: getNum('minrequestintervalms') ?? DEFAULT_MIN_REQUEST_INTERVAL_MS,
|
|
592
|
-
};
|
|
593
|
-
}
|
|
594
|
-
/** Resolves the API base URL from the credential's BaseURL (never a hardcoded host). */
|
|
595
|
-
ResolveBaseUrl(config) {
|
|
596
|
-
return config.BaseURL.replace(/\/+$/, '');
|
|
597
|
-
}
|
|
598
|
-
/**
|
|
599
|
-
* Resolves the token endpoint: credential TokenURL override, else `{base}/token`. iMIS issues
|
|
600
|
-
* tokens at the host root (not under /api/), so a trailing /api segment is stripped.
|
|
601
|
-
*/
|
|
602
|
-
ResolveTokenURL(config, baseUrl) {
|
|
603
|
-
if (config.TokenURL && config.TokenURL.length > 0)
|
|
604
|
-
return config.TokenURL;
|
|
605
|
-
const root = baseUrl.replace(/\/api$/i, '');
|
|
606
|
-
return `${root}${DEFAULT_TOKEN_PATH}`;
|
|
607
|
-
}
|
|
608
|
-
// ── Watermark helper ────────────────────────────────────────────
|
|
609
|
-
ComputeNewWatermark(records, current) {
|
|
610
|
-
const candidateKeys = ['UpdatedOn', 'UpdateDate', 'ModifiedOn', 'LastUpdatedAt'];
|
|
611
|
-
let latest;
|
|
612
|
-
for (const record of records) {
|
|
613
|
-
for (const key of candidateKeys) {
|
|
614
|
-
const value = record.Fields[key];
|
|
615
|
-
if (typeof value === 'string' && (!latest || value > latest))
|
|
616
|
-
latest = value;
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
if (!latest)
|
|
620
|
-
return current ?? undefined;
|
|
621
|
-
if (current && latest <= current)
|
|
622
|
-
return current;
|
|
623
|
-
return latest;
|
|
624
|
-
}
|
|
625
|
-
// ── HTTP helpers ────────────────────────────────────────────────
|
|
626
|
-
/** Throttle to respect the configured minimum request interval. */
|
|
627
|
-
async ThrottleIfNeeded(minIntervalMs) {
|
|
628
|
-
const elapsed = Date.now() - this.lastRequestTime;
|
|
629
|
-
if (elapsed < minIntervalMs)
|
|
630
|
-
await this.Sleep(minIntervalMs - elapsed);
|
|
631
|
-
}
|
|
632
|
-
/** Parses a Retry-After header (seconds or http-date) into ms, if present. */
|
|
633
|
-
RetryAfterMs(response) {
|
|
634
|
-
const header = response.headers.get('retry-after');
|
|
635
|
-
if (!header)
|
|
636
|
-
return undefined;
|
|
637
|
-
const asSeconds = Number(header);
|
|
638
|
-
if (!isNaN(asSeconds))
|
|
639
|
-
return Math.max(0, asSeconds * 1_000);
|
|
640
|
-
const asDate = new Date(header).getTime();
|
|
641
|
-
if (!isNaN(asDate))
|
|
642
|
-
return Math.max(0, asDate - Date.now());
|
|
643
|
-
return undefined;
|
|
644
|
-
}
|
|
645
|
-
/** Exponential backoff delay for retry attempts (capped at 15s). */
|
|
646
|
-
BackoffDelay(attempt) {
|
|
647
|
-
return Math.min(1_000 * Math.pow(2, attempt), 15_000);
|
|
648
|
-
}
|
|
649
|
-
/** Checks whether an error is transient (network/timeout). */
|
|
650
|
-
IsTransientNetworkError(err) {
|
|
651
|
-
if (!(err instanceof Error))
|
|
652
|
-
return false;
|
|
653
|
-
const msg = err.message.toLowerCase();
|
|
654
|
-
return msg.includes('timeout') || msg.includes('abort') ||
|
|
655
|
-
msg.includes('econnreset') || msg.includes('econnrefused') ||
|
|
656
|
-
msg.includes('fetch failed');
|
|
657
|
-
}
|
|
658
|
-
/** Builds the normalized RESTResponse from a fetch Response. */
|
|
659
|
-
async BuildRESTResponse(response) {
|
|
660
|
-
const headers = {};
|
|
661
|
-
response.headers.forEach((v, k) => { headers[k.toLowerCase()] = v; });
|
|
662
|
-
const text = await response.text();
|
|
663
|
-
let body = null;
|
|
664
|
-
if (text.length > 0) {
|
|
665
|
-
try {
|
|
666
|
-
body = JSON.parse(text);
|
|
667
|
-
}
|
|
668
|
-
catch {
|
|
669
|
-
body = text;
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
return { Status: response.status, Body: body, Headers: headers };
|
|
673
|
-
}
|
|
674
|
-
ExtractServerVersion(headers) {
|
|
675
|
-
return headers['x-imis-version'] ?? headers['server'] ?? 'iMIS REST API';
|
|
676
|
-
}
|
|
677
|
-
/** True when a body is the iMIS PagedResult envelope (Items[] + Offset/Limit/HasNext). */
|
|
678
|
-
IsPagedResult(body) {
|
|
679
|
-
if (body == null || typeof body !== 'object' || Array.isArray(body))
|
|
680
|
-
return false;
|
|
681
|
-
const record = body;
|
|
682
|
-
return Array.isArray(record['Items']) && ('Offset' in record || 'Limit' in record || 'HasNext' in record);
|
|
683
|
-
}
|
|
684
|
-
/** Promise-wrapped setTimeout. */
|
|
685
|
-
Sleep(ms) {
|
|
686
|
-
return new Promise(resolve => setTimeout(resolve, ms));
|
|
687
|
-
}
|
|
688
|
-
};
|
|
689
|
-
IMISConnector = __decorate([
|
|
690
|
-
RegisterClass(BaseIntegrationConnector, 'IMISConnector')
|
|
691
|
-
], IMISConnector);
|
|
692
|
-
export { IMISConnector };
|
|
693
|
-
/** Tree-shaking prevention — import and call from the package entry point. */
|
|
694
|
-
export function LoadIMISConnector() { }
|
|
695
|
-
//# sourceMappingURL=IMISConnector.js.map
|