@contrail/flexplm 2.0.0-alpha.fe82e73 → 3.0.0-alpha.0c21bba

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/lib/entity-processor/base-entity-processor.d.ts +0 -29
  2. package/lib/entity-processor/base-entity-processor.js +143 -238
  3. package/lib/entity-processor/base-entity-processor.spec.js +0 -210
  4. package/lib/index.d.ts +0 -1
  5. package/lib/index.js +0 -1
  6. package/lib/interfaces/interfaces.d.ts +1 -1
  7. package/lib/publish/base-process-publish-assortment-callback.js +0 -30
  8. package/lib/publish/base-process-publish-assortment.d.ts +0 -24
  9. package/lib/publish/base-process-publish-assortment.js +132 -238
  10. package/lib/publish/base-process-publish-assortment.spec.js +0 -188
  11. package/lib/util/config-defaults.js +0 -2
  12. package/lib/util/error-response-object.js +0 -2
  13. package/lib/util/flexplm-connect.d.ts +9 -4
  14. package/lib/util/flexplm-connect.js +172 -202
  15. package/lib/util/flexplm-connect.spec.js +166 -2
  16. package/lib/util/thumbnail-util.d.ts +1 -2
  17. package/lib/util/thumbnail-util.js +6 -34
  18. package/lib/util/thumbnail-util.spec.js +0 -42
  19. package/lib/util/type-utils.d.ts +3 -3
  20. package/package.json +17 -12
  21. package/lib/__tests__/telemetry-test-utils.d.ts +0 -8
  22. package/lib/__tests__/telemetry-test-utils.js +0 -30
  23. package/lib/publish/base-process-publish-assortment-callback.spec.d.ts +0 -1
  24. package/lib/publish/base-process-publish-assortment-callback.spec.js +0 -62
  25. package/lib/util/flexplm-connect.telemetry.spec.d.ts +0 -1
  26. package/lib/util/flexplm-connect.telemetry.spec.js +0 -212
  27. package/lib/util/telemetry-attributes.d.ts +0 -68
  28. package/lib/util/telemetry-attributes.js +0 -73
  29. package/lib/util/telemetry-utils.d.ts +0 -3
  30. package/lib/util/telemetry-utils.js +0 -10
@@ -2,25 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FlexPLMConnect = void 0;
4
4
  const app_framework_1 = require("@contrail/app-framework");
5
- const telemetry_1 = require("@contrail/telemetry");
6
- const telemetry_attributes_1 = require("./telemetry-attributes");
7
- const telemetry_utils_1 = require("./telemetry-utils");
8
- // Telemetry: only the path is recorded, never the host or the query string (it can carry file paths).
9
- const toUrlPath = (path) => (path || '').split('?')[0];
10
- const MAX_LOGGED_RESPONSE_BODY = 2048;
11
- /** Reads the response body for an error log; never throws (the body may already be consumed). */
12
- const readBodyForLog = async (response) => {
13
- try {
14
- const text = await response.text();
15
- return text.length > MAX_LOGGED_RESPONSE_BODY ? text.substring(0, MAX_LOGGED_RESPONSE_BODY) + '...(truncated)' : text;
16
- }
17
- catch (e) {
18
- return '(response body unavailable)';
19
- }
20
- };
21
- const logFlexPLMError = async (message, response, urlPath) => {
22
- telemetry_1.logger.error({ flexplm: { status: response.status, url_path: urlPath, response_body: await readBodyForLog(response) } }, message);
23
- };
24
5
  // Module-level on purpose: a new FlexPLMConnect is constructed for every event. Declaring for Session reusing use case.
25
6
  const sessionCache = new Map();
26
7
  // Upper bound so users/option combinations that are never requested again cannot accumulate cookies forever.
@@ -87,6 +68,13 @@ class FlexPLMConnect {
87
68
  this.staticHeaders = this.config?.flexplmConnect?.staticHeaders;
88
69
  }
89
70
  }
71
+ /** When true, a success response whose body is not JSON is returned as `data: { responseBody }`
72
+ * instead of failing the event. Configured via `flexplmConnect.allowNonJsonResponse` (default false).
73
+ */
74
+ get allowNonJsonResponse() {
75
+ const allow = this.config?.flexplmConnect?.allowNonJsonResponse;
76
+ return allow === true || String(allow).toLowerCase() === 'true';
77
+ }
90
78
  /////////////////////////////////////////////////////////////////////////////
91
79
  ///////// ET-390 - Session reuse: start
92
80
  /////////////////////////////////////////////////////////////////////////////
@@ -117,14 +105,6 @@ class FlexPLMConnect {
117
105
  }
118
106
  })();
119
107
  }
120
- /** Marks the active span when this request is about to wait for another request's cold acquisition.
121
- * Synchronous on purpose: it must not add an await to the wait loops (see waitForInFlightAcquisition).
122
- */
123
- recordWaitForInFlightAcquisition() {
124
- if (inFlightAcquisitions.has(this.getSessionKey())) {
125
- (0, telemetry_utils_1.setActiveSpanAttributes)({ [telemetry_attributes_1.ATTR_FLEXPLM_SESSION_WAITED]: true });
126
- }
127
- }
128
108
  /** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
129
109
  async runColdAcquisition(acquire) {
130
110
  const key = this.getSessionKey();
@@ -250,11 +230,8 @@ class FlexPLMConnect {
250
230
  // rejectedCookie: the cookie that was rejected by the caller, so a refresh already done by a concurrent event is not thrown away
251
231
  async getCSRF(getNewSession = false, rejectedCookie) {
252
232
  // Added for Session reuse - ET-390 - Starts
253
- if (!this.sessionOptions.enabled) {
254
- (0, telemetry_utils_1.setActiveSpanAttributes)({ [telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE]: 'disabled' });
233
+ if (!this.sessionOptions.enabled)
255
234
  return this.fetchCSRF(undefined);
256
- }
257
- this.recordWaitForInFlightAcquisition();
258
235
  for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
259
236
  await wait;
260
237
  if (getNewSession) {
@@ -263,8 +240,6 @@ class FlexPLMConnect {
263
240
  this.clearSession();
264
241
  }
265
242
  const cached = this.getCachedSession();
266
- // Set on the caller's span; a retry below overwrites it with the session that was finally used.
267
- (0, telemetry_utils_1.setActiveSpanAttributes)({ [telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE]: cached ? 'cached' : 'new' });
268
243
  if (cached) {
269
244
  try {
270
245
  return await this.fetchCSRF(cached);
@@ -286,62 +261,50 @@ class FlexPLMConnect {
286
261
  const csrfEndpoint = this.config.csrfEndpoint;
287
262
  const csrfURL = this.config.apiHost + urlContext + csrfEndpoint;
288
263
  console.info('csrfURL: ' + csrfURL);
289
- const urlPath = toUrlPath(urlContext + csrfEndpoint);
290
- const result = await (0, telemetry_1.traceSection)('fetch_flexplm_csrf', {
291
- [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_KIND]: 'csrf',
292
- [telemetry_attributes_1.ATTR_HTTP_REQUEST_METHOD]: 'GET',
293
- [telemetry_attributes_1.ATTR_URL_PATH]: urlPath,
294
- }, async (span) => {
295
- // getRequestOptions will be called with additional sentCookie parameter
296
- const csrfOptions = this.getRequestOptions('GET', sentCookie);
297
- const response = await fetch(csrfURL, csrfOptions);
298
- span.setAttribute(telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
299
- // Added for Session reuse - ET-390 - Starts
300
- if (sentCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
301
- console.warn('Cached FlexPLM session rejected on csrf call (status ' + response.status + '). Retrying with a new session.');
302
- // Expected and retried by getCSRF, so it is an event and the span stays OK.
303
- span.addEvent('flexplm_session_rejected');
304
- await this.discardBody(response);
305
- return { sessionRejected: true };
306
- }
307
- // Added for Session reuse - ET-390 - Ends
308
- if (response.status >= 300) {
309
- const message = 'Error connecting to FlexPLM:status: ' + response.status;
310
- await logFlexPLMError(message, response, urlPath);
311
- const e = new Error(message);
312
- e['httpResponseStatus'] = response.status;
313
- throw e;
314
- }
315
- // Added for Session reuse - ET-390 - Starts
316
- // If the cookie we sent was invalid, Windchill answers with a fresh Set-Cookie --> replace the cache.
317
- let sessionCookie = sentCookie;
318
- if (this.sessionOptions.enabled) {
319
- sessionCookie = this.extractSessionCookie(response) ?? sentCookie;
320
- if (sessionCookie)
321
- this.storeSession(sessionCookie);
322
- }
323
- // Added for Session reuse - ET-390 - Ends
324
- try {
325
- const body = await response.json();
326
- const nonce_key = body.items[0].attributes.nonce_key;
327
- const nonce = body.items[0].attributes.nonce;
328
- // ET-390 - adding sessionCookie to the return
329
- return {
330
- nonce_key,
331
- nonce,
332
- sessionCookie,
333
- };
334
- }
335
- catch (e) {
336
- const message = 'Error connecting to FlexPLM: ' + e.message;
337
- await logFlexPLMError(message, response, urlPath);
338
- throw new Error(message);
339
- }
340
- });
341
- // Thrown outside the span so the expected rejection is not recorded as a span error.
342
- if ('sessionRejected' in result)
264
+ // getRequestOptions will be called with additional sentCookie parameter
265
+ const csrfOptions = this.getRequestOptions('GET', sentCookie);
266
+ const response = await fetch(csrfURL, csrfOptions);
267
+ // Added for Session reuse - ET-390 - Starts
268
+ if (sentCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
269
+ console.warn('Cached FlexPLM session rejected on csrf call (status ' + response.status + '). Retrying with a new session.');
270
+ await this.discardBody(response);
343
271
  throw new SessionRejectedError();
344
- return result;
272
+ }
273
+ // Added for Session reuse - ET-390 - Ends
274
+ if (response.status >= 300) {
275
+ const message = 'Error connecting to FlexPLM:status: ' + response.status;
276
+ console.error(message);
277
+ console.error(await response.text());
278
+ const e = new Error(message);
279
+ e['httpResponseStatus'] = response.status;
280
+ throw e;
281
+ }
282
+ // Added for Session reuse - ET-390 - Starts
283
+ // If the cookie we sent was invalid, Windchill answers with a fresh Set-Cookie --> replace the cache.
284
+ let sessionCookie = sentCookie;
285
+ if (this.sessionOptions.enabled) {
286
+ sessionCookie = this.extractSessionCookie(response) ?? sentCookie;
287
+ if (sessionCookie)
288
+ this.storeSession(sessionCookie);
289
+ }
290
+ // Added for Session reuse - ET-390 - Ends
291
+ try {
292
+ const body = await response.json();
293
+ const nonce_key = body.items[0].attributes.nonce_key;
294
+ const nonce = body.items[0].attributes.nonce;
295
+ // ET-390 - adding sessionCookie to the return
296
+ return {
297
+ nonce_key,
298
+ nonce,
299
+ sessionCookie,
300
+ };
301
+ }
302
+ catch (e) {
303
+ const message = 'Error connecting to FlexPLM: ' + e.message;
304
+ console.error(message);
305
+ console.error(await response.text());
306
+ throw new Error(message);
307
+ }
345
308
  }
346
309
  async sendRequest(csrf, payload) {
347
310
  if (this.payloadSendAsArray && !Array.isArray(payload)) {
@@ -369,73 +332,91 @@ class FlexPLMConnect {
369
332
  return eventResponse;
370
333
  }
371
334
  async processRequest(payload) {
372
- const urlPath = toUrlPath(this.config.urlContext + '/servlet/rest' + this.vibeEventEndpoint);
373
- return (0, telemetry_1.traceSection)('send_to_flexplm', {
374
- [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_KIND]: 'send',
375
- [telemetry_attributes_1.ATTR_HTTP_REQUEST_METHOD]: 'POST',
376
- [telemetry_attributes_1.ATTR_URL_PATH]: urlPath,
377
- [telemetry_attributes_1.ATTR_FLEXPLM_PAYLOAD_COUNT]: Array.isArray(payload) ? payload.length : (payload ? 1 : 0),
378
- [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED]: false,
379
- }, async (span) => {
380
- if (!payload) {
381
- const message = 'No payload to send to FlexPLM';
382
- console.error(message);
383
- throw new Error(message);
384
- }
385
- if (app_framework_1.Logger.isInfoOn()) {
386
- console.info('payload: ' + JSON.stringify(payload));
387
- }
388
- let csrf = await this.getCSRF();
389
- if (!csrf) {
390
- const message = 'Failed to get CSRF nonce';
391
- console.error(message);
392
- throw new Error(message);
393
- }
394
- /// Added for Session reuse - ET-390 - Starts
395
- // const response = await this.sendRequest(csrf, payload);
396
- let response = await this.sendRequest(csrf, payload);
397
- if (csrf.sessionCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
398
- console.warn('FlexPLM rejected session/nonce (status ' + response.status + '). Getting a new session and retrying once.');
399
- span.setAttribute(telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED, true);
400
- await this.discardBody(response);
401
- csrf = await this.getCSRF(true, csrf.sessionCookie);
402
- response = await this.sendRequest(csrf, payload);
335
+ if (!payload) {
336
+ const message = 'No payload to send to FlexPLM';
337
+ console.error(message);
338
+ throw new Error(message);
339
+ }
340
+ if (app_framework_1.Logger.isInfoOn()) {
341
+ console.info('payload: ' + JSON.stringify(payload));
342
+ }
343
+ let csrf = await this.getCSRF();
344
+ if (!csrf) {
345
+ const message = 'Failed to get CSRF nonce';
346
+ console.error(message);
347
+ throw new Error(message);
348
+ }
349
+ /// Added for Session reuse - ET-390 - Starts
350
+ // const response = await this.sendRequest(csrf, payload);
351
+ let response = await this.sendRequest(csrf, payload);
352
+ if (csrf.sessionCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
353
+ console.warn('FlexPLM rejected session/nonce (status ' + response.status + '). Getting a new session and retrying once.');
354
+ await this.discardBody(response);
355
+ csrf = await this.getCSRF(true, csrf.sessionCookie);
356
+ response = await this.sendRequest(csrf, payload);
357
+ }
358
+ // Added for Session reuse - ET-390 - Ends
359
+ const status = response.status;
360
+ if (status >= 300) {
361
+ let responseBody;
362
+ try {
363
+ responseBody = await response.text();
403
364
  }
404
- // Added for Session reuse - ET-390 - Ends
405
- const status = response.status;
406
- span.setAttribute(telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE, status);
407
- if (status >= 300) {
408
- // traceSection records the thrown error and sets the span status to ERROR.
409
- const message = 'Error sending data to FlexPLM:status: ' + response.status;
410
- await logFlexPLMError(message, response, urlPath);
411
- const e = new Error(message);
412
- e['httpResponseStatus'] = status;
413
- throw e;
365
+ catch (e) {
366
+ console.error('Error reading FlexPLM error response body: ' + e?.message);
414
367
  }
368
+ throw this.createResponseError('Error sending data to FlexPLM:status: ' + status, status, responseBody);
369
+ }
370
+ const res = {
371
+ status,
372
+ };
373
+ if (![204, 205].includes(status)) {
374
+ let responseBody;
415
375
  try {
416
- const res = {
417
- status,
418
- };
419
- if (![204, 205].includes(status)) {
376
+ responseBody = await response.text();
377
+ if (responseBody.trim() === '') {
378
+ // An empty body is a valid success response.
379
+ res.data = {};
380
+ }
381
+ else {
420
382
  try {
421
- const data = await response.json();
422
- res.data = data;
383
+ res.data = JSON.parse(responseBody);
423
384
  }
424
- catch (e) {
425
- console.error('Error getting response body. Setting {} body: ' + e);
426
- res.data = {};
385
+ catch (parseError) {
386
+ if (!this.allowNonJsonResponse)
387
+ throw parseError;
388
+ console.warn('FlexPLM response is not JSON; allowNonJsonResponse is enabled, returning raw body. status: ' + status);
389
+ res.data = { responseBody };
427
390
  }
428
391
  }
429
- console.log('eventResponse.status: ' + status);
430
- // console.log('eventBody: ', JSON.stringify(data));
431
- return res;
432
392
  }
433
393
  catch (e) {
434
- const message = 'Error getting json data from FlexPLM: ' + e.message;
435
- await logFlexPLMError(message, response, urlPath);
436
- throw new Error(message);
394
+ throw this.createResponseError('Error getting json data from FlexPLM:status: ' + status + ': ' + e?.message, status, responseBody);
395
+ }
396
+ }
397
+ console.log('eventResponse.status: ' + status);
398
+ return res;
399
+ }
400
+ /** Builds the error thrown for a failed FlexPLM response. The response body is put on
401
+ * `details` so that it is surfaced as `errorDetails` in the event output.
402
+ * The body is parsed as JSON when possible, otherwise it is kept as the raw text.
403
+ */
404
+ createResponseError(message, status, responseBody) {
405
+ console.error(message);
406
+ console.error('responseBody: ' + responseBody);
407
+ let body = responseBody;
408
+ if (responseBody) {
409
+ try {
410
+ body = JSON.parse(responseBody);
411
+ }
412
+ catch {
413
+ // keep raw text
437
414
  }
438
- });
415
+ }
416
+ const e = new Error(message);
417
+ e['httpResponseStatus'] = status;
418
+ e['details'] = { httpResponseStatus: status, responseBody: body };
419
+ return e;
439
420
  }
440
421
  async sendToFlexPLM(payload) {
441
422
  return await this.processRequest(payload);
@@ -455,65 +436,54 @@ class FlexPLMConnect {
455
436
  const urlContext = includeUrlContext ? this.config.urlContext : '';
456
437
  const path = urlPath || ('/servlet/rest' + this.vibeEventEndpoint);
457
438
  const vibeEventsURL = this.config.apiHost + urlContext + path;
458
- const spanUrlPath = toUrlPath(urlContext + path);
459
- return (0, telemetry_1.traceSection)('get_from_flexplm', {
460
- [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_KIND]: 'get',
461
- [telemetry_attributes_1.ATTR_HTTP_REQUEST_METHOD]: 'GET',
462
- [telemetry_attributes_1.ATTR_URL_PATH]: spanUrlPath,
463
- [telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED]: false,
464
- }, async (span) => {
465
- // Added for Session reuse - ET-390 - Starts
466
- const attempt = async () => {
467
- if (!this.sessionOptions.enabled) {
468
- span.setAttribute(telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE, 'disabled');
469
- return { response: await fetch(vibeEventsURL, this.getRequestOptions('GET')), sent: undefined };
439
+ // Added for Session reuse - ET-390 - Starts
440
+ const attempt = async () => {
441
+ if (!this.sessionOptions.enabled) {
442
+ return { response: await fetch(vibeEventsURL, this.getRequestOptions('GET')), sent: undefined };
443
+ }
444
+ for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
445
+ await wait;
446
+ const sent = this.getCachedSession();
447
+ const call = async () => {
448
+ const res = await fetch(vibeEventsURL, this.getRequestOptions('GET', sent));
449
+ // A rejected cookie must not be stored again; only keep a cookie that was accepted or newly issued.
450
+ if (!(sent && this.sessionOptions.retryStatuses.includes(res.status))) {
451
+ const cookie = this.extractSessionCookie(res) ?? sent;
452
+ if (cookie)
453
+ this.storeSession(cookie);
470
454
  }
471
- this.recordWaitForInFlightAcquisition();
472
- for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
473
- await wait;
474
- const sent = this.getCachedSession();
475
- span.setAttribute(telemetry_attributes_1.ATTR_FLEXPLM_SESSION_SOURCE, sent ? 'cached' : 'new');
476
- const call = async () => {
477
- const res = await fetch(vibeEventsURL, this.getRequestOptions('GET', sent));
478
- // A rejected cookie must not be stored again; only keep a cookie that was accepted or newly issued.
479
- if (!(sent && this.sessionOptions.retryStatuses.includes(res.status))) {
480
- const cookie = this.extractSessionCookie(res) ?? sent;
481
- if (cookie)
482
- this.storeSession(cookie);
483
- }
484
- return { response: res, sent };
485
- };
486
- return sent ? call() : this.runColdAcquisition(call);
455
+ return { response: res, sent };
487
456
  };
488
- const first = await attempt();
489
- let response = first.response;
490
- if (first.sent && this.sessionOptions.retryStatuses.includes(response.status)) {
491
- span.setAttribute(telemetry_attributes_1.ATTR_FLEXPLM_REQUEST_RETRIED, true);
492
- await this.discardBody(response);
493
- if (this.getCachedSession() === first.sent)
494
- this.clearSession();
495
- response = (await attempt()).response;
496
- }
497
- // Added for Session reuse - ET-390 - Ends
498
- span.setAttribute(telemetry_attributes_1.ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
499
- if (response.status >= 300) {
500
- const message = 'Error connecting to FlexPLM:status: ' + response.status;
501
- await logFlexPLMError(message, response, spanUrlPath);
502
- throw new Error(message);
503
- }
504
- if (returnFullResponse) {
505
- return response;
506
- }
507
- try {
508
- const data = await response.json();
509
- return data;
510
- }
511
- catch (e) {
512
- const message = 'Error getting json data from FlexPLM: ' + e.message;
513
- await logFlexPLMError(message, response, spanUrlPath);
514
- throw new Error(message);
515
- }
516
- });
457
+ return sent ? call() : this.runColdAcquisition(call);
458
+ };
459
+ const first = await attempt();
460
+ let response = first.response;
461
+ if (first.sent && this.sessionOptions.retryStatuses.includes(response.status)) {
462
+ await this.discardBody(response);
463
+ if (this.getCachedSession() === first.sent)
464
+ this.clearSession();
465
+ response = (await attempt()).response;
466
+ }
467
+ // Added for Session reuse - ET-390 - Ends
468
+ if (response.status >= 300) {
469
+ const message = 'Error connecting to FlexPLM:status: ' + response.status;
470
+ console.error(message);
471
+ console.error(await response.text());
472
+ throw new Error(message);
473
+ }
474
+ if (returnFullResponse) {
475
+ return response;
476
+ }
477
+ try {
478
+ const data = await response.json();
479
+ return data;
480
+ }
481
+ catch (e) {
482
+ const message = 'Error getting json data from FlexPLM: ' + e.message;
483
+ console.error(message);
484
+ console.error(await response.text());
485
+ throw new Error(message);
486
+ }
517
487
  }
518
488
  }
519
489
  exports.FlexPLMConnect = FlexPLMConnect;
@@ -1,4 +1,37 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  const flexplm_connect_1 = require("./flexplm-connect");
4
37
  const app_framework_1 = require("@contrail/app-framework");
@@ -6,7 +39,7 @@ const mockJsonData = { items: [{ id: '123', name: 'test' }] };
6
39
  const mockResponse = (status, json = mockJsonData) => ({
7
40
  status,
8
41
  json: jest.fn().mockResolvedValue(json),
9
- text: jest.fn().mockResolvedValue('error text'),
42
+ text: jest.fn().mockResolvedValue(JSON.stringify(json)),
10
43
  });
11
44
  const globalFetch = global.fetch;
12
45
  beforeEach(() => {
@@ -34,7 +67,7 @@ const csrfBody = { items: [{ attributes: { nonce_key: 'CSRF_NONCE', nonce: 'n1'
34
67
  const resp = (status, setCookie = [], json = csrfBody) => ({
35
68
  status,
36
69
  json: jest.fn().mockResolvedValue(json),
37
- text: jest.fn().mockResolvedValue('error text'),
70
+ text: jest.fn().mockResolvedValue(JSON.stringify(json)),
38
71
  headers: { getSetCookie: () => setCookie, get: () => null },
39
72
  });
40
73
  let userCounter = 0;
@@ -138,6 +171,137 @@ describe('FlexPLMConnect.sendRequest', () => {
138
171
  consoleInfoSpy.mockRestore();
139
172
  });
140
173
  });
174
+ describe('FlexPLMConnect.sendToFlexPLM response body handling', () => {
175
+ const payload = { id: '123' };
176
+ const postResp = (status, text) => ({
177
+ status,
178
+ json: jest.fn(),
179
+ text,
180
+ headers: { getSetCookie: () => [], get: () => null },
181
+ });
182
+ let consoleErrorSpy;
183
+ beforeEach(() => {
184
+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation();
185
+ });
186
+ afterEach(() => {
187
+ consoleErrorSpy.mockRestore();
188
+ });
189
+ it('should return the parsed JSON body on success', async () => {
190
+ fetchMock()
191
+ .mockResolvedValueOnce(resp(200))
192
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockResolvedValue('{"ok":true}')));
193
+ const result = await new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
194
+ expect(result).toEqual({ status: 200, data: { ok: true } });
195
+ });
196
+ it('should fail when the response body is not valid JSON', async () => {
197
+ fetchMock()
198
+ .mockResolvedValueOnce(resp(200))
199
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockResolvedValue('<html>Server Error</html>')));
200
+ const promise = new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
201
+ await expect(promise).rejects.toThrow('Error getting json data from FlexPLM:status: 200');
202
+ await expect(promise).rejects.toHaveProperty('httpResponseStatus', 200);
203
+ await expect(promise).rejects.toHaveProperty('details', {
204
+ httpResponseStatus: 200,
205
+ responseBody: '<html>Server Error</html>',
206
+ });
207
+ expect(consoleErrorSpy).toHaveBeenCalledWith('responseBody: <html>Server Error</html>');
208
+ });
209
+ it.each(['', ' \n'])('should succeed with empty data when the response body is empty (%j)', async (body) => {
210
+ fetchMock()
211
+ .mockResolvedValueOnce(resp(200))
212
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockResolvedValue(body)));
213
+ const result = await new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
214
+ expect(result).toEqual({ status: 200, data: {} });
215
+ });
216
+ it('should fail when reading the response body throws', async () => {
217
+ fetchMock()
218
+ .mockResolvedValueOnce(resp(200))
219
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockRejectedValue(new Error('stream aborted'))));
220
+ const promise = new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
221
+ await expect(promise).rejects.toThrow('Error getting json data from FlexPLM:status: 200: stream aborted');
222
+ await expect(promise).rejects.toHaveProperty('details', { httpResponseStatus: 200, responseBody: undefined });
223
+ });
224
+ it('should include a JSON error body, parsed, on the error for status >= 300', async () => {
225
+ const errorBody = { message: 'Attribute xyz is not valid', code: 'INVALID_ATTR' };
226
+ fetchMock()
227
+ .mockResolvedValueOnce(resp(200))
228
+ .mockResolvedValueOnce(postResp(400, jest.fn().mockResolvedValue(JSON.stringify(errorBody))));
229
+ const promise = new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
230
+ await expect(promise).rejects.toThrow('Error sending data to FlexPLM:status: 400');
231
+ await expect(promise).rejects.toHaveProperty('httpResponseStatus', 400);
232
+ await expect(promise).rejects.toHaveProperty('details', { httpResponseStatus: 400, responseBody: errorBody });
233
+ });
234
+ it('should include a non-JSON error body, as text, on the error for status >= 300', async () => {
235
+ fetchMock()
236
+ .mockResolvedValueOnce(resp(200))
237
+ .mockResolvedValueOnce(postResp(500, jest.fn().mockResolvedValue('Internal Server Error')));
238
+ await expect(new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload))
239
+ .rejects.toHaveProperty('details', { httpResponseStatus: 500, responseBody: 'Internal Server Error' });
240
+ });
241
+ it('should still fail with the status error when reading the error body throws', async () => {
242
+ fetchMock()
243
+ .mockResolvedValueOnce(resp(200))
244
+ .mockResolvedValueOnce(postResp(502, jest.fn().mockRejectedValue(new Error('stream aborted'))));
245
+ const promise = new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
246
+ await expect(promise).rejects.toThrow('Error sending data to FlexPLM:status: 502');
247
+ await expect(promise).rejects.toHaveProperty('details', { httpResponseStatus: 502, responseBody: undefined });
248
+ });
249
+ it('should surface the error body as errorDetails in the event output', async () => {
250
+ const { ErrorResponseObject } = await Promise.resolve().then(() => __importStar(require('./error-response-object')));
251
+ fetchMock()
252
+ .mockResolvedValueOnce(resp(200))
253
+ .mockResolvedValueOnce(postResp(400, jest.fn().mockResolvedValue('{"message":"bad"}')));
254
+ const error = await new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload).catch(e => e);
255
+ expect(ErrorResponseObject.getResponse(error).output.errorDetails)
256
+ .toEqual({ httpResponseStatus: 400, responseBody: { message: 'bad' } });
257
+ });
258
+ describe('flexplmConnect.allowNonJsonResponse', () => {
259
+ const connectWith = (allowNonJsonResponse) => new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser, flexplmConnect: { allowNonJsonResponse } }));
260
+ const postReturns = (status, body) => fetchMock()
261
+ .mockResolvedValueOnce(resp(200))
262
+ .mockResolvedValueOnce(postResp(status, jest.fn().mockResolvedValue(body)));
263
+ it.each([true, 'true', 'TRUE'])('should return a non-JSON body as data.responseBody when set to %j', async (flag) => {
264
+ const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();
265
+ postReturns(200, 'OK - event accepted');
266
+ const result = await connectWith(flag).sendToFlexPLM(payload);
267
+ expect(result).toEqual({ status: 200, data: { responseBody: 'OK - event accepted' } });
268
+ expect(consoleWarnSpy).toHaveBeenCalled();
269
+ consoleWarnSpy.mockRestore();
270
+ });
271
+ it.each([false, 'false', undefined, 1])('should still fail on a non-JSON body when set to %j', async (flag) => {
272
+ postReturns(200, 'OK - event accepted');
273
+ await expect(connectWith(flag).sendToFlexPLM(payload))
274
+ .rejects.toThrow('Error getting json data from FlexPLM:status: 200');
275
+ });
276
+ it('should still parse a JSON body when enabled', async () => {
277
+ postReturns(200, '{"ok":true}');
278
+ const result = await connectWith(true).sendToFlexPLM(payload);
279
+ expect(result).toEqual({ status: 200, data: { ok: true } });
280
+ });
281
+ it('should still fail when reading the body throws, even when enabled', async () => {
282
+ fetchMock()
283
+ .mockResolvedValueOnce(resp(200))
284
+ .mockResolvedValueOnce(postResp(200, jest.fn().mockRejectedValue(new Error('stream aborted'))));
285
+ const promise = connectWith(true).sendToFlexPLM(payload);
286
+ await expect(promise).rejects.toThrow('Error getting json data from FlexPLM:status: 200: stream aborted');
287
+ await expect(promise).rejects.toHaveProperty('details', { httpResponseStatus: 200, responseBody: undefined });
288
+ });
289
+ it('should still fail on status >= 300 with a non-JSON body, even when enabled', async () => {
290
+ postReturns(500, 'Internal Server Error');
291
+ await expect(connectWith(true).sendToFlexPLM(payload))
292
+ .rejects.toThrow('Error sending data to FlexPLM:status: 500');
293
+ });
294
+ });
295
+ it.each([204, 205])('should not read the body for status %s', async (status) => {
296
+ const text = jest.fn();
297
+ fetchMock()
298
+ .mockResolvedValueOnce(resp(200))
299
+ .mockResolvedValueOnce(postResp(status, text));
300
+ const result = await new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: uniqueUser })).sendToFlexPLM(payload);
301
+ expect(result).toEqual({ status });
302
+ expect(text).not.toHaveBeenCalled();
303
+ });
304
+ });
141
305
  // Added for Session reuse - ET-390 - Starts
142
306
  describe('FlexPLMConnect session reuse', () => {
143
307
  const payload = { id: '123' };
@@ -43,13 +43,12 @@ export declare class ThumbnailUtil {
43
43
  * @param entityName - The entity type name (e.g. 'item', 'color') used for API calls.
44
44
  * @returns The updated entity, or undefined if no thumbnail changes were needed.
45
45
  */
46
- syncThumbnailToVibeIQ(params: {
46
+ syncThumbnailToVibeIQ({ entityId, primaryViewableId, event, entityName }: {
47
47
  entityId: string;
48
48
  primaryViewableId?: string;
49
49
  event: any;
50
50
  entityName: string;
51
51
  }): Promise<any>;
52
- private syncThumbnail;
53
52
  private createContentFromFlexPLM;
54
53
  private getPrimaryViewableUpdates;
55
54
  private getClearPrimaryViewableUpdates;