@zapier/zapier-sdk 0.15.3 → 0.15.8

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 (66) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/api/auth.d.ts +10 -0
  3. package/dist/api/auth.d.ts.map +1 -1
  4. package/dist/api/auth.js +45 -0
  5. package/dist/api/auth.test.d.ts +2 -0
  6. package/dist/api/auth.test.d.ts.map +1 -0
  7. package/dist/api/auth.test.js +220 -0
  8. package/dist/api/client.d.ts.map +1 -1
  9. package/dist/api/client.js +18 -32
  10. package/dist/api/client.methods.test.d.ts +2 -0
  11. package/dist/api/client.methods.test.d.ts.map +1 -0
  12. package/dist/api/client.methods.test.js +158 -0
  13. package/dist/api/client.test.js +27 -11
  14. package/dist/api/router.d.ts +16 -0
  15. package/dist/api/router.d.ts.map +1 -0
  16. package/dist/api/router.js +37 -0
  17. package/dist/api/router.test.d.ts +2 -0
  18. package/dist/api/router.test.d.ts.map +1 -0
  19. package/dist/api/router.test.js +109 -0
  20. package/dist/api/schemas.d.ts +38 -38
  21. package/dist/auth.d.ts +15 -0
  22. package/dist/auth.d.ts.map +1 -1
  23. package/dist/auth.js +25 -0
  24. package/dist/index.cjs +350 -87
  25. package/dist/index.d.mts +430 -269
  26. package/dist/index.mjs +350 -88
  27. package/dist/plugins/eventEmission/index.d.ts +1 -1
  28. package/dist/plugins/eventEmission/index.d.ts.map +1 -1
  29. package/dist/plugins/eventEmission/index.js +94 -22
  30. package/dist/plugins/eventEmission/index.test.js +340 -2
  31. package/dist/plugins/getAuthentication/index.d.ts +2 -5
  32. package/dist/plugins/getAuthentication/index.d.ts.map +1 -1
  33. package/dist/plugins/getAuthentication/index.js +3 -24
  34. package/dist/plugins/getAuthentication/index.test.js +32 -144
  35. package/dist/plugins/getAuthentication/schemas.d.ts +4 -13
  36. package/dist/plugins/getAuthentication/schemas.d.ts.map +1 -1
  37. package/dist/plugins/getAuthentication/schemas.js +1 -11
  38. package/dist/schemas/Action.d.ts +1 -1
  39. package/dist/schemas/Auth.d.ts +6 -6
  40. package/dist/sdk.d.ts +1 -1
  41. package/dist/temporary-internal-core/handlers/getAuthentication.d.ts +94 -0
  42. package/dist/temporary-internal-core/handlers/getAuthentication.d.ts.map +1 -0
  43. package/dist/temporary-internal-core/handlers/getAuthentication.js +68 -0
  44. package/dist/temporary-internal-core/handlers/getAuthentication.test.d.ts +2 -0
  45. package/dist/temporary-internal-core/handlers/getAuthentication.test.d.ts.map +1 -0
  46. package/dist/temporary-internal-core/handlers/getAuthentication.test.js +248 -0
  47. package/dist/temporary-internal-core/handlers/listApps.js +1 -1
  48. package/dist/temporary-internal-core/index.d.ts +2 -0
  49. package/dist/temporary-internal-core/index.d.ts.map +1 -1
  50. package/dist/temporary-internal-core/index.js +2 -0
  51. package/dist/temporary-internal-core/schemas/authentications/index.d.ts +454 -0
  52. package/dist/temporary-internal-core/schemas/authentications/index.d.ts.map +1 -0
  53. package/dist/temporary-internal-core/schemas/authentications/index.js +96 -0
  54. package/dist/temporary-internal-core/schemas/errors/index.d.ts +139 -0
  55. package/dist/temporary-internal-core/schemas/errors/index.d.ts.map +1 -0
  56. package/dist/temporary-internal-core/schemas/errors/index.js +129 -0
  57. package/dist/temporary-internal-core/utils/app-locators.d.ts +0 -20
  58. package/dist/temporary-internal-core/utils/app-locators.d.ts.map +1 -1
  59. package/dist/temporary-internal-core/utils/app-locators.js +1 -45
  60. package/dist/temporary-internal-core/utils/string-utils.d.ts +28 -0
  61. package/dist/temporary-internal-core/utils/string-utils.d.ts.map +1 -0
  62. package/dist/temporary-internal-core/utils/string-utils.js +52 -0
  63. package/dist/temporary-internal-core/utils/transformations.d.ts +14 -0
  64. package/dist/temporary-internal-core/utils/transformations.d.ts.map +1 -1
  65. package/dist/temporary-internal-core/utils/transformations.js +37 -1
  66. package/package.json +1 -1
package/dist/auth.js CHANGED
@@ -45,3 +45,28 @@ export async function getTokenFromEnvOrConfig(options = {}) {
45
45
  // Second priority: CLI login package (if available)
46
46
  return getTokenFromCliLogin(options);
47
47
  }
48
+ /**
49
+ * Resolves an auth token from all possible sources with the following precedence:
50
+ * 1. Explicitly provided token in options
51
+ * 2. Token from getToken callback in options
52
+ * 3. ZAPIER_TOKEN environment variable
53
+ * 4. CLI login package (if available)
54
+ *
55
+ * This is the canonical token resolution logic used throughout the SDK.
56
+ * Returns undefined if no valid token is found.
57
+ */
58
+ export async function resolveAuthToken(options = {}) {
59
+ // First priority: explicitly provided token
60
+ if (options.token) {
61
+ return options.token;
62
+ }
63
+ // Second priority: getToken callback
64
+ if (options.getToken) {
65
+ const token = await options.getToken();
66
+ if (token) {
67
+ return token;
68
+ }
69
+ }
70
+ // Third and fourth priorities: environment variable or CLI login
71
+ return getTokenFromEnvOrConfig(options);
72
+ }
package/dist/index.cjs CHANGED
@@ -2305,49 +2305,68 @@ var getActionPlugin = ({ sdk }) => {
2305
2305
  }
2306
2306
  };
2307
2307
  };
2308
- var GetAuthenticationSchema = zod.z.object({
2308
+ var AuthenticationSchema2 = zod.z.object({
2309
+ id: zod.z.number(),
2310
+ date: zod.z.string(),
2311
+ lastchanged: zod.z.string().optional(),
2312
+ account_id: zod.z.number(),
2313
+ customuser_id: zod.z.number().optional(),
2314
+ selected_api: zod.z.string(),
2315
+ destination_selected_api: zod.z.string().nullable().optional(),
2316
+ is_invite_only: zod.z.boolean(),
2317
+ is_private: zod.z.boolean(),
2318
+ shared_with_all: zod.z.boolean(),
2319
+ is_stale: zod.z.string().optional(),
2320
+ is_shared: zod.z.string().optional(),
2321
+ marked_stale_at: zod.z.string().nullable().optional(),
2322
+ label: zod.z.string().nullable().optional(),
2323
+ identifier: zod.z.string().nullable().optional(),
2324
+ title: zod.z.string().nullable().optional(),
2325
+ url: zod.z.string().optional(),
2326
+ groups: zod.z.string().optional(),
2327
+ members: zod.z.string().optional(),
2328
+ permissions: zod.z.record(zod.z.boolean()).optional()
2329
+ });
2330
+ zod.z.object({
2331
+ count: zod.z.number(),
2332
+ next: zod.z.string().nullable().optional(),
2333
+ previous: zod.z.string().nullable().optional(),
2334
+ results: zod.z.array(AuthenticationSchema2)
2335
+ });
2336
+ var AuthenticationItemSchema2 = AuthenticationSchema2.omit({
2337
+ selected_api: true,
2338
+ customuser_id: true
2339
+ }).extend({
2340
+ // Renamed fields
2341
+ implementation_id: zod.z.string().optional(),
2342
+ user_id: zod.z.number().optional(),
2343
+ // Mapped fields (originals preserved in ...restOfAuth)
2344
+ is_expired: zod.z.string().optional(),
2345
+ expired_at: zod.z.string().nullable().optional(),
2346
+ // Computed fields
2347
+ app_key: zod.z.string().optional(),
2348
+ app_version: zod.z.string().optional()
2349
+ });
2350
+ var GetAuthenticationOptionsSchema = zod.z.object({
2309
2351
  authenticationId: zod.z.number().int().positive().describe("Authentication ID to retrieve")
2310
2352
  }).describe("Get a specific authentication by ID");
2353
+ var GetAuthenticationHandlerRequestSchema = zod.z.object({
2354
+ authenticationId: zod.z.union([zod.z.string(), zod.z.number()]).describe("Authentication ID - string from searchParams or number")
2355
+ }).transform((data) => ({
2356
+ authenticationId: typeof data.authenticationId === "string" ? parseInt(data.authenticationId, 10) : data.authenticationId
2357
+ }));
2358
+ zod.z.object({
2359
+ data: zod.z.lazy(() => AuthenticationItemSchema2)
2360
+ });
2311
2361
 
2312
2362
  // src/plugins/getAuthentication/index.ts
2313
2363
  var getAuthenticationPlugin = ({ context }) => {
2314
2364
  const getAuthentication = createFunction(async function getAuthentication2(options) {
2315
2365
  const { api } = context;
2316
- const { authenticationId } = options;
2317
- const data = await api.get(
2318
- `/zapier/api/v4/authentications/${authenticationId}/`,
2319
- {
2320
- customErrorHandler: ({ status }) => {
2321
- if (status === 401) {
2322
- return new ZapierAuthenticationError(
2323
- `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${status})`,
2324
- { statusCode: status }
2325
- );
2326
- }
2327
- if (status === 403) {
2328
- return new ZapierAuthenticationError(
2329
- `Access forbidden. Your token may not have the required scopes to get authentication ${authenticationId}. (HTTP ${status})`,
2330
- { statusCode: status }
2331
- );
2332
- }
2333
- if (status === 404) {
2334
- return new ZapierResourceNotFoundError(
2335
- `Authentication ${authenticationId} not found. It may not exist or you may not have access to it. (HTTP ${status})`,
2336
- {
2337
- resourceType: "Authentication",
2338
- resourceId: String(authenticationId)
2339
- }
2340
- );
2341
- }
2342
- return void 0;
2343
- },
2344
- authRequired: true
2345
- }
2366
+ return await api.get(
2367
+ `/api/v0/authentications/${options.authenticationId}`
2346
2368
  );
2347
- return {
2348
- data: normalizeAuthenticationItem(data)
2349
- };
2350
- }, GetAuthenticationSchema);
2369
+ }, GetAuthenticationOptionsSchema);
2351
2370
  return {
2352
2371
  getAuthentication,
2353
2372
  context: {
@@ -2356,7 +2375,7 @@ var getAuthenticationPlugin = ({ context }) => {
2356
2375
  categories: ["authentication"],
2357
2376
  type: "item",
2358
2377
  itemType: "Authentication",
2359
- inputSchema: GetAuthenticationSchema,
2378
+ inputSchema: GetAuthenticationOptionsSchema,
2360
2379
  outputSchema: AuthenticationItemSchema,
2361
2380
  resolvers: {
2362
2381
  authenticationId: authenticationIdGenericResolver
@@ -3193,12 +3212,46 @@ function isJwt(token) {
3193
3212
  const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
3194
3213
  return parts.every((part) => part.length > 0 && base64UrlPattern.test(part));
3195
3214
  }
3215
+ function parseJwt(token) {
3216
+ if (!isJwt(token)) {
3217
+ return null;
3218
+ }
3219
+ return token.split(".");
3220
+ }
3196
3221
  function getAuthorizationHeader(token) {
3197
3222
  if (isJwt(token)) {
3198
3223
  return `JWT ${token}`;
3199
3224
  }
3200
3225
  return `Bearer ${token}`;
3201
3226
  }
3227
+ function extractUserIdsFromJwt(token) {
3228
+ const parts = parseJwt(token);
3229
+ if (!parts) {
3230
+ return { customuser_id: null, account_id: null };
3231
+ }
3232
+ try {
3233
+ const payload = JSON.parse(
3234
+ Buffer.from(parts[1], "base64url").toString("utf-8")
3235
+ );
3236
+ let actualPayload = payload;
3237
+ if (payload.sub_type === "service" && payload.njwt) {
3238
+ const nestedParts = payload.njwt.split(".");
3239
+ if (nestedParts.length === 3) {
3240
+ actualPayload = JSON.parse(
3241
+ Buffer.from(nestedParts[1], "base64url").toString("utf-8")
3242
+ );
3243
+ }
3244
+ }
3245
+ const accountId = actualPayload["zap:acc"] != null ? parseInt(String(actualPayload["zap:acc"]), 10) : null;
3246
+ const customUserId = actualPayload.sub_type === "customuser" && actualPayload.sub != null ? parseInt(String(actualPayload.sub), 10) : null;
3247
+ return {
3248
+ customuser_id: customUserId !== null && !isNaN(customUserId) ? customUserId : null,
3249
+ account_id: accountId !== null && !isNaN(accountId) ? accountId : null
3250
+ };
3251
+ } catch {
3252
+ return { customuser_id: null, account_id: null };
3253
+ }
3254
+ }
3202
3255
 
3203
3256
  // src/api/debug.ts
3204
3257
  var utilModule = null;
@@ -3483,6 +3536,18 @@ async function getTokenFromEnvOrConfig(options = {}) {
3483
3536
  }
3484
3537
  return getTokenFromCliLogin(options);
3485
3538
  }
3539
+ async function resolveAuthToken(options = {}) {
3540
+ if (options.token) {
3541
+ return options.token;
3542
+ }
3543
+ if (options.getToken) {
3544
+ const token = await options.getToken();
3545
+ if (token) {
3546
+ return token;
3547
+ }
3548
+ }
3549
+ return getTokenFromEnvOrConfig(options);
3550
+ }
3486
3551
 
3487
3552
  // src/utils/url-utils.ts
3488
3553
  function getZapierBaseUrl(baseUrl) {
@@ -3530,7 +3595,7 @@ function getTrackingBaseUrl({
3530
3595
  return ZAPIER_BASE_URL;
3531
3596
  }
3532
3597
 
3533
- // src/temporary-internal-core/utils/app-locators.ts
3598
+ // src/temporary-internal-core/utils/string-utils.ts
3534
3599
  function splitVersionedKey2(versionedKey) {
3535
3600
  const parts = versionedKey.split("@");
3536
3601
  if (parts.length >= 2) {
@@ -3565,6 +3630,44 @@ function extractPaginationCursor(response) {
3565
3630
  return void 0;
3566
3631
  }
3567
3632
  }
3633
+ function normalizeAuthenticationItem2(auth, options = {}) {
3634
+ let appKey = options.app_key;
3635
+ let appVersion = options.app_version;
3636
+ if (auth.selected_api) {
3637
+ const [extractedAppKey, extractedVersion] = splitVersionedKey2(
3638
+ auth.selected_api
3639
+ );
3640
+ if (!appKey) {
3641
+ appKey = extractedAppKey;
3642
+ }
3643
+ if (!appVersion) {
3644
+ appVersion = extractedVersion;
3645
+ }
3646
+ }
3647
+ const {
3648
+ selected_api: selectedApi,
3649
+ customuser_id: userId,
3650
+ ...restOfAuth
3651
+ } = auth;
3652
+ return {
3653
+ ...restOfAuth,
3654
+ // Pass through all other API response fields except selected_api
3655
+ implementation_id: selectedApi,
3656
+ // Rename selected_api to implementation_id
3657
+ title: auth.title || auth.label || void 0,
3658
+ // Coerce title from label if missing
3659
+ is_expired: auth.is_stale,
3660
+ // Map is_stale to is_expired
3661
+ expired_at: auth.marked_stale_at,
3662
+ // Map marked_stale_at to expired_at
3663
+ app_key: appKey,
3664
+ // App key from implementations endpoint or parsed from selected_api
3665
+ app_version: appVersion,
3666
+ // Version from selected_api or provided
3667
+ user_id: userId
3668
+ // Map customuser_id to user_id
3669
+ };
3670
+ }
3568
3671
 
3569
3672
  // src/temporary-internal-core/handlers/listApps.ts
3570
3673
  var DEFAULT_PAGE_SIZE = 20;
@@ -3659,6 +3762,111 @@ var handleListApps = async ({ request, deps }) => {
3659
3762
  };
3660
3763
  };
3661
3764
 
3765
+ // src/temporary-internal-core/schemas/errors/index.ts
3766
+ var ZapierError2 = class extends Error {
3767
+ constructor(message, options = {}) {
3768
+ super(message);
3769
+ this.statusCode = options.statusCode;
3770
+ this.errors = options.errors;
3771
+ this.cause = options.cause;
3772
+ this.response = options.response;
3773
+ Object.setPrototypeOf(this, new.target.prototype);
3774
+ }
3775
+ };
3776
+ var ZapierAuthenticationError2 = class extends ZapierError2 {
3777
+ constructor(message, options = {}) {
3778
+ super(message, options);
3779
+ this.name = "ZapierAuthenticationError";
3780
+ }
3781
+ };
3782
+ var ZapierResourceNotFoundError2 = class extends ZapierError2 {
3783
+ constructor(message, options = {}) {
3784
+ super(message, options);
3785
+ this.name = "ZapierResourceNotFoundError";
3786
+ this.resourceType = options.resourceType;
3787
+ this.resourceId = options.resourceId;
3788
+ }
3789
+ };
3790
+
3791
+ // src/temporary-internal-core/handlers/getAuthentication.ts
3792
+ var handleGetAuthentication = async ({ request, deps }) => {
3793
+ const validatedRequest = GetAuthenticationHandlerRequestSchema.parse(request);
3794
+ const { httpClient } = deps;
3795
+ const { authenticationId } = validatedRequest;
3796
+ const authentication = await httpClient.get(
3797
+ `/zapier/api/v4/authentications/${authenticationId}/`,
3798
+ {
3799
+ authRequired: true,
3800
+ customErrorHandler: ({ status }) => {
3801
+ if (status === 401) {
3802
+ return new ZapierAuthenticationError2(
3803
+ `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${status})`,
3804
+ { statusCode: status }
3805
+ );
3806
+ }
3807
+ if (status === 403) {
3808
+ return new ZapierAuthenticationError2(
3809
+ `Access forbidden. Your token may not have the required scopes to get authentication ${authenticationId}. (HTTP ${status})`,
3810
+ { statusCode: status }
3811
+ );
3812
+ }
3813
+ if (status === 404) {
3814
+ return new ZapierResourceNotFoundError2(
3815
+ `Authentication ${authenticationId} not found. It may not exist or you may not have access to it. (HTTP ${status})`,
3816
+ {
3817
+ resourceType: "Authentication",
3818
+ resourceId: String(authenticationId)
3819
+ }
3820
+ );
3821
+ }
3822
+ return void 0;
3823
+ }
3824
+ }
3825
+ );
3826
+ const normalizedAuthentication = normalizeAuthenticationItem2(authentication);
3827
+ return {
3828
+ data: normalizedAuthentication
3829
+ };
3830
+ };
3831
+
3832
+ // src/api/router.ts
3833
+ var routes = [
3834
+ {
3835
+ method: "GET",
3836
+ pattern: /^\/api\/v0\/apps$/,
3837
+ handler: handleListApps,
3838
+ paramMap: []
3839
+ },
3840
+ {
3841
+ method: "GET",
3842
+ pattern: /^\/api\/v0\/authentications\/([^\/]+)$/,
3843
+ handler: handleGetAuthentication,
3844
+ paramMap: ["authenticationId"]
3845
+ }
3846
+ ];
3847
+ function findMatchingRoute(routeList, method, path) {
3848
+ for (const route of routeList) {
3849
+ if (route.method !== method) {
3850
+ continue;
3851
+ }
3852
+ const match = path.match(route.pattern);
3853
+ if (match) {
3854
+ const params = {};
3855
+ route.paramMap.forEach((name, index) => {
3856
+ params[name] = match[index + 1];
3857
+ });
3858
+ return {
3859
+ handler: route.handler,
3860
+ params
3861
+ };
3862
+ }
3863
+ }
3864
+ return null;
3865
+ }
3866
+ function matchRoute(method, path) {
3867
+ return findMatchingRoute(routes, method, path);
3868
+ }
3869
+
3662
3870
  // src/api/client.ts
3663
3871
  var pathConfig = {
3664
3872
  // e.g. /relay -> https://sdkapi.zapier.com/api/v0/sdk/relay/...
@@ -3670,9 +3878,6 @@ var pathConfig = {
3670
3878
  "/zapier": {
3671
3879
  authHeader: "Authorization",
3672
3880
  pathPrefix: "/api/v0/sdk/zapier"
3673
- },
3674
- "/api/v0/apps": {
3675
- handlerOverride: handleListApps
3676
3881
  }
3677
3882
  };
3678
3883
  var ZapierApiClient = class {
@@ -3718,16 +3923,9 @@ var ZapierApiClient = class {
3718
3923
  }
3719
3924
  // Helper to get a token from the different places it could be gotten
3720
3925
  async getAuthToken() {
3721
- if (this.options.token) {
3722
- return this.options.token;
3723
- }
3724
- if (this.options.getToken) {
3725
- const token = await this.options.getToken();
3726
- if (token) {
3727
- return token;
3728
- }
3729
- }
3730
- return getTokenFromEnvOrConfig({
3926
+ return resolveAuthToken({
3927
+ token: this.options.token,
3928
+ getToken: this.options.getToken,
3731
3929
  onEvent: this.options.onEvent,
3732
3930
  fetch: this.options.fetch,
3733
3931
  baseUrl: this.options.baseUrl,
@@ -3830,14 +4028,6 @@ var ZapierApiClient = class {
3830
4028
  }
3831
4029
  return void 0;
3832
4030
  }
3833
- // Helper to check if a path config has a handler override
3834
- hasHandlerOverride(pathConfig2) {
3835
- return pathConfig2 !== void 0 && "handlerOverride" in pathConfig2 && typeof pathConfig2.handlerOverride === "function";
3836
- }
3837
- // Helper to check if a path config is a standard path config
3838
- isStandardPathConfig(pathConfig2) {
3839
- return pathConfig2 !== void 0 && !this.hasHandlerOverride(pathConfig2);
3840
- }
3841
4031
  // Helper to parse API error response
3842
4032
  parseErrorResponse(errorInfo) {
3843
4033
  const fallbackMessage = `HTTP ${errorInfo.status}: ${errorInfo.statusText}`;
@@ -3889,8 +4079,10 @@ var ZapierApiClient = class {
3889
4079
  pathConfig: config
3890
4080
  };
3891
4081
  }
4082
+ const baseUrl = new URL(this.options.baseUrl);
4083
+ const fullPath = baseUrl.pathname.replace(/\/$/, "") + path;
3892
4084
  return {
3893
- url: new URL(path, this.options.baseUrl),
4085
+ url: new URL(fullPath, baseUrl.origin),
3894
4086
  pathConfig: config
3895
4087
  };
3896
4088
  }
@@ -3909,7 +4101,7 @@ var ZapierApiClient = class {
3909
4101
  const headers = new Headers(options.headers ?? {});
3910
4102
  const authToken = await this.getAuthToken();
3911
4103
  if (authToken) {
3912
- const authHeaderName = this.isStandardPathConfig(pathConfig2) && pathConfig2.authHeader ? pathConfig2.authHeader : "Authorization";
4104
+ const authHeaderName = pathConfig2 && pathConfig2.authHeader ? pathConfig2.authHeader : "Authorization";
3913
4105
  headers.set(authHeaderName, getAuthorizationHeader(authToken));
3914
4106
  }
3915
4107
  if (options.authRequired) {
@@ -3923,10 +4115,14 @@ var ZapierApiClient = class {
3923
4115
  }
3924
4116
  // Helper to perform HTTP requests with JSON handling
3925
4117
  async fetchJson(method, path, data, options = {}) {
3926
- const { pathConfig: pathConfig2 } = this.buildUrl(path, options.searchParams);
3927
- if (this.hasHandlerOverride(pathConfig2)) {
3928
- const handlerRequest = method === "GET" ? options.searchParams : data;
3929
- return pathConfig2.handlerOverride({
4118
+ const routeMatch = matchRoute(method, path);
4119
+ if (routeMatch) {
4120
+ const handlerRequest = {
4121
+ ...typeof data === "object" ? data : {},
4122
+ ...options.searchParams,
4123
+ ...routeMatch.params
4124
+ };
4125
+ return routeMatch.handler({
3930
4126
  request: handlerRequest,
3931
4127
  deps: {
3932
4128
  httpClient: this
@@ -4595,7 +4791,7 @@ function getCpuTime() {
4595
4791
 
4596
4792
  // package.json
4597
4793
  var package_default = {
4598
- version: "0.15.3"};
4794
+ version: "0.15.8"};
4599
4795
 
4600
4796
  // src/plugins/eventEmission/builders.ts
4601
4797
  function createBaseEvent(context = {}) {
@@ -4666,17 +4862,26 @@ function buildErrorEventWithContext(data, context = {}) {
4666
4862
  }
4667
4863
 
4668
4864
  // src/plugins/eventEmission/index.ts
4865
+ var TELEMETRY_EMIT_TIMEOUT_MS = 300;
4669
4866
  var APPLICATION_LIFECYCLE_EVENT_SUBJECT = "platform.sdk.ApplicationLifecycleEvent";
4670
4867
  var ERROR_OCCURRED_EVENT_SUBJECT = "platform.sdk.ErrorOccurredEvent";
4671
4868
  var transportStates = /* @__PURE__ */ new WeakMap();
4672
- async function silentEmit(transport, subject, event) {
4869
+ async function silentEmit(transport, subject, event, userContextPromise) {
4673
4870
  try {
4674
4871
  let state = transportStates.get(transport);
4675
4872
  if (!state) {
4676
4873
  state = { hasWorked: false, hasLoggedFailure: false };
4677
4874
  transportStates.set(transport, state);
4678
4875
  }
4679
- transport.emit(subject, event).then(() => {
4876
+ let enrichedEvent = event;
4877
+ if (userContextPromise) {
4878
+ try {
4879
+ const userContext = await userContextPromise;
4880
+ enrichedEvent = Object.assign({}, event, userContext);
4881
+ } catch {
4882
+ }
4883
+ }
4884
+ transport.emit(subject, enrichedEvent).then(() => {
4680
4885
  state.hasWorked = true;
4681
4886
  }).catch((error) => {
4682
4887
  if (!state.hasWorked && !state.hasLoggedFailure) {
@@ -4724,6 +4929,24 @@ var eventEmissionPlugin = ({ context }) => {
4724
4929
  )
4725
4930
  )
4726
4931
  };
4932
+ const getUserContext = (async () => {
4933
+ try {
4934
+ const token = await resolveAuthToken({
4935
+ token: context.options.token,
4936
+ getToken: context.options.getToken,
4937
+ baseUrl: context.options.baseUrl,
4938
+ authBaseUrl: context.options.authBaseUrl,
4939
+ authClientId: context.options.authClientId,
4940
+ onEvent: context.options.onEvent,
4941
+ fetch: context.options.fetch
4942
+ });
4943
+ if (token) {
4944
+ return extractUserIdsFromJwt(token);
4945
+ }
4946
+ } catch {
4947
+ }
4948
+ return { customuser_id: null, account_id: null };
4949
+ })();
4727
4950
  const startupTime = Date.now();
4728
4951
  let shutdownStartTime = null;
4729
4952
  if (!config.enabled) {
@@ -4734,7 +4957,7 @@ var eventEmissionPlugin = ({ context }) => {
4734
4957
  config,
4735
4958
  emit: () => {
4736
4959
  },
4737
- createBaseEvent: () => ({
4960
+ createBaseEvent: async () => ({
4738
4961
  event_id: generateEventId(),
4739
4962
  timestamp_ms: getCurrentTimestamp(),
4740
4963
  release_id: getReleaseId(),
@@ -4754,21 +4977,34 @@ var eventEmissionPlugin = ({ context }) => {
4754
4977
  } catch {
4755
4978
  transport = createTransport({ type: "noop" });
4756
4979
  }
4757
- const createBaseEventHelper = () => ({
4758
- event_id: generateEventId(),
4759
- timestamp_ms: getCurrentTimestamp(),
4760
- release_id: getReleaseId(),
4761
- customuser_id: null,
4762
- account_id: null,
4763
- identity_id: null,
4764
- visitor_id: null,
4765
- correlation_id: null
4766
- });
4980
+ const createBaseEventHelper = async () => {
4981
+ const baseEvent = {
4982
+ event_id: generateEventId(),
4983
+ timestamp_ms: getCurrentTimestamp(),
4984
+ release_id: getReleaseId(),
4985
+ customuser_id: null,
4986
+ account_id: null,
4987
+ identity_id: null,
4988
+ visitor_id: null,
4989
+ correlation_id: null
4990
+ };
4991
+ try {
4992
+ const userContext = await getUserContext;
4993
+ return { ...baseEvent, ...userContext };
4994
+ } catch {
4995
+ return baseEvent;
4996
+ }
4997
+ };
4767
4998
  if (config.enabled) {
4768
4999
  const startupEvent = buildApplicationLifecycleEvent({
4769
5000
  lifecycle_event_type: "startup"
4770
5001
  });
4771
- silentEmit(transport, APPLICATION_LIFECYCLE_EVENT_SUBJECT, startupEvent);
5002
+ silentEmit(
5003
+ transport,
5004
+ APPLICATION_LIFECYCLE_EVENT_SUBJECT,
5005
+ startupEvent,
5006
+ getUserContext
5007
+ );
4772
5008
  if (typeof process?.on === "function") {
4773
5009
  process.on("exit", (code) => {
4774
5010
  const uptime = Date.now() - startupTime;
@@ -4780,10 +5016,15 @@ var eventEmissionPlugin = ({ context }) => {
4780
5016
  is_graceful_shutdown: code === 0,
4781
5017
  shutdown_duration_ms: shutdownDuration
4782
5018
  });
4783
- silentEmit(transport, APPLICATION_LIFECYCLE_EVENT_SUBJECT, exitEvent);
5019
+ silentEmit(
5020
+ transport,
5021
+ APPLICATION_LIFECYCLE_EVENT_SUBJECT,
5022
+ exitEvent,
5023
+ getUserContext
5024
+ );
4784
5025
  });
4785
5026
  process.on("uncaughtException", async (error) => {
4786
- const errorEvent = buildErrorEventWithContext({
5027
+ let errorEvent = buildErrorEventWithContext({
4787
5028
  error_message: error.message || "Unknown error",
4788
5029
  error_type: "UncaughtException",
4789
5030
  error_stack_trace: error.stack || null,
@@ -4792,10 +5033,17 @@ var eventEmissionPlugin = ({ context }) => {
4792
5033
  is_recoverable: false,
4793
5034
  execution_start_time: startupTime
4794
5035
  });
5036
+ try {
5037
+ const userContext = await getUserContext;
5038
+ errorEvent = { ...errorEvent, ...userContext };
5039
+ } catch {
5040
+ }
4795
5041
  try {
4796
5042
  await Promise.race([
4797
5043
  transport.emit(ERROR_OCCURRED_EVENT_SUBJECT, errorEvent),
4798
- new Promise((resolve2) => setTimeout(resolve2, 300))
5044
+ new Promise(
5045
+ (resolve2) => setTimeout(resolve2, TELEMETRY_EMIT_TIMEOUT_MS)
5046
+ )
4799
5047
  ]);
4800
5048
  } catch {
4801
5049
  }
@@ -4805,7 +5053,7 @@ var eventEmissionPlugin = ({ context }) => {
4805
5053
  async (reason, promise) => {
4806
5054
  const errorMessage = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection";
4807
5055
  const errorStack = reason instanceof Error ? reason.stack : null;
4808
- const errorEvent = buildErrorEventWithContext({
5056
+ let errorEvent = buildErrorEventWithContext({
4809
5057
  error_message: errorMessage,
4810
5058
  error_type: "UnhandledRejection",
4811
5059
  error_stack_trace: errorStack,
@@ -4817,10 +5065,17 @@ var eventEmissionPlugin = ({ context }) => {
4817
5065
  promise: String(promise)
4818
5066
  }
4819
5067
  });
5068
+ try {
5069
+ const userContext = await getUserContext;
5070
+ errorEvent = { ...errorEvent, ...userContext };
5071
+ } catch {
5072
+ }
4820
5073
  try {
4821
5074
  await Promise.race([
4822
5075
  transport.emit(ERROR_OCCURRED_EVENT_SUBJECT, errorEvent),
4823
- new Promise((resolve2) => setTimeout(resolve2, 300))
5076
+ new Promise(
5077
+ (resolve2) => setTimeout(resolve2, TELEMETRY_EMIT_TIMEOUT_MS)
5078
+ )
4824
5079
  ]);
4825
5080
  } catch {
4826
5081
  }
@@ -4829,16 +5084,23 @@ var eventEmissionPlugin = ({ context }) => {
4829
5084
  const handleSignal = async (signal) => {
4830
5085
  shutdownStartTime = Date.now();
4831
5086
  const uptime = Date.now() - startupTime;
4832
- const signalEvent = buildApplicationLifecycleEvent({
5087
+ let signalEvent = buildApplicationLifecycleEvent({
4833
5088
  lifecycle_event_type: "signal_termination",
4834
5089
  signal_name: signal,
4835
5090
  uptime_ms: uptime,
4836
5091
  is_graceful_shutdown: true
4837
5092
  });
5093
+ try {
5094
+ const userContext = await getUserContext;
5095
+ signalEvent = { ...signalEvent, ...userContext };
5096
+ } catch {
5097
+ }
4838
5098
  try {
4839
5099
  await Promise.race([
4840
5100
  transport.emit(APPLICATION_LIFECYCLE_EVENT_SUBJECT, signalEvent),
4841
- new Promise((resolve2) => setTimeout(resolve2, 300))
5101
+ new Promise(
5102
+ (resolve2) => setTimeout(resolve2, TELEMETRY_EMIT_TIMEOUT_MS)
5103
+ )
4842
5104
  ]);
4843
5105
  } catch {
4844
5106
  }
@@ -4854,7 +5116,7 @@ var eventEmissionPlugin = ({ context }) => {
4854
5116
  transport,
4855
5117
  config,
4856
5118
  emit: (subject, event) => {
4857
- silentEmit(transport, subject, event);
5119
+ silentEmit(transport, subject, event, getUserContext);
4858
5120
  },
4859
5121
  createBaseEvent: createBaseEventHelper
4860
5122
  }
@@ -4994,6 +5256,7 @@ exports.manifestPlugin = manifestPlugin;
4994
5256
  exports.readManifestFromFile = readManifestFromFile;
4995
5257
  exports.registryPlugin = registryPlugin;
4996
5258
  exports.requestPlugin = requestPlugin;
5259
+ exports.resolveAuthToken = resolveAuthToken;
4997
5260
  exports.runActionPlugin = runActionPlugin;
4998
5261
  exports.toSnakeCase = toSnakeCase;
4999
5262
  exports.toTitleCase = toTitleCase;