@superdurable/connector-amplitude 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,45 @@
1
1
  import {
2
+ ActiveUserCountsInputSchema,
3
+ ActiveUserCountsSchema,
4
+ ChartResultSchema,
2
5
  ConfigSchema,
3
6
  Connection,
4
7
  ConnectorID,
8
+ CredentialMaterialError,
9
+ GetActiveUserCountsBranch,
10
+ GetActiveUserCountsBranchCounted,
11
+ GetActiveUserCountsBranchDefect,
12
+ GetActiveUserCountsBranchInvalidResponse,
13
+ GetActiveUserCountsBranchProviderRejected,
14
+ GetActiveUserCountsDefinition,
15
+ GetActiveUserCountsMetadata,
16
+ GetUserActivityBranch,
17
+ GetUserActivityBranchDefect,
18
+ GetUserActivityBranchFound,
19
+ GetUserActivityBranchInvalidResponse,
20
+ GetUserActivityBranchMissing,
21
+ GetUserActivityBranchProviderRejected,
22
+ GetUserActivityDefinition,
23
+ GetUserActivityInputSchema,
24
+ GetUserActivityMetadata,
25
+ IdentifiedUserSchema,
26
+ IdentifyUserBranch,
27
+ IdentifyUserBranchDefect,
28
+ IdentifyUserBranchIdentified,
29
+ IdentifyUserBranchProviderRejected,
30
+ IdentifyUserDefinition,
31
+ IdentifyUserInputSchema,
32
+ IdentifyUserMetadata,
5
33
  ProviderID,
34
+ QueryChartBranch,
35
+ QueryChartBranchDefect,
36
+ QueryChartBranchFound,
37
+ QueryChartBranchInvalidResponse,
38
+ QueryChartBranchMissing,
39
+ QueryChartBranchProviderRejected,
40
+ QueryChartDefinition,
41
+ QueryChartInputSchema,
42
+ QueryChartMetadata,
6
43
  SearchUsersBranch,
7
44
  SearchUsersBranchDefect,
8
45
  SearchUsersBranchInvalidResponse,
@@ -11,15 +48,91 @@ import {
11
48
  SearchUsersDefinition,
12
49
  SearchUsersInputSchema,
13
50
  SearchUsersMetadata,
51
+ TrackEventBranch,
52
+ TrackEventBranchDefect,
53
+ TrackEventBranchProviderRejected,
54
+ TrackEventBranchTracked,
55
+ TrackEventDefinition,
56
+ TrackEventInputSchema,
57
+ TrackEventMetadata,
58
+ TrackedEventSchema,
59
+ UnsetUserPropertyBranch,
60
+ UnsetUserPropertyBranchDefect,
61
+ UnsetUserPropertyBranchProviderRejected,
62
+ UnsetUserPropertyBranchUnset,
63
+ UnsetUserPropertyDefinition,
64
+ UnsetUserPropertyInputSchema,
65
+ UnsetUserPropertyMetadata,
66
+ UserActivitySchema,
14
67
  UserSearchPageSchema,
15
68
  decodeCredentials,
69
+ isCredentialMaterialError,
16
70
  newConnection,
17
71
  newConnectionWithOperations,
18
72
  newProjectConnection
19
- } from "./chunk-JHZRBQDD.js";
73
+ } from "./chunk-CTVTAUET.js";
20
74
 
21
75
  // src/generated/steps.ts
22
- import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
76
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
77
+ function newQueryChartStep(configuration) {
78
+ const { connection, connectionName, found, missing, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
79
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
80
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.queryChart(), connection: connection.reference, branches: [
81
+ goToBranch("found", found),
82
+ ...missing ? [goToBranch("missing", missing)] : [],
83
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
84
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
85
+ ...defect ? [goToBranch("defect", defect)] : []
86
+ ] });
87
+ }
88
+ function newGetActiveUserCountsStep(configuration) {
89
+ const { connection, connectionName, counted, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
90
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
91
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getActiveUserCounts(), connection: connection.reference, branches: [
92
+ goToBranch("counted", counted),
93
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
94
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
95
+ ...defect ? [goToBranch("defect", defect)] : []
96
+ ] });
97
+ }
98
+ function newGetUserActivityStep(configuration) {
99
+ const { connection, connectionName, found, missing, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
100
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
101
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getUserActivity(), connection: connection.reference, branches: [
102
+ goToBranch("found", found),
103
+ ...missing ? [goToBranch("missing", missing)] : [],
104
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
105
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
106
+ ...defect ? [goToBranch("defect", defect)] : []
107
+ ] });
108
+ }
109
+ function newUnsetUserPropertyStep(configuration) {
110
+ const { connection, connectionName, unset, providerRejected, defect, maxSends, ...stepConfiguration } = configuration;
111
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
112
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.unsetUserProperty(), connection: connection.reference, branches: [
113
+ goToBranch("unset", unset),
114
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
115
+ ...defect ? [goToBranch("defect", defect)] : []
116
+ ] });
117
+ }
118
+ function newTrackEventStep(configuration) {
119
+ const { connection, connectionName, tracked, providerRejected, defect, maxSends, ...stepConfiguration } = configuration;
120
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
121
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.trackEvent(), connection: connection.reference, branches: [
122
+ goToBranch("tracked", tracked),
123
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
124
+ ...defect ? [goToBranch("defect", defect)] : []
125
+ ] });
126
+ }
127
+ function newIdentifyUserStep(configuration) {
128
+ const { connection, connectionName, identified, providerRejected, defect, maxSends, ...stepConfiguration } = configuration;
129
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
130
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.identifyUser(), connection: connection.reference, branches: [
131
+ goToBranch("identified", identified),
132
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
133
+ ...defect ? [goToBranch("defect", defect)] : []
134
+ ] });
135
+ }
23
136
  function newSearchUsersStep(configuration) {
24
137
  const { connection, connectionName, searched, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
25
138
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
@@ -33,18 +146,61 @@ function newSearchUsersStep(configuration) {
33
146
 
34
147
  // src/project.ts
35
148
  import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
36
- import { z } from "zod";
149
+ import { z as z2 } from "zod";
37
150
 
38
151
  // src/client.ts
39
- import { SecretString, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
40
- import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
152
+ import { SecretString, newMutationBranch, newMutationRetry, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
153
+ import { BodyTooLargeError, encodeQueryValues, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
154
+ import { z } from "zod";
41
155
  var emptyUsers = () => ({ user: "", userIDs: [], matchType: "" });
42
156
  var AmplitudeClient = class {
157
+ transport;
43
158
  /** Validate provider configuration without contacting Amplitude. */
44
159
  constructor(config, credentials, options = {}) {
160
+ this.transport = new AmplitudeTransport(config, credentials, options);
161
+ }
162
+ /** Bind the queryChart operation. */
163
+ queryChart() {
164
+ return new QueryChartOperation(this.transport);
165
+ }
166
+ /** Bind the getActiveUserCounts operation. */
167
+ getActiveUserCounts() {
168
+ return new GetActiveUserCountsOperation(this.transport);
169
+ }
170
+ /** Bind the getUserActivity operation. */
171
+ getUserActivity() {
172
+ return new GetUserActivityOperation(this.transport);
173
+ }
174
+ /** Bind the unsetUserProperty operation. */
175
+ unsetUserProperty() {
176
+ return new UnsetUserPropertyOperation(this.transport);
177
+ }
178
+ /** Bind the trackEvent operation. */
179
+ trackEvent() {
180
+ return new TrackEventOperation(this.transport);
181
+ }
182
+ /** Bind the identifyUser operation. */
183
+ identifyUser() {
184
+ return new IdentifyUserOperation(this.transport);
185
+ }
186
+ /** Bind the searchUsers Query. */
187
+ searchUsers() {
188
+ return new SearchUsersOperation(this);
189
+ }
190
+ /** Resolve credentials and send one bounded user search. */
191
+ async get(call, user) {
192
+ return this.transport.getDashboard(call, "/api/2/usersearch", { user: [user] });
193
+ }
194
+ };
195
+ var AmplitudeTransport = class {
196
+ constructor(config, credentials, options) {
45
197
  this.credentials = credentials;
46
198
  if (!config || !credentials) throw new TypeError("Amplitude configuration and credentials are required");
47
199
  this.baseURL = validateBaseURL(config.baseUrl ?? "https://amplitude.com").replace(/\/$/, "");
200
+ this.ingestionURL = (/* @__PURE__ */ new Map([
201
+ ["https://amplitude.com", "https://api2.amplitude.com"],
202
+ ["https://analytics.eu.amplitude.com", "https://api.eu.amplitude.com"]
203
+ ])).get(this.baseURL) ?? this.baseURL;
48
204
  this.timeoutMs = config.timeoutMs ?? 15e3;
49
205
  this.maxResponseBytes = config.maxResponseBytes ?? 1048576;
50
206
  if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0)
@@ -53,34 +209,53 @@ var AmplitudeClient = class {
53
209
  }
54
210
  credentials;
55
211
  baseURL;
212
+ ingestionURL;
56
213
  timeoutMs;
57
214
  maxResponseBytes;
58
215
  send;
59
- /** Bind the searchUsers Query. */
60
- searchUsers() {
61
- return new SearchUsersOperation(this);
216
+ /** Resolve credentials and send a bounded Dashboard request. */
217
+ async getDashboard(call, path, parameters) {
218
+ const keys = await this.resolveKeys(call);
219
+ if (!keys || !isHeaderSafeCredential(keys.apiKey) || !isHeaderSafeCredential(keys.secretKey) || keys.apiKey.includes(":"))
220
+ return emptyExchange("credential");
221
+ const authorization = Buffer.from(`${keys.apiKey}:${keys.secretKey}`).toString("base64");
222
+ const query = encodeQueryValues(parameters);
223
+ const exchange = await this.sendRequest(call, "GET", this.baseURL + path + (query ? "?" + query : ""), {
224
+ Authorization: `Basic ${authorization}`
225
+ });
226
+ const body = Buffer.from(exchange.body);
227
+ if (body.includes(keys.apiKey) || body.includes(keys.secretKey))
228
+ return { ...exchange, body: new Uint8Array(), error: "credentialEcho" };
229
+ return exchange;
62
230
  }
63
- /** Resolve credentials and send one bounded user search. */
64
- async get(call, user) {
65
- let apiKey;
66
- let secretKey;
231
+ /** Send one bounded ingestion request to the configured region. */
232
+ async postIngestion(call, path, contentType, body) {
233
+ return this.sendRequest(call, "POST", this.ingestionURL + path, { "Content-Type": contentType }, body);
234
+ }
235
+ /** Resolve the API key used by the ingestion endpoints. */
236
+ async ingestionKey(call) {
237
+ const keys = await this.resolveKeys(call);
238
+ return keys && isHeaderSafeCredential(keys.apiKey) ? keys.apiKey : void 0;
239
+ }
240
+ async resolveKeys(call) {
67
241
  try {
68
242
  const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
69
- apiKey = credentials.apiKey instanceof SecretString ? credentials.apiKey.reveal() : "";
70
- secretKey = credentials.secretKey instanceof SecretString ? credentials.secretKey.reveal() : "";
243
+ const apiKey = credentials.apiKey instanceof SecretString ? credentials.apiKey.reveal() : "";
244
+ const secretKey = credentials.secretKey instanceof SecretString ? credentials.secretKey.reveal() : "";
245
+ return apiKey && secretKey ? { apiKey, secretKey } : void 0;
71
246
  } catch {
72
- return emptyExchange("credential");
247
+ return void 0;
73
248
  }
74
- if (!isHeaderSafeCredential(apiKey) || !isHeaderSafeCredential(secretKey) || apiKey.includes(":")) return emptyExchange("credential");
75
- const url = new URL(`${this.baseURL}/api/2/usersearch`);
76
- url.searchParams.set("user", user);
249
+ }
250
+ async sendRequest(call, method, url, headers, body) {
77
251
  const request = {
78
- url: url.toString(),
79
- method: "GET",
80
- headers: { Accept: "application/json", Authorization: `Basic ${Buffer.from(`${apiKey}:${secretKey}`).toString("base64")}` },
252
+ url,
253
+ method,
254
+ headers: { Accept: "application/json", ...headers },
255
+ ...body === void 0 ? {} : { body },
81
256
  maxResponseBytes: this.maxResponseBytes,
82
257
  timeoutMs: this.timeoutMs,
83
- addressPolicy: this.baseURL.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
258
+ addressPolicy: url.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
84
259
  signal: call.context.cancellationSignal
85
260
  };
86
261
  let response;
@@ -120,6 +295,7 @@ var SearchUsersOperation = class {
120
295
  if (exchange.status === 408 || exchange.status >= 500) return retry("AVAILABILITY", "Amplitude is temporarily unavailable", exchange.retryAfterMs);
121
296
  if (exchange.status !== 200) return terminal("providerRejected", "PROVIDER_REJECTION", `Amplitude rejected HTTP ${exchange.status}`);
122
297
  if (exchange.error === "tooLarge") return terminal("invalidResponse", "RESPONSE_TOO_LARGE", "Amplitude response exceeded the configured limit");
298
+ if (exchange.error === "credentialEcho") return terminal("invalidResponse", "PROTOCOL", "Amplitude response contained credentials");
123
299
  const users = decodeUsers(exchange.body, input.user);
124
300
  if (!users) return terminal("invalidResponse", "PROTOCOL", "Amplitude returned invalid user-search JSON");
125
301
  return newQueryBranch("searched", users);
@@ -162,13 +338,324 @@ function decodeUsers(body, user) {
162
338
  }
163
339
  return { user, userIDs, matchType: raw.type };
164
340
  }
341
+ var QueryChartOperation = class {
342
+ /** Bind the provider client. */
343
+ constructor(client) {
344
+ this.client = client;
345
+ }
346
+ client;
347
+ /** Return the saved chart Query definition. */
348
+ definition() {
349
+ return QueryChartDefinition;
350
+ }
351
+ /** Return the compact data object or array. */
352
+ async invoke(call, input) {
353
+ const operation = "queryChart";
354
+ const zero = { chartID: "", dataJSON: "" };
355
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(input.chartID))
356
+ return queryBranch(operation, zero, "defect", "VALIDATION");
357
+ const exchange = await this.client.getDashboard(call, `/api/3/chart/${input.chartID}/query`, {});
358
+ const failure2 = dashboardFailure(operation, zero, exchange, true);
359
+ if (failure2) return failure2;
360
+ const dataJSON = chartData(exchange.body);
361
+ return dataJSON === void 0 ? queryBranch(operation, zero, "invalidResponse", "PROTOCOL") : newQueryBranch("found", { chartID: input.chartID, dataJSON });
362
+ }
363
+ };
364
+ var GetActiveUserCountsOperation = class {
365
+ /** Bind the provider client. */
366
+ constructor(client) {
367
+ this.client = client;
368
+ }
369
+ client;
370
+ /** Return the user counts Query definition. */
371
+ definition() {
372
+ return GetActiveUserCountsDefinition;
373
+ }
374
+ /** Validate the date range and return the provider count series. */
375
+ async invoke(call, input) {
376
+ const operation = "getActiveUserCounts";
377
+ const zero = { startDate: "", endDate: "", metric: "", intervalDays: 0, dates: [], series: [] };
378
+ const metric = input.metric || "active";
379
+ const interval = input.intervalDays || 1;
380
+ const span = parseDate(input.endDate, false) - parseDate(input.startDate, false);
381
+ if (!(span >= 0 && span <= 366 * 864e5) || !["active", "new"].includes(metric) || ![1, 7, 30].includes(interval))
382
+ return queryBranch(operation, zero, "defect", "VALIDATION");
383
+ const exchange = await this.client.getDashboard(call, "/api/2/users", {
384
+ start: [input.startDate],
385
+ end: [input.endDate],
386
+ m: [metric],
387
+ i: [String(interval)]
388
+ });
389
+ const failure2 = dashboardFailure(operation, zero, exchange);
390
+ if (failure2) return failure2;
391
+ const result = countSeriesSchema.safeParse(decodeJSON(exchange.body));
392
+ if (!result.success) return queryBranch(operation, zero, "invalidResponse", "PROTOCOL");
393
+ const { xValues: dates, series } = result.data.data;
394
+ if (series.some((row) => (row?.length ?? 0) !== dates.length))
395
+ return queryBranch(operation, zero, "invalidResponse", "PROTOCOL");
396
+ return newQueryBranch("counted", {
397
+ startDate: input.startDate,
398
+ endDate: input.endDate,
399
+ metric,
400
+ intervalDays: interval,
401
+ dates,
402
+ series: series.map((row) => row?.map((count) => count ?? 0) ?? [])
403
+ });
404
+ }
405
+ };
406
+ var GetUserActivityOperation = class {
407
+ /** Bind the provider client. */
408
+ constructor(client) {
409
+ this.client = client;
410
+ }
411
+ client;
412
+ /** Return the user activity Query definition. */
413
+ definition() {
414
+ return GetUserActivityDefinition;
415
+ }
416
+ /** Validate the page selection and return an activity summary. */
417
+ async invoke(call, input) {
418
+ const operation = "getUserActivity";
419
+ const zero = { amplitudeID: "", userID: "", eventCount: 0, sessionCount: 0, returnedEvents: 0 };
420
+ const limit = input.limit || 100;
421
+ const offset = input.offset ?? 0;
422
+ const direction = input.direction || "latest";
423
+ const digits = input.amplitudeID.replace(/^0+/, "");
424
+ if (!/^[0-9]+$/.test(input.amplitudeID) || !digits || digits.length > 20 || BigInt(digits) > 2n ** 64n - 1n || !Number.isInteger(limit) || limit < 1 || limit > 1e3 || !Number.isInteger(offset) || offset < 0 || offset > 1e6 || !["latest", "earliest"].includes(direction))
425
+ return queryBranch(operation, zero, "defect", "VALIDATION");
426
+ const exchange = await this.client.getDashboard(call, "/api/2/useractivity", {
427
+ user: [input.amplitudeID],
428
+ offset: [String(offset)],
429
+ limit: [String(limit)],
430
+ direction: [direction]
431
+ });
432
+ const failure2 = dashboardFailure(operation, zero, exchange, true);
433
+ if (failure2) return failure2;
434
+ const result = activitySchema.safeParse(decodeJSON(exchange.body));
435
+ if (!result.success) return queryBranch(operation, zero, "invalidResponse", "PROTOCOL");
436
+ const { userData, events } = result.data;
437
+ return newQueryBranch("found", {
438
+ amplitudeID: input.amplitudeID,
439
+ userID: userData.user_id ?? "",
440
+ eventCount: userData.num_events ?? 0,
441
+ sessionCount: userData.num_sessions ?? 0,
442
+ returnedEvents: events.length,
443
+ ...events.length ? { eventTypes: events.map((event) => event.event_type) } : {}
444
+ });
445
+ }
446
+ };
447
+ var TrackEventOperation = class {
448
+ /** Bind the provider client. */
449
+ constructor(client) {
450
+ this.client = client;
451
+ }
452
+ client;
453
+ /** Return the event upload Mutation definition. */
454
+ definition() {
455
+ return TrackEventDefinition;
456
+ }
457
+ /** Use the Dex call ID as the provider deduplication key. */
458
+ idempotencyKey(callId) {
459
+ return callId;
460
+ }
461
+ /** Upload one event and preserve the insert ID on retry. */
462
+ async invoke(call, input) {
463
+ const operation = "trackEvent";
464
+ const zero = { userID: "", eventType: "", insertID: "" };
465
+ const properties = Object.entries(input.eventProperties ?? {});
466
+ if (!isValidUserSearch(input.userID) || Buffer.byteLength(input.userID) < 5 || !isValidUserSearch(input.eventType) || properties.some(([name, value]) => !isValidUserSearch(name) || !isValidPropertyValue(value)))
467
+ return mutationBranch(operation, zero, "defect", "VALIDATION");
468
+ const apiKey = await this.client.ingestionKey(call);
469
+ if (apiKey === void 0) return ingestionAuthFailure(operation, zero, call);
470
+ const insertID = call.idempotencyKey ?? "";
471
+ const event = {
472
+ user_id: input.userID,
473
+ event_type: input.eventType,
474
+ insert_id: insertID,
475
+ ...properties.length ? { event_properties: Object.fromEntries(properties) } : {}
476
+ };
477
+ const payload = Buffer.from(encodeProviderJSON({ api_key: apiKey, events: [event] }));
478
+ if (payload.length > 1024 * 1024) return mutationBranch(operation, zero, "defect", "VALIDATION");
479
+ const exchange = await this.client.postIngestion(call, "/2/httpapi", "application/json", payload);
480
+ const failure2 = ingestionFailure(operation, zero, call, exchange);
481
+ if (failure2) return failure2;
482
+ const response = decodeJSON(exchange.body);
483
+ if (!isObject(response) || response.code !== 200 || response.events_ingested !== 1)
484
+ return newMutationRetry(operationFailure(operation, "PROTOCOL"));
485
+ return newMutationBranch(
486
+ "tracked",
487
+ { userID: input.userID, eventType: input.eventType, insertID },
488
+ receipt(call, insertID)
489
+ );
490
+ }
491
+ };
492
+ var IdentifyUserOperation = class {
493
+ /** Bind the provider client. */
494
+ constructor(client) {
495
+ this.client = client;
496
+ }
497
+ client;
498
+ /** Return the property replacement Mutation definition. */
499
+ definition() {
500
+ return IdentifyUserDefinition;
501
+ }
502
+ /** Use the Dex call ID to identify retries of the replacement. */
503
+ idempotencyKey(callId) {
504
+ return callId;
505
+ }
506
+ /** Set the named property, including to an empty string. */
507
+ invoke(call, input) {
508
+ return updateProperty(this.client, call, input, "$set", input.propertyValue);
509
+ }
510
+ };
511
+ var UnsetUserPropertyOperation = class {
512
+ /** Bind the provider client. */
513
+ constructor(client) {
514
+ this.client = client;
515
+ }
516
+ client;
517
+ /** Return the property removal Mutation definition. */
518
+ definition() {
519
+ return UnsetUserPropertyDefinition;
520
+ }
521
+ /** Use the Dex call ID to identify retries of the removal. */
522
+ idempotencyKey(callId) {
523
+ return callId;
524
+ }
525
+ /** Remove the named property through the Identify API. */
526
+ invoke(call, input) {
527
+ return updateProperty(this.client, call, input, "$unset", "-");
528
+ }
529
+ };
530
+ function operationFailure(operation, kind) {
531
+ return { provider: "amplitude", operation, kind, message: `Amplitude ${operation} failed: ${kind}` };
532
+ }
533
+ function queryBranch(operation, zero, branch, kind) {
534
+ return newQueryBranch(branch, zero, {}, operationFailure(operation, kind));
535
+ }
536
+ function dashboardFailure(operation, zero, exchange, hasMissing = false) {
537
+ if (exchange.error === "credential") return queryBranch(operation, zero, "defect", "AUTHENTICATION");
538
+ if (exchange.error === "request") return newQueryRetry(operationFailure(operation, "TRANSPORT"));
539
+ if (exchange.status === 429) return newQueryRetry(operationFailure(operation, "RATE_LIMIT"), exchange.retryAfterMs);
540
+ if (exchange.status === 408 || exchange.status >= 500)
541
+ return newQueryRetry(operationFailure(operation, "AVAILABILITY"), exchange.retryAfterMs);
542
+ if (exchange.status === 404 && hasMissing) return newQueryBranch("missing", zero);
543
+ if (exchange.status !== 200) return queryBranch(operation, zero, "providerRejected", "PROVIDER_REJECTION");
544
+ if (exchange.error === "tooLarge") return queryBranch(operation, zero, "invalidResponse", "RESPONSE_TOO_LARGE");
545
+ if (exchange.error === "credentialEcho") return queryBranch(operation, zero, "invalidResponse", "PROTOCOL");
546
+ return void 0;
547
+ }
548
+ var utf8 = new TextDecoder("utf-8", { fatal: true });
549
+ function decodeJSON(body) {
550
+ try {
551
+ return JSON.parse(utf8.decode(body));
552
+ } catch {
553
+ return void 0;
554
+ }
555
+ }
556
+ function chartData(body) {
557
+ const document = decodeJSON(body);
558
+ if (!isObject(document) || !isObject(document.data) && !Array.isArray(document.data)) return void 0;
559
+ const tokens = utf8.decode(body).match(/"(?:[^"\\]|\\.)*"|[{}[\]:,]|[^"{}[\]:, \t\r\n]+/g) ?? [];
560
+ let depth = 0;
561
+ let start = -1;
562
+ let data;
563
+ for (const [index, token] of tokens.entries()) {
564
+ if (depth === 1 && token.startsWith('"') && tokens[index + 1] === ":" && JSON.parse(token) === "data")
565
+ start = index + 2;
566
+ if (token === "{" || token === "[") depth++;
567
+ if (token === "}" || token === "]") depth--;
568
+ if (start >= 0 && index >= start && depth === 1 && (token === "}" || token === "]")) {
569
+ data = tokens.slice(start, index + 1).join("");
570
+ start = -1;
571
+ }
572
+ }
573
+ return data;
574
+ }
575
+ function parseDate(value, separated) {
576
+ const match = (separated ? /^(\d{4})-(\d{2})-(\d{2})$/ : /^(\d{4})(\d{2})(\d{2})$/).exec(value);
577
+ if (!match) return NaN;
578
+ const date = /* @__PURE__ */ new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`);
579
+ return Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== `${match[1]}-${match[2]}-${match[3]}` ? NaN : date.getTime();
580
+ }
581
+ var countSeriesSchema = z.object({ data: z.object({
582
+ xValues: z.array(z.string().refine((value) => !Number.isNaN(parseDate(value, true)))).max(366),
583
+ series: z.array(z.array(z.number().nullable()).nullable()).max(100)
584
+ }) });
585
+ var activitySchema = z.object({
586
+ userData: z.object({
587
+ user_id: z.string().nullish(),
588
+ num_events: z.int().nonnegative().nullish(),
589
+ num_sessions: z.int().nonnegative().nullish()
590
+ }),
591
+ events: z.array(z.object({
592
+ event_type: z.string().min(1).refine((value) => Buffer.byteLength(value) <= 1024)
593
+ })).max(5e3)
594
+ });
595
+ async function updateProperty(client, call, input, action, value) {
596
+ const operation = action === "$set" ? "identifyUser" : "unsetUserProperty";
597
+ const zero = { userID: "", propertyName: "" };
598
+ if (!isValidUserSearch(input.userID) || !isValidUserSearch(input.propertyName) || !isValidPropertyValue(value))
599
+ return mutationBranch(operation, zero, "defect", "VALIDATION");
600
+ const apiKey = await client.ingestionKey(call);
601
+ if (apiKey === void 0) return ingestionAuthFailure(operation, zero, call);
602
+ const identification = encodeProviderJSON({
603
+ user_id: input.userID,
604
+ user_properties: { [action]: { [input.propertyName]: value } }
605
+ });
606
+ const form = encodeQueryValues({ api_key: [apiKey], identification: [identification] });
607
+ const exchange = await client.postIngestion(call, "/identify", "application/x-www-form-urlencoded", Buffer.from(form));
608
+ const failure2 = ingestionFailure(operation, zero, call, exchange);
609
+ if (failure2) return failure2;
610
+ if (exchange.body.length) {
611
+ const response = decodeJSON(exchange.body);
612
+ if (!isObject(response) || response.code !== 200 || response.error != null && response.error !== "")
613
+ return newMutationRetry(operationFailure(operation, "PROTOCOL"));
614
+ }
615
+ return newMutationBranch(
616
+ action === "$set" ? "identified" : "unset",
617
+ { userID: input.userID, propertyName: input.propertyName },
618
+ receipt(call, input.userID)
619
+ );
620
+ }
621
+ function ingestionAuthFailure(operation, zero, call) {
622
+ return call.context.attempt > 1 ? newMutationRetry(operationFailure(operation, "AUTHENTICATION")) : mutationBranch(operation, zero, "defect", "AUTHENTICATION");
623
+ }
624
+ function ingestionFailure(operation, zero, call, exchange) {
625
+ if (exchange.error) return newMutationRetry(operationFailure(operation, "TRANSPORT"), exchange.retryAfterMs);
626
+ if (exchange.status === 429) return newMutationRetry(operationFailure(operation, "RATE_LIMIT"), exchange.retryAfterMs);
627
+ if (exchange.status === 408 || exchange.status >= 500)
628
+ return newMutationRetry(operationFailure(operation, "AVAILABILITY"), exchange.retryAfterMs);
629
+ if (exchange.status === 200) return void 0;
630
+ if (call.context.attempt <= 1 && [400, 401, 403, 404, 411, 413, 414, 415, 422].includes(exchange.status)) {
631
+ const response = decodeJSON(exchange.body);
632
+ if (isObject(response) && typeof response.error === "string" && response.error && (response.code ?? 0) === 0 && (response.events_ingested ?? 0) === 0)
633
+ return mutationBranch(operation, zero, "providerRejected", "PROVIDER_REJECTION");
634
+ }
635
+ return newMutationRetry(operationFailure(operation, "TRANSPORT"));
636
+ }
637
+ function mutationBranch(operation, zero, branch, kind) {
638
+ return newMutationBranch(branch, zero, {}, operationFailure(operation, kind));
639
+ }
640
+ function receipt(call, providerObjectId) {
641
+ return { callId: call.id, idempotencyKey: call.idempotencyKey, provider: "amplitude", providerObjectId };
642
+ }
643
+ function isValidPropertyValue(value) {
644
+ return Buffer.byteLength(value) <= 8192 && Buffer.from(value).toString() === value;
645
+ }
646
+ function encodeProviderJSON(value) {
647
+ return JSON.stringify(value).replace(
648
+ /[<>&\u2028\u2029]/g,
649
+ (character) => "\\u" + character.charCodeAt(0).toString(16).padStart(4, "0")
650
+ );
651
+ }
165
652
 
166
653
  // src/project.ts
167
654
  function newProjectConnection2(project, connectionName) {
168
655
  return newProjectConnection(project, connectionName, (loadedProject, name) => {
169
656
  const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "amplitude" && entry.connectionName === name);
170
657
  if (!selected) throw new TypeError("Amplitude project connection is not configured");
171
- const fields = z.strictObject({ baseUrl: z.string().optional(), timeout: z.union([z.string(), z.number().int()]).optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
658
+ const fields = z2.strictObject({ baseUrl: z2.string().optional(), timeout: z2.union([z2.string(), z2.number().int()]).optional(), maxResponseBytes: z2.number().int().optional() }).parse(selected.configuration);
172
659
  const timeoutMs = typeof fields.timeout === "number" ? Math.ceil(fields.timeout / 1e6) : fields.timeout ? parseDurationMilliseconds(fields.timeout) : void 0;
173
660
  const config = {
174
661
  ...fields.baseUrl ? { baseUrl: fields.baseUrl } : {},
@@ -199,11 +686,52 @@ function parseDurationMilliseconds(value) {
199
686
  return milliseconds;
200
687
  }
201
688
  export {
689
+ ActiveUserCountsInputSchema,
690
+ ActiveUserCountsSchema,
202
691
  AmplitudeClient,
692
+ ChartResultSchema,
203
693
  ConfigSchema,
204
694
  Connection,
205
695
  ConnectorID,
696
+ CredentialMaterialError,
697
+ GetActiveUserCountsBranch,
698
+ GetActiveUserCountsBranchCounted,
699
+ GetActiveUserCountsBranchDefect,
700
+ GetActiveUserCountsBranchInvalidResponse,
701
+ GetActiveUserCountsBranchProviderRejected,
702
+ GetActiveUserCountsDefinition,
703
+ GetActiveUserCountsMetadata,
704
+ GetActiveUserCountsOperation,
705
+ GetUserActivityBranch,
706
+ GetUserActivityBranchDefect,
707
+ GetUserActivityBranchFound,
708
+ GetUserActivityBranchInvalidResponse,
709
+ GetUserActivityBranchMissing,
710
+ GetUserActivityBranchProviderRejected,
711
+ GetUserActivityDefinition,
712
+ GetUserActivityInputSchema,
713
+ GetUserActivityMetadata,
714
+ GetUserActivityOperation,
715
+ IdentifiedUserSchema,
716
+ IdentifyUserBranch,
717
+ IdentifyUserBranchDefect,
718
+ IdentifyUserBranchIdentified,
719
+ IdentifyUserBranchProviderRejected,
720
+ IdentifyUserDefinition,
721
+ IdentifyUserInputSchema,
722
+ IdentifyUserMetadata,
723
+ IdentifyUserOperation,
206
724
  ProviderID,
725
+ QueryChartBranch,
726
+ QueryChartBranchDefect,
727
+ QueryChartBranchFound,
728
+ QueryChartBranchInvalidResponse,
729
+ QueryChartBranchMissing,
730
+ QueryChartBranchProviderRejected,
731
+ QueryChartDefinition,
732
+ QueryChartInputSchema,
733
+ QueryChartMetadata,
734
+ QueryChartOperation,
207
735
  SearchUsersBranch,
208
736
  SearchUsersBranchDefect,
209
737
  SearchUsersBranchInvalidResponse,
@@ -213,10 +741,35 @@ export {
213
741
  SearchUsersInputSchema,
214
742
  SearchUsersMetadata,
215
743
  SearchUsersOperation,
744
+ TrackEventBranch,
745
+ TrackEventBranchDefect,
746
+ TrackEventBranchProviderRejected,
747
+ TrackEventBranchTracked,
748
+ TrackEventDefinition,
749
+ TrackEventInputSchema,
750
+ TrackEventMetadata,
751
+ TrackEventOperation,
752
+ TrackedEventSchema,
753
+ UnsetUserPropertyBranch,
754
+ UnsetUserPropertyBranchDefect,
755
+ UnsetUserPropertyBranchProviderRejected,
756
+ UnsetUserPropertyBranchUnset,
757
+ UnsetUserPropertyDefinition,
758
+ UnsetUserPropertyInputSchema,
759
+ UnsetUserPropertyMetadata,
760
+ UnsetUserPropertyOperation,
761
+ UserActivitySchema,
216
762
  UserSearchPageSchema,
217
763
  decodeCredentials,
764
+ isCredentialMaterialError,
218
765
  newConnection,
219
766
  newConnectionWithOperations,
767
+ newGetActiveUserCountsStep,
768
+ newGetUserActivityStep,
769
+ newIdentifyUserStep,
220
770
  newProjectConnection2 as newProjectConnection,
221
- newSearchUsersStep
771
+ newQueryChartStep,
772
+ newSearchUsersStep,
773
+ newTrackEventStep,
774
+ newUnsetUserPropertyStep
222
775
  };