@worknice/js-sdk 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/dist/{_types-BXw9D0Qi.d.ts → _types-kBsjg67t.d.ts} +57 -2
  2. package/dist/api/ApiError.d.ts +2 -1
  3. package/dist/api/ApiError.js +7 -5
  4. package/dist/api/ApiError.js.map +1 -1
  5. package/dist/api/WorkniceIntegrationLogger.d.ts +41 -17
  6. package/dist/api/WorkniceIntegrationLogger.js +58 -28
  7. package/dist/api/WorkniceIntegrationLogger.js.map +1 -1
  8. package/dist/api/_generated.d.ts +183 -68
  9. package/dist/api/_generated.js +2 -0
  10. package/dist/api/_generated.js.map +1 -1
  11. package/dist/api/_types.d.ts +2 -2
  12. package/dist/api/createApiOperation.d.ts +1 -1
  13. package/dist/api/createWorkniceClient.d.ts +1 -1
  14. package/dist/api/createWorkniceClient.js +2 -0
  15. package/dist/api/createWorkniceClient.js.map +1 -1
  16. package/dist/api/operations/activateIntegration.d.ts +1 -1
  17. package/dist/api/operations/authorizeIntegration.d.ts +1 -1
  18. package/dist/api/operations/completeSync.d.ts +1 -1
  19. package/dist/api/operations/createApiToken.d.ts +1 -1
  20. package/dist/api/operations/createDataImport.d.ts +1 -1
  21. package/dist/api/operations/createPersonConnection.d.ts +8 -1
  22. package/dist/api/operations/createPersonConnection.js +1 -0
  23. package/dist/api/operations/createPersonConnection.js.map +1 -1
  24. package/dist/api/operations/createPersonDataImportLine.d.ts +7 -3
  25. package/dist/api/operations/createPersonDataImportLine.js +10 -2
  26. package/dist/api/operations/createPersonDataImportLine.js.map +1 -1
  27. package/dist/api/operations/deleteApiToken.d.ts +1 -1
  28. package/dist/api/operations/deletePersonConnection.d.ts +1 -1
  29. package/dist/api/operations/getApiTokens.d.ts +1 -1
  30. package/dist/api/operations/getApiTokens.js +7 -1
  31. package/dist/api/operations/getApiTokens.js.map +1 -1
  32. package/dist/api/operations/getIntegration.d.ts +1 -1
  33. package/dist/api/operations/getMyApps.d.ts +37 -0
  34. package/dist/api/operations/getMyApps.js +62 -0
  35. package/dist/api/operations/getMyApps.js.map +1 -0
  36. package/dist/api/operations/getPeople.d.ts +1 -1
  37. package/dist/api/operations/getPersonConnections.d.ts +8 -1
  38. package/dist/api/operations/getPersonConnections.js +1 -0
  39. package/dist/api/operations/getPersonConnections.js.map +1 -1
  40. package/dist/api/operations/initializeIntegration.d.ts +1 -1
  41. package/dist/api/operations/updatePersonConnection.d.ts +8 -1
  42. package/dist/api/operations/updatePersonConnection.js +1 -0
  43. package/dist/api/operations/updatePersonConnection.js.map +1 -1
  44. package/dist/employee-records/EQUALITY_CHECKS.js +23 -11
  45. package/dist/employee-records/EQUALITY_CHECKS.js.map +1 -1
  46. package/dist/employee-records/_types.d.ts +169 -149
  47. package/dist/employee-records/comparePersonDataTransferLines.js +61 -13
  48. package/dist/employee-records/comparePersonDataTransferLines.js.map +1 -1
  49. package/dist/employee-records/index.d.ts +9 -6
  50. package/dist/employee-records/index.js +22 -14
  51. package/dist/employee-records/index.js.map +1 -1
  52. package/dist/employee-records/mergePersonDataTransferLines.js +5 -9
  53. package/dist/employee-records/mergePersonDataTransferLines.js.map +1 -1
  54. package/dist/employee-records/validatePersonDataTransferLine.js +10 -2
  55. package/dist/employee-records/validatePersonDataTransferLine.js.map +1 -1
  56. package/dist/employee-records/validatePersonDataTransferLineDateOfBirth.d.ts +6 -0
  57. package/dist/employee-records/validatePersonDataTransferLineDateOfBirth.js +17 -0
  58. package/dist/employee-records/validatePersonDataTransferLineDateOfBirth.js.map +1 -0
  59. package/dist/employee-records/validatePersonDataTransferLineFullName.d.ts +6 -0
  60. package/dist/employee-records/validatePersonDataTransferLineFullName.js +20 -0
  61. package/dist/employee-records/validatePersonDataTransferLineFullName.js.map +1 -0
  62. package/dist/employee-records/validatePersonDataTransferLineGender.d.ts +6 -0
  63. package/dist/employee-records/validatePersonDataTransferLineGender.js +13 -0
  64. package/dist/employee-records/validatePersonDataTransferLineGender.js.map +1 -0
  65. package/dist/employee-records/validatePersonDataTransferLinePersonalEmail.d.ts +6 -0
  66. package/dist/employee-records/validatePersonDataTransferLinePersonalEmail.js +15 -0
  67. package/dist/employee-records/validatePersonDataTransferLinePersonalEmail.js.map +1 -0
  68. package/dist/employee-records/validatePersonDataTransferLinePersonalPhone.d.ts +6 -0
  69. package/dist/employee-records/validatePersonDataTransferLinePersonalPhone.js +15 -0
  70. package/dist/employee-records/validatePersonDataTransferLinePersonalPhone.js.map +1 -0
  71. package/dist/employee-records/validatePersonDataTransferLineTenure.js +1 -1
  72. package/dist/employee-records/validatePersonDataTransferLineTenure.js.map +1 -1
  73. package/dist/helpers/_types.d.ts +7 -3
  74. package/dist/helpers/handleApproveLeaveRequestWebhook.d.ts +15 -0
  75. package/dist/helpers/handleApproveLeaveRequestWebhook.js +21 -0
  76. package/dist/helpers/handleApproveLeaveRequestWebhook.js.map +1 -0
  77. package/dist/helpers/handleCancelLeaveRequestWebhook.d.ts +15 -0
  78. package/dist/helpers/handleCancelLeaveRequestWebhook.js +21 -0
  79. package/dist/helpers/handleCancelLeaveRequestWebhook.js.map +1 -0
  80. package/dist/helpers/handleCreateIntegrationWebhook.d.ts +6 -4
  81. package/dist/helpers/handleCreateIntegrationWebhook.js +24 -4
  82. package/dist/helpers/handleCreateIntegrationWebhook.js.map +1 -1
  83. package/dist/helpers/handleCreateLeaveRequestWebhook.d.ts +15 -0
  84. package/dist/helpers/handleCreateLeaveRequestWebhook.js +21 -0
  85. package/dist/helpers/handleCreateLeaveRequestWebhook.js.map +1 -0
  86. package/dist/helpers/handleDenyLeaveRequestWebhook.d.ts +15 -0
  87. package/dist/helpers/handleDenyLeaveRequestWebhook.js +21 -0
  88. package/dist/helpers/handleDenyLeaveRequestWebhook.js.map +1 -0
  89. package/dist/helpers/handleGetAuthorizationUrlWebhook.d.ts +4 -4
  90. package/dist/helpers/handleGetAuthorizationUrlWebhook.js +7 -2
  91. package/dist/helpers/handleGetAuthorizationUrlWebhook.js.map +1 -1
  92. package/dist/helpers/handleGetLeaveBalancesWebhook.d.ts +6 -7
  93. package/dist/helpers/handleGetLeaveBalancesWebhook.js +7 -2
  94. package/dist/helpers/handleGetLeaveBalancesWebhook.js.map +1 -1
  95. package/dist/helpers/handleGetLeaveCategoriesWebhook.d.ts +15 -0
  96. package/dist/helpers/handleGetLeaveCategoriesWebhook.js +27 -0
  97. package/dist/helpers/handleGetLeaveCategoriesWebhook.js.map +1 -0
  98. package/dist/helpers/handleGetLeaveRequestHoursWebhook.d.ts +13 -0
  99. package/dist/helpers/handleGetLeaveRequestHoursWebhook.js +27 -0
  100. package/dist/helpers/handleGetLeaveRequestHoursWebhook.js.map +1 -0
  101. package/dist/helpers/handleProcessLeaveRequestWebhook.d.ts +15 -0
  102. package/dist/helpers/handleProcessLeaveRequestWebhook.js +21 -0
  103. package/dist/helpers/handleProcessLeaveRequestWebhook.js.map +1 -0
  104. package/dist/helpers/handleRequest.d.ts +12 -0
  105. package/dist/helpers/handleRequest.js +58 -0
  106. package/dist/helpers/handleRequest.js.map +1 -0
  107. package/dist/helpers/handleRequestWithWorknice.d.ts +17 -8
  108. package/dist/helpers/handleRequestWithWorknice.js +35 -58
  109. package/dist/helpers/handleRequestWithWorknice.js.map +1 -1
  110. package/dist/helpers/handleTriggerIntegrationSyncWebhook.d.ts +15 -11
  111. package/dist/helpers/handleTriggerIntegrationSyncWebhook.js +214 -139
  112. package/dist/helpers/handleTriggerIntegrationSyncWebhook.js.map +1 -1
  113. package/dist/helpers/index.d.ts +9 -1
  114. package/dist/helpers/index.js +26 -10
  115. package/dist/helpers/index.js.map +1 -1
  116. package/dist/index.d.ts +9 -6
  117. package/dist/index.js +6 -8
  118. package/dist/index.js.map +1 -1
  119. package/dist/utils/errorToString.js +4 -0
  120. package/dist/utils/errorToString.js.map +1 -1
  121. package/dist/utils/isSamePlainDate.d.ts +3 -1
  122. package/dist/utils/isSamePlainDate.js +1 -1
  123. package/dist/utils/isSamePlainDate.js.map +1 -1
  124. package/dist/utils/isValidPlainDate.d.ts +1 -1
  125. package/dist/utils/isValidPlainDate.js +1 -1
  126. package/dist/utils/isValidPlainDate.js.map +1 -1
  127. package/dist/utils/parsePlainDate.d.ts +1 -1
  128. package/dist/utils/parsePlainDate.js +1 -1
  129. package/dist/utils/parsePlainDate.js.map +1 -1
  130. package/dist/webhooks.d.ts +71 -1
  131. package/package.json +8 -5
  132. package/dist/employee-records/validatePersonDataTransferLinePersonalDetails.d.ts +0 -6
  133. package/dist/employee-records/validatePersonDataTransferLinePersonalDetails.js +0 -38
  134. package/dist/employee-records/validatePersonDataTransferLinePersonalDetails.js.map +0 -1
  135. package/dist/utils/isAfter.d.ts +0 -4
  136. package/dist/utils/isAfter.js +0 -5
  137. package/dist/utils/isAfter.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { Exact, Scalars, InputMaybe, ConnectionStatus, PersonBankAccountsChangeInput, PersonDataTransferConfigInput, PersonEmergencyContactsChangeInput, PersonPersonalDetailsChangeInput, PersonPostalAddressChangeInput, PersonResidentialAddressChangeInput, PersonSuperFundsChangeInput, PersonTaxDetailsChangeInput, PersonTenureChangeInput, IntegrationStatus, AppCategory, AllocationMethod, Gender, TaxResidencyStatus, SuperFundNomination, TaxFileNumberExemption } from './api/_generated.js';
1
+ import { Exact, Scalars, InputMaybe, ConnectionStatus, PersonBankAccountsChangeInput, PersonDataTransferConfigInput, PersonDateOfBirthChangeInput, PersonEmergencyContactsChangeInput, PersonFullNameChangeInput, PersonGenderChangeInput, PersonPersonalEmailChangeInput, PersonPersonalPhoneChangeInput, PersonPostalAddressChangeInput, PersonResidentialAddressChangeInput, PersonSuperFundsChangeInput, PersonTaxDetailsChangeInput, PersonTenureChangeInput, AppCategory, AppStatus, IntegrationStatus, AllocationMethod, Gender, TaxResidencyStatus, SuperFundNomination, TaxFileNumberExemption } from './api/_generated.js';
2
2
 
3
3
  declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
4
4
  fetchFromApi: <Data extends object, Variables extends object>(query: string, variables?: Variables, fetchOptions?: FetchOptions) => Promise<SuccessfulQueryResult<Data>>;
@@ -99,6 +99,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
99
99
  person?: {
100
100
  displayName: string;
101
101
  id: string;
102
+ updatedAt: string;
102
103
  } | null;
103
104
  remote?: {
104
105
  name: string;
@@ -115,6 +116,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
115
116
  person: {
116
117
  displayName: string;
117
118
  id: string;
119
+ updatedAt: string;
118
120
  };
119
121
  }) | ({
120
122
  __typename: "PersonConnection";
@@ -125,6 +127,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
125
127
  person?: {
126
128
  displayName: string;
127
129
  id: string;
130
+ updatedAt: string;
128
131
  } | null;
129
132
  remote?: {
130
133
  name: string;
@@ -141,6 +144,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
141
144
  person: {
142
145
  displayName: string;
143
146
  id: string;
147
+ updatedAt: string;
144
148
  };
145
149
  }) | ({
146
150
  __typename: "PersonConnection";
@@ -151,6 +155,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
151
155
  person?: {
152
156
  displayName: string;
153
157
  id: string;
158
+ updatedAt: string;
154
159
  } | null;
155
160
  remote?: {
156
161
  name: string;
@@ -162,6 +167,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
162
167
  person: {
163
168
  displayName: string;
164
169
  id: string;
170
+ updatedAt: string;
165
171
  };
166
172
  remote: null;
167
173
  }) | ({
@@ -173,6 +179,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
173
179
  person?: {
174
180
  displayName: string;
175
181
  id: string;
182
+ updatedAt: string;
176
183
  } | null;
177
184
  remote?: {
178
185
  name: string;
@@ -192,8 +199,12 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
192
199
  bankAccounts?: InputMaybe<PersonBankAccountsChangeInput>;
193
200
  config: PersonDataTransferConfigInput;
194
201
  dataImportId: Scalars["ID"]["input"];
202
+ dateOfBirth?: InputMaybe<PersonDateOfBirthChangeInput>;
195
203
  emergencyContacts?: InputMaybe<PersonEmergencyContactsChangeInput>;
196
- personalDetails?: InputMaybe<PersonPersonalDetailsChangeInput>;
204
+ fullName?: InputMaybe<PersonFullNameChangeInput>;
205
+ gender?: InputMaybe<PersonGenderChangeInput>;
206
+ personalEmail?: InputMaybe<PersonPersonalEmailChangeInput>;
207
+ personalPhone?: InputMaybe<PersonPersonalPhoneChangeInput>;
197
208
  personId: Scalars["ID"]["input"];
198
209
  postalAddress?: InputMaybe<PersonPostalAddressChangeInput>;
199
210
  residentialAddress?: InputMaybe<PersonResidentialAddressChangeInput>;
@@ -243,6 +254,36 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
243
254
  id: string;
244
255
  name: string;
245
256
  }[]>;
257
+ getMyApps: (variables: Exact<{
258
+ [key: string]: never;
259
+ }>, fetchOptions?: FetchOptions) => Promise<{
260
+ category: AppCategory;
261
+ description?: string | null;
262
+ id: string;
263
+ name: string;
264
+ status: AppStatus;
265
+ logo?: {
266
+ url: string;
267
+ } | null;
268
+ config: {
269
+ webhooks: {
270
+ approveLeaveRequest?: string | null;
271
+ cancelLeaveRequest?: string | null;
272
+ createIntegration?: string | null;
273
+ createLeaveRequest?: string | null;
274
+ denyLeaveRequest?: string | null;
275
+ getAuthorizationUrl?: string | null;
276
+ getConfigurationUrl?: string | null;
277
+ getLeaveBalances?: string | null;
278
+ getLeaveCategories?: string | null;
279
+ getLeaveRequestHours?: string | null;
280
+ getReconfigurationUrl?: string | null;
281
+ personConnected?: string | null;
282
+ processLeaveRequest?: string | null;
283
+ triggerIntegrationSync?: string | null;
284
+ };
285
+ };
286
+ }[]>;
246
287
  getIntegration: (variables: Exact<{
247
288
  integrationId: Scalars["ID"]["input"];
248
289
  }>, fetchOptions?: FetchOptions) => Promise<{
@@ -370,6 +411,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
370
411
  person?: {
371
412
  displayName: string;
372
413
  id: string;
414
+ updatedAt: string;
373
415
  } | null;
374
416
  remote?: {
375
417
  name: string;
@@ -386,6 +428,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
386
428
  person: {
387
429
  displayName: string;
388
430
  id: string;
431
+ updatedAt: string;
389
432
  };
390
433
  }) | ({
391
434
  __typename: "PersonConnection";
@@ -396,6 +439,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
396
439
  person?: {
397
440
  displayName: string;
398
441
  id: string;
442
+ updatedAt: string;
399
443
  } | null;
400
444
  remote?: {
401
445
  name: string;
@@ -412,6 +456,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
412
456
  person: {
413
457
  displayName: string;
414
458
  id: string;
459
+ updatedAt: string;
415
460
  };
416
461
  }) | ({
417
462
  __typename: "PersonConnection";
@@ -422,6 +467,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
422
467
  person?: {
423
468
  displayName: string;
424
469
  id: string;
470
+ updatedAt: string;
425
471
  } | null;
426
472
  remote?: {
427
473
  name: string;
@@ -433,6 +479,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
433
479
  person: {
434
480
  displayName: string;
435
481
  id: string;
482
+ updatedAt: string;
436
483
  };
437
484
  remote: null;
438
485
  }) | ({
@@ -444,6 +491,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
444
491
  person?: {
445
492
  displayName: string;
446
493
  id: string;
494
+ updatedAt: string;
447
495
  } | null;
448
496
  remote?: {
449
497
  name: string;
@@ -495,6 +543,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
495
543
  person?: {
496
544
  displayName: string;
497
545
  id: string;
546
+ updatedAt: string;
498
547
  } | null;
499
548
  remote?: {
500
549
  name: string;
@@ -511,6 +560,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
511
560
  person: {
512
561
  displayName: string;
513
562
  id: string;
563
+ updatedAt: string;
514
564
  };
515
565
  }) | ({
516
566
  __typename: "PersonConnection";
@@ -521,6 +571,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
521
571
  person?: {
522
572
  displayName: string;
523
573
  id: string;
574
+ updatedAt: string;
524
575
  } | null;
525
576
  remote?: {
526
577
  name: string;
@@ -537,6 +588,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
537
588
  person: {
538
589
  displayName: string;
539
590
  id: string;
591
+ updatedAt: string;
540
592
  };
541
593
  }) | ({
542
594
  __typename: "PersonConnection";
@@ -547,6 +599,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
547
599
  person?: {
548
600
  displayName: string;
549
601
  id: string;
602
+ updatedAt: string;
550
603
  } | null;
551
604
  remote?: {
552
605
  name: string;
@@ -558,6 +611,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
558
611
  person: {
559
612
  displayName: string;
560
613
  id: string;
614
+ updatedAt: string;
561
615
  };
562
616
  remote: null;
563
617
  }) | ({
@@ -569,6 +623,7 @@ declare const createWorkniceClient: (clientConfig?: ClientConfig) => {
569
623
  person?: {
570
624
  displayName: string;
571
625
  id: string;
626
+ updatedAt: string;
572
627
  } | null;
573
628
  remote?: {
574
629
  name: string;
@@ -4,8 +4,9 @@ declare class ApiError extends Error {
4
4
  }
5
5
  declare enum ApiErrorCode {
6
6
  INVALID_QUERY = "INVALID_QUERY",
7
- NO_PERSON = "NO_PERSON",
8
7
  QUERY_EXECUTION_FAILED = "QUERY_EXECUTION_FAILED",
8
+ SESSION_UNASSOCIATED = "SESSION_UNASSOCIATED",
9
+ SESSION_UNAUTHENTICATED = "SESSION_UNAUTHENTICATED",
9
10
  UNEXPECTED_RESPONSE = "UNEXPECTED_RESPONSE"
10
11
  }
11
12
 
@@ -8,16 +8,18 @@ class ApiError extends Error {
8
8
  }
9
9
  var ApiErrorCode = /* @__PURE__ */ ((ApiErrorCode2) => {
10
10
  ApiErrorCode2["INVALID_QUERY"] = "INVALID_QUERY";
11
- ApiErrorCode2["NO_PERSON"] = "NO_PERSON";
12
11
  ApiErrorCode2["QUERY_EXECUTION_FAILED"] = "QUERY_EXECUTION_FAILED";
12
+ ApiErrorCode2["SESSION_UNASSOCIATED"] = "SESSION_UNASSOCIATED";
13
+ ApiErrorCode2["SESSION_UNAUTHENTICATED"] = "SESSION_UNAUTHENTICATED";
13
14
  ApiErrorCode2["UNEXPECTED_RESPONSE"] = "UNEXPECTED_RESPONSE";
14
15
  return ApiErrorCode2;
15
16
  })(ApiErrorCode || {});
16
17
  const ApiErrorCodeMessage = {
17
- ["INVALID_QUERY" /* INVALID_QUERY */]: "The GraphQL query could not be executed due to a syntax error, missing information or a validation error.",
18
- ["NO_PERSON" /* NO_PERSON */]: "No person associated with the session. The session is either in an 'unauthenticated' state (the API token is missing or invalid) or an 'unassociated' state (the user has no active logins).",
19
- ["QUERY_EXECUTION_FAILED" /* QUERY_EXECUTION_FAILED */]: "An error occurred while executing the GraphQL query. This is likely a problem with the Worknice API.",
20
- ["UNEXPECTED_RESPONSE" /* UNEXPECTED_RESPONSE */]: "The API returned an unexpected response. This is likely a problem with the Worknice API or a mismatch between JS-SDK and the API. Make sure you are using the latest version of the JS-SDK."
18
+ ["INVALID_QUERY" /* INVALID_QUERY */]: "The Worknice API was unable to execute the query. This could be due to a syntax error or invalid query.",
19
+ ["QUERY_EXECUTION_FAILED" /* QUERY_EXECUTION_FAILED */]: "The Worknice API returned an error while executing the query.",
20
+ ["SESSION_UNAUTHENTICATED" /* SESSION_UNAUTHENTICATED */]: "API token is missing or invalid.",
21
+ ["SESSION_UNASSOCIATED" /* SESSION_UNASSOCIATED */]: "No person, org or account associated with the session. The session is in 'unassociated' state (the user has no active logins).",
22
+ ["UNEXPECTED_RESPONSE" /* UNEXPECTED_RESPONSE */]: "The API returned an unexpected response. This could be a configuration problem (wrong URL for the API endpoint) or an outdated/mismatched JS-SDK version."
21
23
  };
22
24
  var ApiError_default = ApiError;
23
25
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/ApiError.ts"],"sourcesContent":["class ApiError extends Error {\n readonly code: ApiErrorCode;\n constructor(code: ApiErrorCode, options?: ErrorOptions) {\n super(ApiErrorCodeMessage[code], options);\n this.name = \"ApiError\";\n this.code = code;\n }\n}\n\nenum ApiErrorCode {\n INVALID_QUERY = \"INVALID_QUERY\",\n NO_PERSON = \"NO_PERSON\",\n QUERY_EXECUTION_FAILED = \"QUERY_EXECUTION_FAILED\",\n UNEXPECTED_RESPONSE = \"UNEXPECTED_RESPONSE\",\n}\n\nconst ApiErrorCodeMessage: Record<ApiErrorCode, string> = {\n [ApiErrorCode.INVALID_QUERY]:\n \"The GraphQL query could not be executed due to a syntax error, missing information or a validation error.\",\n [ApiErrorCode.NO_PERSON]:\n \"No person associated with the session. The session is either in an 'unauthenticated' state (the API token is missing or invalid) or an 'unassociated' state (the user has no active logins).\",\n [ApiErrorCode.QUERY_EXECUTION_FAILED]:\n \"An error occurred while executing the GraphQL query. This is likely a problem with the Worknice API.\",\n [ApiErrorCode.UNEXPECTED_RESPONSE]:\n \"The API returned an unexpected response. This is likely a problem with the Worknice API or a mismatch between JS-SDK and the API. Make sure you are using the latest version of the JS-SDK.\",\n} as const;\n\nexport default ApiError;\nexport { ApiErrorCode };\n"],"mappings":"AAAA,MAAM,iBAAiB,MAAM;AAAA,EAClB;AAAA,EACT,YAAY,MAAoB,SAAwB;AACtD,UAAM,oBAAoB,IAAI,GAAG,OAAO;AACxC,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAK,eAAL,kBAAKA,kBAAL;AACE,EAAAA,cAAA,mBAAgB;AAChB,EAAAA,cAAA,eAAY;AACZ,EAAAA,cAAA,4BAAyB;AACzB,EAAAA,cAAA,yBAAsB;AAJnB,SAAAA;AAAA,GAAA;AAOL,MAAM,sBAAoD;AAAA,EACxD,CAAC,mCAA0B,GACzB;AAAA,EACF,CAAC,2BAAsB,GACrB;AAAA,EACF,CAAC,qDAAmC,GAClC;AAAA,EACF,CAAC,+CAAgC,GAC/B;AACJ;AAEA,IAAO,mBAAQ;","names":["ApiErrorCode"]}
1
+ {"version":3,"sources":["../../src/api/ApiError.ts"],"sourcesContent":["class ApiError extends Error {\n readonly code: ApiErrorCode;\n constructor(code: ApiErrorCode, options?: ErrorOptions) {\n super(ApiErrorCodeMessage[code], options);\n this.name = \"ApiError\";\n this.code = code;\n }\n}\n\nenum ApiErrorCode {\n INVALID_QUERY = \"INVALID_QUERY\",\n QUERY_EXECUTION_FAILED = \"QUERY_EXECUTION_FAILED\",\n SESSION_UNASSOCIATED = \"SESSION_UNASSOCIATED\",\n SESSION_UNAUTHENTICATED = \"SESSION_UNAUTHENTICATED\",\n UNEXPECTED_RESPONSE = \"UNEXPECTED_RESPONSE\",\n}\n\nconst ApiErrorCodeMessage: Record<ApiErrorCode, string> = {\n [ApiErrorCode.INVALID_QUERY]:\n \"The Worknice API was unable to execute the query. This could be due to a syntax error or invalid query.\",\n [ApiErrorCode.QUERY_EXECUTION_FAILED]:\n \"The Worknice API returned an error while executing the query.\",\n [ApiErrorCode.SESSION_UNAUTHENTICATED]: \"API token is missing or invalid.\",\n [ApiErrorCode.SESSION_UNASSOCIATED]:\n \"No person, org or account associated with the session. The session is in 'unassociated' state (the user has no active logins).\",\n [ApiErrorCode.UNEXPECTED_RESPONSE]:\n \"The API returned an unexpected response. This could be a configuration problem (wrong URL for the API endpoint) or an outdated/mismatched JS-SDK version.\",\n} as const;\n\nexport default ApiError;\nexport { ApiErrorCode };\n"],"mappings":"AAAA,MAAM,iBAAiB,MAAM;AAAA,EAClB;AAAA,EACT,YAAY,MAAoB,SAAwB;AACtD,UAAM,oBAAoB,IAAI,GAAG,OAAO;AACxC,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAK,eAAL,kBAAKA,kBAAL;AACE,EAAAA,cAAA,mBAAgB;AAChB,EAAAA,cAAA,4BAAyB;AACzB,EAAAA,cAAA,0BAAuB;AACvB,EAAAA,cAAA,6BAA0B;AAC1B,EAAAA,cAAA,yBAAsB;AALnB,SAAAA;AAAA,GAAA;AAQL,MAAM,sBAAoD;AAAA,EACxD,CAAC,mCAA0B,GACzB;AAAA,EACF,CAAC,qDAAmC,GAClC;AAAA,EACF,CAAC,uDAAoC,GAAG;AAAA,EACxC,CAAC,iDAAiC,GAChC;AAAA,EACF,CAAC,+CAAgC,GAC/B;AACJ;AAEA,IAAO,mBAAQ;","names":["ApiErrorCode"]}
@@ -1,7 +1,26 @@
1
- import { W as WorkniceClient } from '../_types-BXw9D0Qi.js';
1
+ import { W as WorkniceClient } from '../_types-kBsjg67t.js';
2
2
  import './_generated.js';
3
3
 
4
4
  type Logger = Pick<Console, "debug" | "error" | "info" | "warn"> & Partial<Pick<Console, "group" | "groupEnd">>;
5
+ type WorkniceIntegrationLoggerOptions = {
6
+ /**
7
+ * The type of log to use for debug messages. If set to "debug", debug
8
+ * messages will be logged using the logger.debug() method, but if set to
9
+ * "info", debug messages will be logged using the logger.info() method.
10
+ *
11
+ * Irrespective of this option, debug messages are only logged to the
12
+ * configured logger and are never sent to the Worknice integration logs.
13
+ */
14
+ debugLogType: "debug" | "info";
15
+ /**
16
+ * The delay between flushes in milliseconds. Defaults to 1000 (1 second).
17
+ */
18
+ delayBetweenFlushes: number;
19
+ /**
20
+ * A Console-like object with which messages will be logger.
21
+ */
22
+ logger: Logger;
23
+ };
5
24
  declare class WorkniceIntegrationLogger {
6
25
  /**
7
26
  * The Worknice client used to send the logs to the server. If null, the logs
@@ -35,10 +54,6 @@ declare class WorkniceIntegrationLogger {
35
54
  * created. Subsequent flushes will append to the existing log.
36
55
  */
37
56
  private logCreated;
38
- /**
39
- * A Console-like object with which messages will be logger.
40
- */
41
- private logger;
42
57
  /**
43
58
  * Backlog of log messages that have not yet been sent to Worknice. The logs
44
59
  * will be sent to the server when the logger is flushed and the backlog will
@@ -51,19 +66,21 @@ declare class WorkniceIntegrationLogger {
51
66
  * level.
52
67
  */
53
68
  private messageIndent;
69
+ private options;
70
+ private timeout;
54
71
  /**
55
72
  * A logger can log messages to both a Console-like object and to a Worknice
56
73
  * integration's logs which can be view by a Worknice user. By default,
57
- * messages are only logged to the console, but when a Worknice integration is
58
- * connected using the connect() method, the messages will also be logged to
59
- * Worknice.
74
+ * messages are only logged to the configured logger, but when a Worknice
75
+ * integration is connected using the connect() method, the messages will also
76
+ * be sent to the Worknice integration logs.
60
77
  * @param logger A Console-like object with which messages can be logged.
61
78
  * @example
62
79
  * ```js
63
- * const logger = new WorkniceIntegrationLogger(console);
80
+ * const logger = new WorkniceIntegrationLogger({ logger: console });
64
81
  * ```
65
82
  */
66
- constructor(logger?: Logger);
83
+ constructor(options?: Partial<WorkniceIntegrationLoggerOptions>);
67
84
  /**
68
85
  * Connects the logger to a Worknice integration. If there are previously
69
86
  * logged messages that need to be flushed, a new integration log will be
@@ -72,13 +89,20 @@ declare class WorkniceIntegrationLogger {
72
89
  */
73
90
  connect(client: WorkniceClient, integrationId: string): void;
74
91
  /**
75
- * Logs a debug message. Debug messages are only logged to the console and are
76
- * never append to the Worknice integration logs.
92
+ * Logs a debug message. Debug messages are only logged to the configured logger
93
+ * and are never sent to the Worknice integration logs.
77
94
  */
78
95
  debug(message: string): void;
79
96
  dedent(message?: string): void;
80
97
  private enqueue;
81
- error(message: string): void;
98
+ /**
99
+ * Logs an error of any type. The error will be logged to the configured logger
100
+ * with full stack traces and a chain of error causes. A simplified error
101
+ * message will sent to the Worknice integration logs (if connected) and
102
+ * returned for displaying to the user. If the error is not an instance of
103
+ * Error, it will be coerced into a string before being logged.
104
+ */
105
+ error(error: unknown): string;
82
106
  /**
83
107
  * Flushes the log buffer to the server. The info() function will
84
108
  * automatically flush the logs if the last flush was more than 1 second
@@ -88,12 +112,12 @@ declare class WorkniceIntegrationLogger {
88
112
  flush(): Promise<void>;
89
113
  indent(message?: string): void;
90
114
  /**
91
- * Logs an informational message. The message will be appended to the log
92
- * buffer and flushed to the server if the last flush was more than 1 second
93
- * ago.
115
+ * Logs an informational message. The message will be logged to the configured
116
+ * logger and flushed to the Worknice integration logs if/when connected.
94
117
  */
95
118
  info(message: string): void;
119
+ private timeSinceLastFlush;
96
120
  warn(message: string): void;
97
121
  }
98
122
 
99
- export { type Logger, WorkniceIntegrationLogger as default };
123
+ export { type Logger, type WorkniceIntegrationLoggerOptions, WorkniceIntegrationLogger as default };
@@ -1,6 +1,7 @@
1
1
  import gql from "dedent";
2
2
  import { Temporal } from "temporal-polyfill";
3
3
  import { v4 as uuid } from "uuid";
4
+ import errorToString from "../utils/errorToString.js";
4
5
  class WorkniceIntegrationLogger {
5
6
  /**
6
7
  * The Worknice client used to send the logs to the server. If null, the logs
@@ -34,10 +35,6 @@ class WorkniceIntegrationLogger {
34
35
  * created. Subsequent flushes will append to the existing log.
35
36
  */
36
37
  logCreated = false;
37
- /**
38
- * A Console-like object with which messages will be logger.
39
- */
40
- logger;
41
38
  /**
42
39
  * Backlog of log messages that have not yet been sent to Worknice. The logs
43
40
  * will be sent to the server when the logger is flushed and the backlog will
@@ -50,21 +47,27 @@ class WorkniceIntegrationLogger {
50
47
  * level.
51
48
  */
52
49
  messageIndent = 0;
50
+ options;
51
+ timeout = null;
53
52
  /**
54
53
  * A logger can log messages to both a Console-like object and to a Worknice
55
54
  * integration's logs which can be view by a Worknice user. By default,
56
- * messages are only logged to the console, but when a Worknice integration is
57
- * connected using the connect() method, the messages will also be logged to
58
- * Worknice.
55
+ * messages are only logged to the configured logger, but when a Worknice
56
+ * integration is connected using the connect() method, the messages will also
57
+ * be sent to the Worknice integration logs.
59
58
  * @param logger A Console-like object with which messages can be logged.
60
59
  * @example
61
60
  * ```js
62
- * const logger = new WorkniceIntegrationLogger(console);
61
+ * const logger = new WorkniceIntegrationLogger({ logger: console });
63
62
  * ```
64
63
  */
65
- constructor(logger) {
66
- this.logger = logger ?? console;
64
+ constructor(options) {
67
65
  this.integrationLogId = uuid();
66
+ this.options = {
67
+ debugLogType: options?.debugLogType ?? "debug",
68
+ delayBetweenFlushes: options?.delayBetweenFlushes ?? 1e3,
69
+ logger: options?.logger ?? console
70
+ };
68
71
  }
69
72
  /**
70
73
  * Connects the logger to a Worknice integration. If there are previously
@@ -75,20 +78,19 @@ class WorkniceIntegrationLogger {
75
78
  connect(client, integrationId) {
76
79
  this.client = client;
77
80
  this.integrationId = integrationId;
78
- if (this.lastFlush === null || Temporal.Now.instant().since(this.lastFlush).seconds >= 1) {
79
- this.flush();
80
- }
81
+ this.flush();
81
82
  }
82
83
  /**
83
- * Logs a debug message. Debug messages are only logged to the console and are
84
- * never append to the Worknice integration logs.
84
+ * Logs a debug message. Debug messages are only logged to the configured logger
85
+ * and are never sent to the Worknice integration logs.
85
86
  */
86
87
  debug(message) {
87
- this.logger.debug(message);
88
+ if (this.options.debugLogType === "debug") this.options.logger.debug(message);
89
+ else this.options.logger.info(message);
88
90
  }
89
91
  dedent(message) {
90
92
  if (message !== void 0) this.info(message);
91
- if (this.logger.groupEnd) this.logger.groupEnd();
93
+ if (this.options.logger.groupEnd) this.options.logger.groupEnd();
92
94
  this.messageIndent = Math.max(0, this.messageIndent - 1);
93
95
  }
94
96
  enqueue(message) {
@@ -96,13 +98,35 @@ class WorkniceIntegrationLogger {
96
98
  time: Temporal.Now.instant(),
97
99
  message: message.split("\n").map((line) => `${" ".repeat(this.messageIndent * 2)}${line}`).join("\n")
98
100
  });
99
- if (this.lastFlush === null || Temporal.Now.instant().since(this.lastFlush).seconds >= 1) {
101
+ if (this.timeSinceLastFlush() >= this.options.delayBetweenFlushes) {
100
102
  this.flush();
103
+ } else if (this.timeout === null) {
104
+ this.timeout = setTimeout(() => {
105
+ if (this.timeSinceLastFlush() >= this.options.delayBetweenFlushes) {
106
+ this.flush();
107
+ }
108
+ }, this.options.delayBetweenFlushes - this.timeSinceLastFlush());
101
109
  }
102
110
  }
103
- error(message) {
104
- this.logger.error(message);
105
- this.enqueue(message);
111
+ /**
112
+ * Logs an error of any type. The error will be logged to the configured logger
113
+ * with full stack traces and a chain of error causes. A simplified error
114
+ * message will sent to the Worknice integration logs (if connected) and
115
+ * returned for displaying to the user. If the error is not an instance of
116
+ * Error, it will be coerced into a string before being logged.
117
+ */
118
+ error(error) {
119
+ const verboseMessage = errorToString(error, {
120
+ format: "chain",
121
+ stack: true
122
+ });
123
+ const simpleMessage = errorToString(error, {
124
+ format: "simple",
125
+ stack: false
126
+ });
127
+ this.options.logger.error(verboseMessage);
128
+ this.enqueue(simpleMessage);
129
+ return simpleMessage;
106
130
  }
107
131
  /**
108
132
  * Flushes the log buffer to the server. The info() function will
@@ -111,9 +135,13 @@ class WorkniceIntegrationLogger {
111
135
  * script to ensure that all logs are sent to the server.
112
136
  */
113
137
  async flush() {
138
+ if (this.timeout) {
139
+ clearTimeout(this.timeout);
140
+ this.timeout = null;
141
+ }
142
+ this.lastFlush = Temporal.Now.instant();
114
143
  if (this.currentRequest) await this.currentRequest;
115
144
  if (this.logs.length === 0 || this.client === null || this.integrationId === null) return;
116
- this.lastFlush = Temporal.Now.instant();
117
145
  const entries = this.logs.splice(0).map(({ time, message }) => ({
118
146
  time: time.toString({ timeZone: "Australia/Sydney", smallestUnit: "second" }),
119
147
  message
@@ -149,20 +177,22 @@ class WorkniceIntegrationLogger {
149
177
  }
150
178
  indent(message) {
151
179
  if (message !== void 0) this.info(message);
152
- if (this.logger.group) this.logger.group();
180
+ if (this.options.logger.group) this.options.logger.group();
153
181
  this.messageIndent += 1;
154
182
  }
155
183
  /**
156
- * Logs an informational message. The message will be appended to the log
157
- * buffer and flushed to the server if the last flush was more than 1 second
158
- * ago.
184
+ * Logs an informational message. The message will be logged to the configured
185
+ * logger and flushed to the Worknice integration logs if/when connected.
159
186
  */
160
187
  info(message) {
161
- this.logger.info(message);
188
+ this.options.logger.info(message);
162
189
  this.enqueue(message);
163
190
  }
191
+ timeSinceLastFlush() {
192
+ return this.lastFlush === null ? Number.MAX_SAFE_INTEGER : Temporal.Now.instant().since(this.lastFlush).total("milliseconds");
193
+ }
164
194
  warn(message) {
165
- this.logger.warn(message);
195
+ this.options.logger.warn(message);
166
196
  this.enqueue(message);
167
197
  }
168
198
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/WorkniceIntegrationLogger.ts"],"sourcesContent":["import gql from \"dedent\";\nimport { Temporal } from \"temporal-polyfill\";\nimport { v4 as uuid } from \"uuid\";\nimport type { WorkniceClient } from \"./_types.js\";\n\nexport type Logger = Pick<Console, \"debug\" | \"error\" | \"info\" | \"warn\"> &\n Partial<Pick<Console, \"group\" | \"groupEnd\">>;\n\nclass WorkniceIntegrationLogger {\n /**\n * The Worknice client used to send the logs to the server. If null, the logs\n * will be buffered until the logger is initialized.\n */\n private client: WorkniceClient | null = null;\n\n /**\n * A promise used to ensure that only one request is in progress at a time. If\n * a flush is called while a request is in progress, the flush will wait for\n * the request to finish before starting a new one.\n */\n private currentRequest: Promise<unknown> | null = null;\n\n /**\n * The integration ID the logs will be associated with. If undefined, the\n * logs will be buffered until the logger has been initialized.\n */\n private integrationId: string | undefined = undefined;\n\n /**\n * The random ID for the integration log to which the logs will be appended.\n */\n private integrationLogId: string;\n\n /**\n * Determines when the logger should flush the logs. Calling info(), error(),\n * warn(), indent() or dedent() will automatically flush the logs if the last\n * flush was more than 1 second ago.\n */\n private lastFlush: Temporal.Instant | null = null;\n\n /**\n * A flag is used to determine whether a new log should be created when the\n * logger is flushed. The first time the logger is flushed, a new log will be\n * created. Subsequent flushes will append to the existing log.\n */\n private logCreated = false;\n\n /**\n * A Console-like object with which messages will be logger.\n */\n private logger: Logger;\n\n /**\n * Backlog of log messages that have not yet been sent to Worknice. The logs\n * will be sent to the server when the logger is flushed and the backlog will\n * be cleared.\n */\n private logs: Array<{ time: Temporal.Instant; message: string }> = [];\n\n /**\n * Determines the current indentation level of the log messages. The indent()\n * and dedent() functions can be used to increase or decrease the indentation\n * level.\n */\n private messageIndent = 0;\n\n /**\n * A logger can log messages to both a Console-like object and to a Worknice\n * integration's logs which can be view by a Worknice user. By default,\n * messages are only logged to the console, but when a Worknice integration is\n * connected using the connect() method, the messages will also be logged to\n * Worknice.\n * @param logger A Console-like object with which messages can be logged.\n * @example\n * ```js\n * const logger = new WorkniceIntegrationLogger(console);\n * ```\n */\n constructor(logger?: Logger) {\n this.logger = logger ?? console;\n this.integrationLogId = uuid();\n }\n\n /**\n * Connects the logger to a Worknice integration. If there are previously\n * logged messages that need to be flushed, a new integration log will be\n * instantly created and the messages flushed to it. Otherwise, an integration\n * log will be created if/when the first message is logged.\n */\n public connect(client: WorkniceClient, integrationId: string) {\n this.client = client;\n this.integrationId = integrationId;\n if (this.lastFlush === null || Temporal.Now.instant().since(this.lastFlush).seconds >= 1) {\n this.flush();\n }\n }\n\n /**\n * Logs a debug message. Debug messages are only logged to the console and are\n * never append to the Worknice integration logs.\n */\n public debug(message: string) {\n this.logger.debug(message);\n }\n\n public dedent(message?: string) {\n if (message !== undefined) this.info(message);\n if (this.logger.groupEnd) this.logger.groupEnd();\n this.messageIndent = Math.max(0, this.messageIndent - 1);\n }\n\n private enqueue(message: string) {\n this.logs.push({\n time: Temporal.Now.instant(),\n message: message\n .split(\"\\n\")\n .map((line) => `${\" \".repeat(this.messageIndent * 2)}${line}`)\n .join(\"\\n\"),\n });\n\n if (this.lastFlush === null || Temporal.Now.instant().since(this.lastFlush).seconds >= 1) {\n this.flush();\n }\n }\n\n public error(message: string) {\n this.logger.error(message);\n this.enqueue(message);\n }\n\n /**\n * Flushes the log buffer to the server. The info() function will\n * automatically flush the logs if the last flush was more than 1 second\n * ago, but the flush() function should be called manually at the end of the\n * script to ensure that all logs are sent to the server.\n */\n public async flush() {\n // If there's already a request in progress, wait for it to finish before\n // starting a new one.\n if (this.currentRequest) await this.currentRequest;\n\n // If there are no pending logs or the logger hasn't been initialized,\n // don't do anything (any logs will remain in the buffer until the next\n // flush).\n if (this.logs.length === 0 || this.client === null || this.integrationId === null) return;\n\n this.lastFlush = Temporal.Now.instant();\n\n const entries = this.logs.splice(0).map(({ time, message }) => ({\n time: time.toString({ timeZone: \"Australia/Sydney\", smallestUnit: \"second\" }),\n message,\n }));\n\n this.currentRequest = this.client.fetchFromApi(\n gql`\n mutation AppendIntegrationLog(\n $createNewLog: Boolean!\n $entries: [IntegrationLogInput!]!\n $integrationId: ID!\n $integrationLogId: ID!\n ) {\n createIntegrationLog(integrationId: $integrationId, integrationLogId: $integrationLogId)\n @include(if: $createNewLog) {\n id\n }\n appendIntegrationLog(integrationLogId: $integrationLogId, entries: $entries) {\n id\n }\n }\n `,\n {\n // Only create a new log the first time the logger is flushed.\n createNewLog: this.logCreated === false,\n entries,\n integrationId: this.integrationId,\n integrationLogId: this.integrationLogId,\n },\n );\n\n // Only create a new log the first time the logger is flushed.\n this.logCreated = true;\n\n await this.currentRequest;\n\n // Clear the request promise so that the next flush can start a new request.\n this.currentRequest = null;\n }\n\n public indent(message?: string) {\n if (message !== undefined) this.info(message);\n if (this.logger.group) this.logger.group();\n this.messageIndent += 1;\n }\n\n /**\n * Logs an informational message. The message will be appended to the log\n * buffer and flushed to the server if the last flush was more than 1 second\n * ago.\n */\n public info(message: string) {\n this.logger.info(message);\n this.enqueue(message);\n }\n\n public warn(message: string) {\n this.logger.warn(message);\n this.enqueue(message);\n }\n}\n\nexport default WorkniceIntegrationLogger;\n"],"mappings":"AAAA,OAAO,SAAS;AAChB,SAAS,gBAAgB;AACzB,SAAS,MAAM,YAAY;AAM3B,MAAM,0BAA0B;AAAA;AAAA;AAAA;AAAA;AAAA,EAKtB,SAAgC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,iBAA0C;AAAA;AAAA;AAAA;AAAA;AAAA,EAM1C,gBAAoC;AAAA;AAAA;AAAA;AAAA,EAKpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAqC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOrC,aAAa;AAAA;AAAA;AAAA;AAAA,EAKb;AAAA;AAAA;A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";\nimport { Temporal } from \"temporal-polyfill\";\nimport { v4 as uuid } from \"uuid\";\nimport errorToString from \"../utils/errorToString.js\";\nimport type { WorkniceClient } from \"./_types.js\";\n\nexport type Logger = Pick<Console, \"debug\" | \"error\" | \"info\" | \"warn\"> &\n Partial<Pick<Console, \"group\" | \"groupEnd\">>;\n\nexport type WorkniceIntegrationLoggerOptions = {\n /**\n * The type of log to use for debug messages. If set to \"debug\", debug\n * messages will be logged using the logger.debug() method, but if set to\n * \"info\", debug messages will be logged using the logger.info() method.\n *\n * Irrespective of this option, debug messages are only logged to the\n * configured logger and are never sent to the Worknice integration logs.\n */\n debugLogType: \"debug\" | \"info\";\n\n /**\n * The delay between flushes in milliseconds. Defaults to 1000 (1 second).\n */\n delayBetweenFlushes: number;\n\n /**\n * A Console-like object with which messages will be logger.\n */\n logger: Logger;\n};\n\nclass WorkniceIntegrationLogger {\n /**\n * The Worknice client used to send the logs to the server. If null, the logs\n * will be buffered until the logger is initialized.\n */\n private client: WorkniceClient | null = null;\n\n /**\n * A promise used to ensure that only one request is in progress at a time. If\n * a flush is called while a request is in progress, the flush will wait for\n * the request to finish before starting a new one.\n */\n private currentRequest: Promise<unknown> | null = null;\n\n /**\n * The integration ID the logs will be associated with. If undefined, the\n * logs will be buffered until the logger has been initialized.\n */\n private integrationId: string | undefined = undefined;\n\n /**\n * The random ID for the integration log to which the logs will be appended.\n */\n private integrationLogId: string;\n\n /**\n * Determines when the logger should flush the logs. Calling info(), error(),\n * warn(), indent() or dedent() will automatically flush the logs if the last\n * flush was more than 1 second ago.\n */\n private lastFlush: Temporal.Instant | null = null;\n\n /**\n * A flag is used to determine whether a new log should be created when the\n * logger is flushed. The first time the logger is flushed, a new log will be\n * created. Subsequent flushes will append to the existing log.\n */\n private logCreated = false;\n\n /**\n * Backlog of log messages that have not yet been sent to Worknice. The logs\n * will be sent to the server when the logger is flushed and the backlog will\n * be cleared.\n */\n private logs: Array<{ time: Temporal.Instant; message: string }> = [];\n\n /**\n * Determines the current indentation level of the log messages. The indent()\n * and dedent() functions can be used to increase or decrease the indentation\n * level.\n */\n private messageIndent = 0;\n\n private options: WorkniceIntegrationLoggerOptions;\n\n private timeout: NodeJS.Timeout | null = null;\n\n /**\n * A logger can log messages to both a Console-like object and to a Worknice\n * integration's logs which can be view by a Worknice user. By default,\n * messages are only logged to the configured logger, but when a Worknice\n * integration is connected using the connect() method, the messages will also\n * be sent to the Worknice integration logs.\n * @param logger A Console-like object with which messages can be logged.\n * @example\n * ```js\n * const logger = new WorkniceIntegrationLogger({ logger: console });\n * ```\n */\n constructor(options?: Partial<WorkniceIntegrationLoggerOptions>) {\n this.integrationLogId = uuid();\n this.options = {\n debugLogType: options?.debugLogType ?? \"debug\",\n delayBetweenFlushes: options?.delayBetweenFlushes ?? 1000,\n logger: options?.logger ?? console,\n };\n }\n\n /**\n * Connects the logger to a Worknice integration. If there are previously\n * logged messages that need to be flushed, a new integration log will be\n * instantly created and the messages flushed to it. Otherwise, an integration\n * log will be created if/when the first message is logged.\n */\n public connect(client: WorkniceClient, integrationId: string) {\n this.client = client;\n this.integrationId = integrationId;\n this.flush();\n }\n\n /**\n * Logs a debug message. Debug messages are only logged to the configured logger\n * and are never sent to the Worknice integration logs.\n */\n public debug(message: string) {\n if (this.options.debugLogType === \"debug\") this.options.logger.debug(message);\n else this.options.logger.info(message);\n }\n\n public dedent(message?: string) {\n if (message !== undefined) this.info(message);\n if (this.options.logger.groupEnd) this.options.logger.groupEnd();\n this.messageIndent = Math.max(0, this.messageIndent - 1);\n }\n\n private enqueue(message: string) {\n this.logs.push({\n time: Temporal.Now.instant(),\n message: message\n .split(\"\\n\")\n .map((line) => `${\" \".repeat(this.messageIndent * 2)}${line}`)\n .join(\"\\n\"),\n });\n\n // If the last flush was more than the delay between flushes, flush the logs\n // immediately. Otherwise, schedule a new flush unless one is already\n // scheduled.\n if (this.timeSinceLastFlush() >= this.options.delayBetweenFlushes) {\n this.flush();\n } else if (this.timeout === null) {\n this.timeout = setTimeout(() => {\n if (this.timeSinceLastFlush() >= this.options.delayBetweenFlushes) {\n this.flush();\n }\n }, this.options.delayBetweenFlushes - this.timeSinceLastFlush());\n }\n }\n\n /**\n * Logs an error of any type. The error will be logged to the configured logger\n * with full stack traces and a chain of error causes. A simplified error\n * message will sent to the Worknice integration logs (if connected) and\n * returned for displaying to the user. If the error is not an instance of\n * Error, it will be coerced into a string before being logged.\n */\n public error(error: unknown) {\n const verboseMessage = errorToString(error, {\n format: \"chain\",\n stack: true,\n });\n\n const simpleMessage = errorToString(error, {\n format: \"simple\",\n stack: false,\n });\n\n this.options.logger.error(verboseMessage);\n this.enqueue(simpleMessage);\n\n return simpleMessage;\n }\n\n /**\n * Flushes the log buffer to the server. The info() function will\n * automatically flush the logs if the last flush was more than 1 second\n * ago, but the flush() function should be called manually at the end of the\n * script to ensure that all logs are sent to the server.\n */\n public async flush() {\n // Clear any scheduled flushes.\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n\n // Update the last flush time to the current time so that any calls to\n // enqueue will not unnecessarily try to flush the logs again.\n this.lastFlush = Temporal.Now.instant();\n\n // If there's already a request in progress, wait for it to finish before\n // starting a new one.\n if (this.currentRequest) await this.currentRequest;\n\n // If there are no pending logs or the logger hasn't been initialized,\n // don't do anything (any logs will remain in the buffer until the next\n // flush).\n if (this.logs.length === 0 || this.client === null || this.integrationId === null) return;\n\n const entries = this.logs.splice(0).map(({ time, message }) => ({\n time: time.toString({ timeZone: \"Australia/Sydney\", smallestUnit: \"second\" }),\n message,\n }));\n\n this.currentRequest = this.client.fetchFromApi(\n gql`\n mutation AppendIntegrationLog(\n $createNewLog: Boolean!\n $entries: [IntegrationLogInput!]!\n $integrationId: ID!\n $integrationLogId: ID!\n ) {\n createIntegrationLog(integrationId: $integrationId, integrationLogId: $integrationLogId)\n @include(if: $createNewLog) {\n id\n }\n appendIntegrationLog(integrationLogId: $integrationLogId, entries: $entries) {\n id\n }\n }\n `,\n {\n // Only create a new log the first time the logger is flushed.\n createNewLog: this.logCreated === false,\n entries,\n integrationId: this.integrationId,\n integrationLogId: this.integrationLogId,\n },\n );\n\n // Only create a new log the first time the logger is flushed.\n this.logCreated = true;\n\n await this.currentRequest;\n\n // Clear the request promise so that the next flush can start a new request.\n this.currentRequest = null;\n }\n\n public indent(message?: string) {\n if (message !== undefined) this.info(message);\n if (this.options.logger.group) this.options.logger.group();\n this.messageIndent += 1;\n }\n\n /**\n * Logs an informational message. The message will be logged to the configured\n * logger and flushed to the Worknice integration logs if/when connected.\n */\n public info(message: string) {\n this.options.logger.info(message);\n this.enqueue(message);\n }\n\n private timeSinceLastFlush() {\n return this.lastFlush === null\n ? Number.MAX_SAFE_INTEGER\n : Temporal.Now.instant().since(this.lastFlush).total(\"milliseconds\");\n }\n\n public warn(message: string) {\n this.options.logger.warn(message);\n this.enqueue(message);\n }\n}\n\nexport default WorkniceIntegrationLogger;\n"],"mappings":"AAAA,OAAO,SAAS;AAChB,SAAS,gBAAgB;AACzB,SAAS,MAAM,YAAY;AAC3B,OAAO,mBAAmB;AA4B1B,MAAM,0BAA0B;AAAA;AAAA;AAAA;AAAA;AAAA,EAKtB,SAAgC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,iBAA0C;AAAA;AAAA;AAAA;AAAA;AAAA,EAM1C,gBAAoC;AAAA;AAAA;AAAA;AAAA,EAKpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAqC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOrC,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOb,OAA2D,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO5D,gBAAgB;AAAA,EAEhB;AAAA,EAEA,UAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,YAAY,SAAqD;AAC/D,SAAK,mBAAmB,KAAK;AAC7B,SAAK,UAAU;A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