@entrolytics/api-client 2.2.0 → 2.2.1

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 DELETED
@@ -1,1554 +0,0 @@
1
- // src/client.ts
2
- var ApiClient = class {
3
- endpoint;
4
- bearerToken;
5
- apiKey;
6
- userId;
7
- secret;
8
- fetchFn;
9
- retries;
10
- retryDelay;
11
- constructor(config = {}) {
12
- const getEnv = (key) => {
13
- if (typeof process !== "undefined" && process.env) {
14
- return process.env[key];
15
- }
16
- return void 0;
17
- };
18
- this.endpoint = config.endpoint || getEnv("ENTROLYTICS_API_ENDPOINT") || "";
19
- this.bearerToken = config.bearerToken || getEnv("ENTROLYTICS_BEARER_TOKEN");
20
- this.apiKey = config.apiKey || getEnv("ENTROLYTICS_API_KEY");
21
- this.userId = config.userId || getEnv("ENTROLYTICS_USER_ID");
22
- this.secret = config.secret || getEnv("ENTROLYTICS_SECRET");
23
- this.fetchFn = config.fetch || globalThis.fetch;
24
- this.retries = config.retries ?? 3;
25
- this.retryDelay = config.retryDelay ?? 1e3;
26
- if (!this.endpoint) {
27
- throw new Error(
28
- "Entrolytics API endpoint is required. Set ENTROLYTICS_API_ENDPOINT or pass endpoint in config."
29
- );
30
- }
31
- }
32
- /**
33
- * Update the bearer token (useful for token refresh).
34
- */
35
- setBearerToken(token) {
36
- this.bearerToken = token;
37
- }
38
- /**
39
- * Generate authentication headers.
40
- * Priority: Bearer token > API key > Legacy share token
41
- */
42
- getAuthHeaders() {
43
- const headers = {};
44
- if (this.bearerToken) {
45
- headers.Authorization = `Bearer ${this.bearerToken}`;
46
- } else if (this.apiKey) {
47
- headers["x-entrolytics-api-key"] = this.apiKey;
48
- } else if (this.userId && this.secret) {
49
- headers["x-entrolytics-share-token"] = this.createShareToken();
50
- }
51
- return headers;
52
- }
53
- /**
54
- * Create a share token for self-hosted authentication (legacy).
55
- * @deprecated Use bearerToken or apiKey instead
56
- */
57
- createShareToken() {
58
- if (!this.userId || !this.secret) {
59
- throw new Error("userId and secret are required for self-hosted authentication");
60
- }
61
- const payload = {
62
- userId: this.userId,
63
- timestamp: Date.now()
64
- };
65
- if (typeof Buffer !== "undefined") {
66
- return Buffer.from(JSON.stringify(payload)).toString("base64");
67
- } else {
68
- return btoa(JSON.stringify(payload));
69
- }
70
- }
71
- /**
72
- * Sleep helper for retry delays.
73
- */
74
- sleep(ms) {
75
- return new Promise((resolve) => setTimeout(resolve, ms));
76
- }
77
- /**
78
- * Check if error is retryable.
79
- */
80
- isRetryable(status) {
81
- return status === 0 || status === 429 || status >= 500;
82
- }
83
- /**
84
- * Build URL with query parameters.
85
- */
86
- buildUrl(path, params) {
87
- const url = new URL(path, this.endpoint);
88
- if (params) {
89
- Object.entries(params).forEach(([key, value]) => {
90
- if (value !== void 0) {
91
- url.searchParams.set(key, String(value));
92
- }
93
- });
94
- }
95
- return url.toString();
96
- }
97
- /**
98
- * Make an authenticated API request with automatic retries.
99
- */
100
- async request(path, options = {}) {
101
- const { method = "GET", body, params, headers = {} } = options;
102
- const url = this.buildUrl(path, params);
103
- let lastError = null;
104
- for (let attempt = 0; attempt <= this.retries; attempt++) {
105
- try {
106
- const fetchOptions = {
107
- method,
108
- headers: {
109
- "Content-Type": "application/json",
110
- ...this.getAuthHeaders(),
111
- ...headers
112
- }
113
- };
114
- if (body) {
115
- fetchOptions.body = JSON.stringify(body);
116
- }
117
- const response = await this.fetchFn(url, fetchOptions);
118
- const data = await response.json().catch(() => ({}));
119
- if (!response.ok) {
120
- const errorMessage = typeof data.error === "string" ? data.error : typeof data.message === "string" ? data.message : `HTTP ${response.status}`;
121
- lastError = {
122
- ok: false,
123
- status: response.status,
124
- error: errorMessage
125
- };
126
- if (this.isRetryable(response.status) && attempt < this.retries) {
127
- const delay = this.retryDelay * 2 ** attempt;
128
- await this.sleep(delay);
129
- continue;
130
- }
131
- return lastError;
132
- }
133
- return {
134
- ok: true,
135
- status: response.status,
136
- data
137
- };
138
- } catch (error) {
139
- lastError = {
140
- ok: false,
141
- status: 0,
142
- error: error instanceof Error ? error.message : "Network error"
143
- };
144
- if (attempt < this.retries) {
145
- const delay = this.retryDelay * 2 ** attempt;
146
- await this.sleep(delay);
147
- }
148
- }
149
- }
150
- return lastError ?? {
151
- ok: false,
152
- status: 0,
153
- error: "Request failed after retries"
154
- };
155
- }
156
- /**
157
- * GET request helper.
158
- */
159
- get(path, params) {
160
- return this.request(path, { method: "GET", params });
161
- }
162
- /**
163
- * POST request helper.
164
- */
165
- post(path, body) {
166
- return this.request(path, { method: "POST", body });
167
- }
168
- /**
169
- * PUT request helper.
170
- */
171
- put(path, body) {
172
- return this.request(path, { method: "PUT", body });
173
- }
174
- /**
175
- * DELETE request helper.
176
- */
177
- delete(path) {
178
- return this.request(path, { method: "DELETE" });
179
- }
180
- /**
181
- * PATCH request helper.
182
- */
183
- patch(path, body) {
184
- return this.request(path, { method: "PATCH", body });
185
- }
186
- };
187
-
188
- // src/endpoints/admin.ts
189
- function createAdminEndpoints(client) {
190
- return {
191
- /**
192
- * Get all organizations (admin only)
193
- */
194
- getOrgs: () => client.get("/admin/orgs"),
195
- /**
196
- * Get organization details (admin only)
197
- */
198
- getOrg: ({ orgId }) => client.get(`/admin/orgs/${orgId}`),
199
- /**
200
- * Get all users (admin only)
201
- */
202
- getUsers: () => client.get("/admin/users"),
203
- /**
204
- * Get user details (admin only)
205
- */
206
- getUser: ({ userId }) => client.get(`/admin/users/${userId}`),
207
- /**
208
- * Get all websites (admin only)
209
- */
210
- getWebsites: () => client.get("/admin/websites"),
211
- /**
212
- * Get website details (admin only)
213
- */
214
- getWebsite: ({ websiteId }) => client.get(`/admin/websites/${websiteId}`),
215
- /**
216
- * Run admin setup
217
- */
218
- setup: () => client.post("/admin/setup", {})
219
- };
220
- }
221
-
222
- // src/endpoints/auth.ts
223
- function createAuthEndpoints(client) {
224
- return {
225
- /**
226
- * List all active CLI access tokens for the current user.
227
- */
228
- listCliTokens() {
229
- return client.get("/auth/cli/tokens");
230
- },
231
- /**
232
- * Revoke a specific CLI access token by its JTI.
233
- *
234
- * @param jti - The JWT ID of the token to revoke
235
- */
236
- revokeCliToken(jti) {
237
- return client["request"]("/auth/cli/tokens", {
238
- method: "DELETE",
239
- body: { jti }
240
- });
241
- },
242
- /**
243
- * Revoke all CLI access tokens for the current user.
244
- */
245
- revokeAllCliTokens() {
246
- return client["request"]("/auth/cli/tokens", {
247
- method: "DELETE",
248
- body: { revokeAll: true }
249
- });
250
- }
251
- };
252
- }
253
-
254
- // src/endpoints/billing.ts
255
- function createBillingEndpoints(client) {
256
- return {
257
- /**
258
- * Get current account usage for the billing period.
259
- */
260
- getUsage() {
261
- return client.get("/billing/usage");
262
- },
263
- /**
264
- * Get account entitlements based on current plan.
265
- */
266
- getEntitlements() {
267
- return client.get("/billing/entitlements");
268
- },
269
- /**
270
- * Get current subscription details.
271
- */
272
- getSubscription() {
273
- return client.get("/billing/subscription");
274
- },
275
- /**
276
- * Create a Stripe checkout session for upgrading/changing plan.
277
- */
278
- createCheckoutSession(options) {
279
- return client.post("/billing/checkout", options);
280
- },
281
- /**
282
- * Create a Stripe billing portal session for managing subscription.
283
- */
284
- createPortalSession() {
285
- return client.post("/billing/portal");
286
- }
287
- };
288
- }
289
-
290
- // src/endpoints/boards.ts
291
- function createBoardsEndpoints(client) {
292
- return {
293
- /**
294
- * Get all boards for a website.
295
- */
296
- getBoards(websiteId) {
297
- return client.get(`/websites/${websiteId}/boards`);
298
- },
299
- /**
300
- * Get a specific board by ID.
301
- */
302
- getBoard(boardId) {
303
- return client.get(`/boards/${boardId}`);
304
- },
305
- /**
306
- * Create a new board.
307
- */
308
- createBoard(data) {
309
- return client.post("/boards", data);
310
- },
311
- /**
312
- * Update a board.
313
- */
314
- updateBoard(boardId, data) {
315
- return client.post(`/boards/${boardId}`, data);
316
- },
317
- /**
318
- * Delete a board.
319
- */
320
- deleteBoard(boardId) {
321
- return client.delete(`/boards/${boardId}`);
322
- },
323
- /**
324
- * Get all widgets for a board.
325
- */
326
- getBoardWidgets(boardId) {
327
- return client.get(`/boards/${boardId}/widgets`);
328
- },
329
- /**
330
- * Get a specific widget by ID.
331
- */
332
- getBoardWidget(boardId, widgetId) {
333
- return client.get(`/boards/${boardId}/widgets/${widgetId}`);
334
- },
335
- /**
336
- * Create a new widget on a board.
337
- */
338
- createBoardWidget(boardId, data) {
339
- return client.post(`/boards/${boardId}/widgets`, data);
340
- },
341
- /**
342
- * Update a widget.
343
- */
344
- updateBoardWidget(boardId, widgetId, data) {
345
- return client.post(`/boards/${boardId}/widgets/${widgetId}`, data);
346
- },
347
- /**
348
- * Delete a widget.
349
- */
350
- deleteBoardWidget(boardId, widgetId) {
351
- return client.delete(`/boards/${boardId}/widgets/${widgetId}`);
352
- }
353
- };
354
- }
355
-
356
- // src/endpoints/config.ts
357
- function createConfigEndpoints(client) {
358
- return {
359
- /**
360
- * Get system configuration
361
- */
362
- get: () => client.get("/config")
363
- };
364
- }
365
-
366
- // src/endpoints/events.ts
367
- function createEventsEndpoints(client) {
368
- return {
369
- /**
370
- * Get event data statistics.
371
- */
372
- getEventDataStats(websiteId, params) {
373
- return client.get(`/websites/${websiteId}/event-data/stats`, params);
374
- },
375
- /**
376
- * Get event data events (distinct event names).
377
- */
378
- getEventDataEvents(websiteId, params) {
379
- return client.get(`/websites/${websiteId}/event-data/events`, params);
380
- },
381
- /**
382
- * Get event data fields for a specific event.
383
- */
384
- getEventDataFields(websiteId, params) {
385
- return client.get(`/websites/${websiteId}/event-data/fields`, params);
386
- },
387
- /**
388
- * Get event data values for a specific field.
389
- */
390
- getEventDataValues(websiteId, params) {
391
- return client.get(`/websites/${websiteId}/event-data/values`, params);
392
- },
393
- /**
394
- * Get event data properties breakdown.
395
- */
396
- getEventDataProperties(websiteId, params) {
397
- return client.get(`/websites/${websiteId}/event-data/properties`, params);
398
- },
399
- /**
400
- * Get specific event data by ID.
401
- */
402
- getEventData(websiteId, eventId) {
403
- return client.get(`/websites/${websiteId}/event-data/${eventId}`);
404
- },
405
- /**
406
- * Get session data properties.
407
- */
408
- getSessionDataProperties(websiteId, params) {
409
- return client.get(`/websites/${websiteId}/session-data/properties`, params);
410
- },
411
- getSessionDataValues(websiteId, params) {
412
- return client.get(`/websites/${websiteId}/session-data/values`, params);
413
- },
414
- /**
415
- * Send a test event to verify setup.
416
- */
417
- sendTestEvent(websiteId) {
418
- return client.post("/send", {
419
- type: "event",
420
- payload: {
421
- website: websiteId,
422
- name: "cli_test_event",
423
- data: { source: "entro-cli", timestamp: Date.now() }
424
- }
425
- });
426
- }
427
- };
428
- }
429
-
430
- // src/endpoints/integrations.ts
431
- function createIntegrationsEndpoints(client) {
432
- return {
433
- /**
434
- * Handle WordPress integration
435
- */
436
- wordpress: (params) => client.post("/integrations/wordpress", params.data)
437
- };
438
- }
439
-
440
- // src/endpoints/links.ts
441
- function createLinksEndpoints(client) {
442
- return {
443
- /**
444
- * Get all links.
445
- */
446
- getLinks() {
447
- return client.get("/links");
448
- },
449
- /**
450
- * Get links for an organization.
451
- */
452
- getOrgLinks(orgId) {
453
- return client.get(`/orgs/${orgId}/links`);
454
- },
455
- /**
456
- * Create a new link.
457
- */
458
- createLink(orgId, data) {
459
- return client.post(`/orgs/${orgId}/links`, data);
460
- },
461
- /**
462
- * Get a link by ID.
463
- */
464
- getLink(linkId) {
465
- return client.get(`/links/${linkId}`);
466
- },
467
- /**
468
- * Update a link.
469
- */
470
- updateLink(linkId, data) {
471
- return client.post(`/links/${linkId}`, data);
472
- },
473
- /**
474
- * Delete a link.
475
- */
476
- deleteLink(linkId) {
477
- return client.delete(`/links/${linkId}`);
478
- },
479
- /**
480
- * Get link statistics.
481
- */
482
- getLinkStats(linkId) {
483
- return client.get(`/links/${linkId}/stats`);
484
- }
485
- };
486
- }
487
-
488
- // src/endpoints/me.ts
489
- function createMeEndpoints(client) {
490
- return {
491
- /**
492
- * Get current user profile.
493
- */
494
- getMe() {
495
- return client.get("/me");
496
- },
497
- /**
498
- * Update current user's password.
499
- */
500
- updateMyPassword(data) {
501
- return client.post("/me/password", data);
502
- },
503
- /**
504
- * Get current user's websites.
505
- */
506
- getMyWebsites() {
507
- return client.get("/me/websites");
508
- },
509
- /**
510
- * Get current user's organizations.
511
- */
512
- getMyOrgs() {
513
- return client.get("/me/orgs");
514
- }
515
- };
516
- }
517
-
518
- // src/endpoints/orgs.ts
519
- function createOrgsEndpoints(client) {
520
- return {
521
- /**
522
- * Get all organizations for the current user.
523
- */
524
- getOrgs() {
525
- return client.get("/orgs");
526
- },
527
- /**
528
- * Create a new organization.
529
- */
530
- createOrg(data) {
531
- return client.post("/orgs", data);
532
- },
533
- /**
534
- * Join an organization using access code.
535
- */
536
- joinOrg(data) {
537
- return client.post("/orgs/join", data);
538
- },
539
- /**
540
- * Get an organization by ID.
541
- */
542
- getOrg(orgId) {
543
- return client.get(`/orgs/${orgId}`);
544
- },
545
- /**
546
- * Update an organization.
547
- */
548
- updateOrg(orgId, data) {
549
- return client.post(`/orgs/${orgId}`, data);
550
- },
551
- /**
552
- * Delete an organization.
553
- */
554
- deleteOrg(orgId) {
555
- return client.delete(`/orgs/${orgId}`);
556
- },
557
- /**
558
- * Get organization members.
559
- */
560
- getOrgUsers(orgId) {
561
- return client.get(`/orgs/${orgId}/users`);
562
- },
563
- /**
564
- * Add a user to an organization.
565
- */
566
- addOrgUser(orgId, data) {
567
- return client.post(`/orgs/${orgId}/users`, data);
568
- },
569
- /**
570
- * Update an organization member's role.
571
- */
572
- updateOrgUser(orgId, userId, data) {
573
- return client.post(`/orgs/${orgId}/users/${userId}`, data);
574
- },
575
- /**
576
- * Remove a user from an organization.
577
- */
578
- removeOrgUser(orgId, userId) {
579
- return client.delete(`/orgs/${orgId}/users/${userId}`);
580
- },
581
- /**
582
- * Get organization websites.
583
- */
584
- getOrgWebsites(orgId) {
585
- return client.get(`/orgs/${orgId}/websites`);
586
- },
587
- /**
588
- * Add a website to an organization.
589
- */
590
- addOrgWebsite(orgId, data) {
591
- return client.post(`/orgs/${orgId}/websites`, data);
592
- },
593
- /**
594
- * Remove a website from an organization.
595
- */
596
- removeOrgWebsite(orgId, websiteId) {
597
- return client.delete(`/orgs/${orgId}/websites/${websiteId}`);
598
- }
599
- };
600
- }
601
-
602
- // src/endpoints/pixels.ts
603
- function createPixelsEndpoints(client) {
604
- return {
605
- /**
606
- * Get all pixels.
607
- */
608
- getPixels() {
609
- return client.get("/pixels");
610
- },
611
- /**
612
- * Get pixels for an organization.
613
- */
614
- getOrgPixels(orgId) {
615
- return client.get(`/orgs/${orgId}/pixels`);
616
- },
617
- /**
618
- * Create a new pixel.
619
- */
620
- createPixel(orgId, data) {
621
- return client.post(`/orgs/${orgId}/pixels`, data);
622
- },
623
- /**
624
- * Get a pixel by ID.
625
- */
626
- getPixel(pixelId) {
627
- return client.get(`/pixels/${pixelId}`);
628
- },
629
- /**
630
- * Update a pixel.
631
- */
632
- updatePixel(pixelId, data) {
633
- return client.post(`/pixels/${pixelId}`, data);
634
- },
635
- /**
636
- * Delete a pixel.
637
- */
638
- deletePixel(pixelId) {
639
- return client.delete(`/pixels/${pixelId}`);
640
- }
641
- };
642
- }
643
-
644
- // src/endpoints/reports.ts
645
- function createReportsEndpoints(client) {
646
- return {
647
- /**
648
- * Get all reports for a website.
649
- */
650
- getReports(websiteId) {
651
- return client.get(`/websites/${websiteId}/reports`);
652
- },
653
- /**
654
- * Create a new report.
655
- */
656
- createReport(data) {
657
- return client.post("/reports", data);
658
- },
659
- /**
660
- * Get a report by ID.
661
- */
662
- getReport(reportId) {
663
- return client.get(`/reports/${reportId}`);
664
- },
665
- /**
666
- * Update a report.
667
- */
668
- updateReport(reportId, data) {
669
- return client.post(`/reports/${reportId}`, data);
670
- },
671
- /**
672
- * Delete a report.
673
- */
674
- deleteReport(reportId) {
675
- return client.delete(`/reports/${reportId}`);
676
- },
677
- /**
678
- * Run a funnel report.
679
- */
680
- runFunnelReport(params) {
681
- const { websiteId, steps, window = 30, startAt, endAt, ...rest } = params;
682
- return client.post("/reports/funnel", {
683
- websiteId,
684
- parameters: {
685
- startDate: startAt,
686
- endDate: endAt,
687
- window,
688
- steps
689
- },
690
- filters: rest
691
- });
692
- },
693
- /**
694
- * Run a retention report.
695
- */
696
- runRetentionReport(params) {
697
- const { websiteId, startAt, endAt, timezone, ...rest } = params;
698
- return client.post("/reports/retention", {
699
- websiteId,
700
- parameters: {
701
- startDate: startAt,
702
- endDate: endAt,
703
- timezone
704
- },
705
- filters: rest
706
- });
707
- },
708
- /**
709
- * Run a journey/flow report.
710
- */
711
- runJourneyReport(params) {
712
- const { websiteId, startAt, endAt, steps = 5, startStep, endStep, ...rest } = params;
713
- return client.post("/reports/journey", {
714
- websiteId,
715
- parameters: {
716
- startDate: startAt,
717
- endDate: endAt,
718
- steps,
719
- startStep,
720
- endStep
721
- },
722
- filters: rest
723
- });
724
- },
725
- /**
726
- * Run a goals report.
727
- */
728
- runGoalReport(params) {
729
- const { websiteId, startAt, endAt, type, value, ...rest } = params;
730
- return client.post("/reports/goal", {
731
- websiteId,
732
- parameters: {
733
- startDate: startAt,
734
- endDate: endAt,
735
- type,
736
- value
737
- },
738
- filters: rest
739
- });
740
- },
741
- /**
742
- * Run an attribution report.
743
- */
744
- runAttributionReport(params) {
745
- const { websiteId, startAt, endAt, model, type, step, currency, ...rest } = params;
746
- return client.post("/reports/attribution", {
747
- websiteId,
748
- parameters: {
749
- startDate: startAt,
750
- endDate: endAt,
751
- model,
752
- type,
753
- step,
754
- currency
755
- },
756
- filters: rest
757
- });
758
- },
759
- /**
760
- * Run a revenue report.
761
- */
762
- runRevenueReport(params) {
763
- const { websiteId, startAt, endAt, currency = "USD", ...rest } = params;
764
- return client.post("/reports/revenue", {
765
- websiteId,
766
- parameters: {
767
- startDate: startAt,
768
- endDate: endAt,
769
- currency
770
- },
771
- filters: rest
772
- });
773
- },
774
- /**
775
- * Run a UTM report.
776
- */
777
- runUTMReport(params) {
778
- const { websiteId, startAt, endAt, ...rest } = params;
779
- return client.post("/reports/utm", {
780
- websiteId,
781
- parameters: {
782
- startDate: startAt,
783
- endDate: endAt
784
- },
785
- filters: rest
786
- });
787
- },
788
- /**
789
- * Run a breakdown report.
790
- * @param property - Field to break down by (path, referrer, browser, device, os, country, etc.)
791
- */
792
- runBreakdownReport(params) {
793
- const { websiteId, startAt, endAt, property, ...rest } = params;
794
- return client.post("/reports/breakdown", {
795
- websiteId,
796
- parameters: {
797
- startDate: startAt,
798
- endDate: endAt,
799
- property
800
- },
801
- filters: rest
802
- });
803
- }
804
- };
805
- }
806
-
807
- // src/endpoints/segments.ts
808
- function createSegmentsEndpoints(client) {
809
- return {
810
- /**
811
- * Get all segments for a website.
812
- */
813
- getSegments(websiteId) {
814
- return client.get(`/websites/${websiteId}/segments`);
815
- },
816
- /**
817
- * Create a new segment.
818
- */
819
- createSegment(websiteId, data) {
820
- return client.post(`/websites/${websiteId}/segments`, data);
821
- },
822
- /**
823
- * Get a segment by ID.
824
- */
825
- getSegment(websiteId, segmentId) {
826
- return client.get(`/websites/${websiteId}/segments/${segmentId}`);
827
- },
828
- /**
829
- * Update a segment.
830
- */
831
- updateSegment(websiteId, segmentId, data) {
832
- return client.post(`/websites/${websiteId}/segments/${segmentId}`, data);
833
- },
834
- /**
835
- * Delete a segment.
836
- */
837
- deleteSegment(websiteId, segmentId) {
838
- return client.delete(`/websites/${websiteId}/segments/${segmentId}`);
839
- }
840
- };
841
- }
842
-
843
- // src/endpoints/sessions.ts
844
- function createSessionsEndpoints(client) {
845
- return {
846
- /**
847
- * Get website sessions.
848
- */
849
- getWebsiteSessions(websiteId, params) {
850
- return client.get(`/websites/${websiteId}/sessions`, params);
851
- },
852
- /**
853
- * Get session statistics.
854
- */
855
- getWebsiteSessionStats(websiteId, params) {
856
- return client.get(`/websites/${websiteId}/sessions/stats`, params);
857
- },
858
- /**
859
- * Get weekly session traffic.
860
- */
861
- getWeeklyTraffic(websiteId, params) {
862
- return client.get(`/websites/${websiteId}/sessions/weekly`, params);
863
- },
864
- /**
865
- * Get a specific session.
866
- */
867
- getSession(websiteId, sessionId) {
868
- return client.get(`/websites/${websiteId}/sessions/${sessionId}`);
869
- },
870
- /**
871
- * Get session activity (pageviews and events).
872
- */
873
- getSessionActivity(websiteId, sessionId, params) {
874
- return client.get(
875
- `/websites/${websiteId}/sessions/${sessionId}/activity`,
876
- params
877
- );
878
- },
879
- /**
880
- * Get session properties (custom data).
881
- */
882
- getSessionProperties(websiteId, sessionId) {
883
- return client.get(`/websites/${websiteId}/sessions/${sessionId}/properties`);
884
- }
885
- };
886
- }
887
-
888
- // src/endpoints/users.ts
889
- function createUsersEndpoints(client) {
890
- return {
891
- /**
892
- * Get all users (admin only).
893
- */
894
- getUsers() {
895
- return client.get("/users");
896
- },
897
- /**
898
- * Create a new user (admin only).
899
- */
900
- createUser(data) {
901
- return client.post("/users", data);
902
- },
903
- /**
904
- * Get a user by ID.
905
- */
906
- getUser(userId) {
907
- return client.get(`/users/${userId}`);
908
- },
909
- /**
910
- * Update a user.
911
- */
912
- updateUser(userId, data) {
913
- return client.post(`/users/${userId}`, data);
914
- },
915
- /**
916
- * Delete a user (admin only).
917
- */
918
- deleteUser(userId) {
919
- return client.delete(`/users/${userId}`);
920
- },
921
- /**
922
- * Get websites belonging to a user.
923
- */
924
- getUserWebsites(userId) {
925
- return client.get(`/users/${userId}/websites`);
926
- },
927
- /**
928
- * Get user usage statistics.
929
- */
930
- getUserUsage(userId, params) {
931
- return client.get(`/users/${userId}/usage`, params);
932
- }
933
- };
934
- }
935
-
936
- // src/endpoints/webhooks.ts
937
- function createWebhooksEndpoints(client) {
938
- return {
939
- /**
940
- * Handle Clerk webhook
941
- */
942
- clerk: (params) => client.post("/webhooks/clerk", params.data)
943
- };
944
- }
945
-
946
- // src/endpoints/websites.ts
947
- function createWebsitesEndpoints(client) {
948
- return {
949
- /**
950
- * Get all websites.
951
- */
952
- getWebsites() {
953
- return client.get("/websites").then((response) => {
954
- if (response.data) {
955
- response.data = response.data.map((site) => ({
956
- ...site,
957
- id: site.id || site.websiteId
958
- }));
959
- }
960
- return response;
961
- });
962
- },
963
- /**
964
- * Create a new website.
965
- */
966
- createWebsite(data) {
967
- return client.post("/websites", data).then((response) => {
968
- if (response.data) {
969
- response.data.id = response.data.id || response.data.websiteId;
970
- }
971
- return response;
972
- });
973
- },
974
- /**
975
- * Get a website by ID.
976
- */
977
- getWebsite(websiteId) {
978
- return client.get(`/websites/${websiteId}`).then((response) => {
979
- if (response.data) {
980
- response.data.id = response.data.id || response.data.websiteId;
981
- }
982
- return response;
983
- });
984
- },
985
- /**
986
- * Update a website.
987
- */
988
- updateWebsite(websiteId, data) {
989
- return client.post(`/websites/${websiteId}`, data);
990
- },
991
- /**
992
- * Delete a website.
993
- */
994
- deleteWebsite(websiteId) {
995
- return client.delete(`/websites/${websiteId}`);
996
- },
997
- /**
998
- * Reset a website's data.
999
- */
1000
- resetWebsite(websiteId) {
1001
- return client.post(`/websites/${websiteId}/reset`);
1002
- },
1003
- /**
1004
- * Transfer website ownership.
1005
- */
1006
- transferWebsite(websiteId, data) {
1007
- return client.post(`/websites/${websiteId}/transfer`, data);
1008
- },
1009
- /**
1010
- * Get website statistics.
1011
- */
1012
- getWebsiteStats(websiteId, params) {
1013
- return client.get(`/websites/${websiteId}/stats`, params);
1014
- },
1015
- /**
1016
- * Get website pageviews data.
1017
- */
1018
- getWebsitePageviews(websiteId, params) {
1019
- return client.get(`/websites/${websiteId}/pageviews`, params);
1020
- },
1021
- /**
1022
- * Get website metrics (URLs, referrers, browsers, etc.).
1023
- */
1024
- getWebsiteMetrics(websiteId, params) {
1025
- return client.get(`/websites/${websiteId}/metrics`, params);
1026
- },
1027
- /**
1028
- * Get expanded metrics (with additional details).
1029
- */
1030
- getWebsiteExpandedMetrics(websiteId, params) {
1031
- return client.get(`/websites/${websiteId}/metrics/expanded`, params);
1032
- },
1033
- /**
1034
- * Get website events.
1035
- */
1036
- getWebsiteEvents(websiteId, params) {
1037
- return client.get(`/websites/${websiteId}/events`, params);
1038
- },
1039
- /**
1040
- * Get events time series.
1041
- */
1042
- getWebsiteEventsSeries(websiteId, params) {
1043
- return client.get(`/websites/${websiteId}/events/series`, params);
1044
- },
1045
- /**
1046
- * Get active visitors count.
1047
- */
1048
- getWebsiteActive(websiteId) {
1049
- return client.get(`/websites/${websiteId}/active`);
1050
- },
1051
- /**
1052
- * Get website date range (first and last event dates).
1053
- */
1054
- getWebsiteDateRange(websiteId) {
1055
- return client.get(`/websites/${websiteId}/daterange`);
1056
- },
1057
- /**
1058
- * Get website values for a specific field.
1059
- */
1060
- getWebsiteValues(websiteId, params) {
1061
- return client.get(`/websites/${websiteId}/values`, params);
1062
- },
1063
- /**
1064
- * Get realtime data.
1065
- */
1066
- getRealtimeData(websiteId) {
1067
- return client.get(`/realtime/${websiteId}`);
1068
- },
1069
- /**
1070
- * Export website data.
1071
- */
1072
- exportWebsiteData(websiteId, params) {
1073
- return client.get(`/websites/${websiteId}/export`, params);
1074
- },
1075
- /**
1076
- * Get website ingest mode configuration.
1077
- */
1078
- getWebsiteMode(websiteId) {
1079
- return client.get(`/websites/${websiteId}/mode`);
1080
- },
1081
- /**
1082
- * Set website ingest mode (auto, node, or edge).
1083
- */
1084
- setWebsiteMode(websiteId, mode) {
1085
- return client.post(`/websites/${websiteId}/mode`, { ingestMode: mode });
1086
- },
1087
- /**
1088
- * Get routing health status.
1089
- */
1090
- getRoutingHealth() {
1091
- return client.get("/health/routing");
1092
- },
1093
- /**
1094
- * Get routing statistics.
1095
- */
1096
- getRoutingStats(params) {
1097
- return client.get("/routing/stats", params);
1098
- },
1099
- // ========================================================================
1100
- // Phase 2: Web Vitals Endpoints (NG only)
1101
- // ========================================================================
1102
- /**
1103
- * Get Web Vitals statistics for a website.
1104
- * Note: Only available in entrolytics.
1105
- */
1106
- getWebsiteVitals(websiteId, params) {
1107
- return client.get(`/websites/${websiteId}/vitals`, params);
1108
- },
1109
- /**
1110
- * Get individual Web Vital events.
1111
- * Note: Only available in entrolytics.
1112
- */
1113
- getWebsiteVitalEvents(websiteId, params) {
1114
- return client.get(`/websites/${websiteId}/vitals/events`, params);
1115
- },
1116
- /**
1117
- * Track a Web Vital metric (send to collection endpoint).
1118
- * Note: Only available in entrolytics.
1119
- */
1120
- trackVital(websiteId, data) {
1121
- return client.post("/collect/vitals", {
1122
- website: websiteId,
1123
- ...data
1124
- });
1125
- },
1126
- /**
1127
- * Track multiple Web Vitals metrics in batch.
1128
- * Note: Only available in entrolytics.
1129
- */
1130
- trackVitalsBatch(websiteId, vitals) {
1131
- return client.post("/collect/vitals", {
1132
- website: websiteId,
1133
- vitals
1134
- });
1135
- },
1136
- // ========================================================================
1137
- // Phase 2: Form Analytics Endpoints (NG only)
1138
- // ========================================================================
1139
- /**
1140
- * Get form analytics for a website.
1141
- * Note: Only available in entrolytics.
1142
- */
1143
- getWebsiteForms(websiteId, params) {
1144
- return client.get(`/websites/${websiteId}/forms`, params);
1145
- },
1146
- /**
1147
- * Get field-level analytics for a specific form.
1148
- * Note: Only available in entrolytics.
1149
- */
1150
- getFormFields(websiteId, formId, params) {
1151
- return client.get(`/websites/${websiteId}/forms/${formId}/fields`, params);
1152
- },
1153
- /**
1154
- * Get individual form events.
1155
- * Note: Only available in entrolytics.
1156
- */
1157
- getFormEvents(websiteId, params) {
1158
- return client.get(`/websites/${websiteId}/forms/events`, params);
1159
- },
1160
- /**
1161
- * Track a form event (send to collection endpoint).
1162
- * Note: Only available in entrolytics.
1163
- */
1164
- trackFormEvent(websiteId, data) {
1165
- return client.post("/collect/forms", {
1166
- website: websiteId,
1167
- ...data
1168
- });
1169
- },
1170
- /**
1171
- * Track multiple form events in batch.
1172
- * Note: Only available in entrolytics.
1173
- */
1174
- trackFormEventsBatch(websiteId, events) {
1175
- return client.post("/collect/forms", {
1176
- website: websiteId,
1177
- events
1178
- });
1179
- },
1180
- // ========================================================================
1181
- // Phase 2: Deployment Tracking Endpoints (NG only)
1182
- // ========================================================================
1183
- /**
1184
- * Get deployments for a website.
1185
- * Note: Only available in entrolytics.
1186
- */
1187
- getWebsiteDeployments(websiteId, params) {
1188
- return client.get(`/websites/${websiteId}/deployments`, params);
1189
- },
1190
- /**
1191
- * Get a specific deployment.
1192
- * Note: Only available in entrolytics.
1193
- */
1194
- getDeployment(websiteId, deployId) {
1195
- return client.get(`/websites/${websiteId}/deployments/${deployId}`);
1196
- },
1197
- /**
1198
- * Compare two deployments.
1199
- * Note: Only available in entrolytics.
1200
- */
1201
- compareDeployments(websiteId, currentDeployId, previousDeployId) {
1202
- return client.get(`/websites/${websiteId}/deployments/${currentDeployId}/compare`, {
1203
- previous: previousDeployId
1204
- });
1205
- },
1206
- /**
1207
- * Set/register a deployment context.
1208
- * Note: Only available in entrolytics.
1209
- */
1210
- setDeployment(websiteId, data) {
1211
- return client.post(`/websites/${websiteId}/deployments`, data);
1212
- }
1213
- };
1214
- }
1215
-
1216
- // src/index.ts
1217
- import {
1218
- PLANS,
1219
- PLAN_FEATURES,
1220
- USAGE_THRESHOLDS,
1221
- BILLING_ERRORS,
1222
- API_ENDPOINTS,
1223
- DEFAULT_API_HOST,
1224
- ENV_VAR_NAMES,
1225
- CLI_CONFIG,
1226
- EVENT_TYPES,
1227
- VITAL_TYPES,
1228
- VITAL_RATINGS,
1229
- VITAL_THRESHOLDS,
1230
- NAVIGATION_TYPES,
1231
- FORM_EVENT_TYPES,
1232
- FORM_FIELD_TYPES,
1233
- DEPLOYMENT_SOURCES,
1234
- DEPLOYMENT_ENV_VARS,
1235
- HTTP_STATUS,
1236
- API_ROUTES,
1237
- ONBOARDING_STEPS,
1238
- CLI_TOKEN_STATUS,
1239
- USER_ROLES,
1240
- FRAMEWORK_PACKAGES,
1241
- FRAMEWORK_PATTERNS,
1242
- RATE_LIMITS,
1243
- ERROR_MESSAGES,
1244
- SUCCESS_MESSAGES,
1245
- getEnvVarNames,
1246
- getFrameworkPackage,
1247
- isValidFramework,
1248
- getApiRoute,
1249
- getPlan,
1250
- isPlanFeatureEnabled,
1251
- getPlanLimit,
1252
- isUsageWarning,
1253
- isUsageCritical,
1254
- getVitalRating,
1255
- detectDeploymentContext
1256
- } from "@entrolytics/shared";
1257
-
1258
- // src/runtime.ts
1259
- function detectRuntime() {
1260
- if (
1261
- // @ts-ignore - Edge Runtime global
1262
- typeof EdgeRuntime !== "undefined" || // @ts-ignore - Vercel Edge Runtime
1263
- globalThis.EdgeRuntime !== void 0 || // @ts-ignore - Netlify Edge Functions use Deno
1264
- typeof Deno !== "undefined" || // @ts-ignore - Cloudflare Workers
1265
- typeof WebAssembly !== "undefined" && typeof Response !== "undefined" && !process?.versions?.node
1266
- ) {
1267
- return "edge";
1268
- }
1269
- if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) {
1270
- return "node";
1271
- }
1272
- return "unknown";
1273
- }
1274
- function isNodeRuntime() {
1275
- return detectRuntime() === "node";
1276
- }
1277
- function isEdgeRuntime() {
1278
- return detectRuntime() === "edge";
1279
- }
1280
- function getRuntimeCapabilities() {
1281
- const runtime = detectRuntime();
1282
- return {
1283
- runtime,
1284
- isNode: runtime === "node",
1285
- isEdge: runtime === "edge",
1286
- supportsFileSystem: runtime === "node",
1287
- supportsWebCrypto: typeof crypto !== "undefined" && typeof crypto.subtle !== "undefined",
1288
- supportsFetch: typeof fetch !== "undefined",
1289
- supportsStreams: typeof ReadableStream !== "undefined"
1290
- };
1291
- }
1292
- function assertRuntime(expected) {
1293
- const actual = detectRuntime();
1294
- if (actual !== expected) {
1295
- throw new Error(
1296
- `Expected ${expected} runtime, but detected ${actual}. This code requires ${expected} runtime to function correctly.`
1297
- );
1298
- }
1299
- }
1300
-
1301
- // src/edge-helpers.ts
1302
- function getEdgeEnv(key, defaultValue) {
1303
- if (typeof process !== "undefined" && process.env) {
1304
- const value = process.env[key];
1305
- if (value !== void 0) return value;
1306
- }
1307
- if (typeof Deno !== "undefined" && typeof Deno.env !== "undefined") {
1308
- try {
1309
- return Deno.env.get(key) || defaultValue;
1310
- } catch {
1311
- }
1312
- }
1313
- return defaultValue;
1314
- }
1315
- function requireEdgeEnv(key) {
1316
- const value = getEdgeEnv(key);
1317
- if (!value) {
1318
- throw new Error(`Required environment variable ${key} is not set`);
1319
- }
1320
- return value;
1321
- }
1322
- function createEdgeFetch(defaultOptions = {}) {
1323
- const {
1324
- retries = 3,
1325
- retryDelay = 1e3,
1326
- timeout = 3e4,
1327
- ...fetchDefaults
1328
- } = defaultOptions;
1329
- return async function edgeFetch(input, options) {
1330
- const finalRetries = options?.retries ?? retries;
1331
- const finalDelay = options?.retryDelay ?? retryDelay;
1332
- const finalTimeout = options?.timeout ?? timeout;
1333
- const finalOptions = { ...fetchDefaults, ...options };
1334
- let lastError;
1335
- for (let attempt = 0; attempt <= finalRetries; attempt++) {
1336
- try {
1337
- const controller = new AbortController();
1338
- const timeoutId = setTimeout(() => controller.abort(), finalTimeout);
1339
- const response = await fetch(input, {
1340
- ...finalOptions,
1341
- signal: controller.signal
1342
- });
1343
- clearTimeout(timeoutId);
1344
- if (response.ok || response.status >= 400 && response.status < 500) {
1345
- return response;
1346
- }
1347
- lastError = new Error(`HTTP ${response.status}: ${response.statusText}`);
1348
- } catch (error) {
1349
- lastError = error instanceof Error ? error : new Error(String(error));
1350
- if (lastError.name === "AbortError") {
1351
- throw new Error(`Request timeout after ${finalTimeout}ms`);
1352
- }
1353
- }
1354
- if (attempt < finalRetries) {
1355
- const delay = finalDelay * Math.pow(2, attempt);
1356
- await new Promise((resolve) => setTimeout(resolve, delay));
1357
- }
1358
- }
1359
- throw lastError || new Error("Request failed");
1360
- };
1361
- }
1362
- function getRegionInfo() {
1363
- if (getEdgeEnv("VERCEL")) {
1364
- return {
1365
- provider: "vercel",
1366
- region: getEdgeEnv("VERCEL_REGION"),
1367
- isEdge: getEdgeEnv("VERCEL_EDGE_RUNTIME") === "1"
1368
- };
1369
- }
1370
- if (typeof Deno !== "undefined" && getEdgeEnv("NETLIFY")) {
1371
- return {
1372
- provider: "netlify",
1373
- region: getEdgeEnv("NETLIFY_REGION"),
1374
- isEdge: true
1375
- };
1376
- }
1377
- if (typeof caches !== "undefined" && typeof WebAssembly !== "undefined") {
1378
- return {
1379
- provider: "cloudflare",
1380
- region: void 0,
1381
- // Cloudflare doesn't expose region
1382
- isEdge: true
1383
- };
1384
- }
1385
- return {
1386
- provider: "unknown",
1387
- isEdge: false
1388
- };
1389
- }
1390
- function getGeoFromRequest(request) {
1391
- const headers = request.headers;
1392
- const vercelCountry = headers.get("x-vercel-ip-country");
1393
- if (vercelCountry) {
1394
- return {
1395
- country: vercelCountry,
1396
- region: headers.get("x-vercel-ip-country-region"),
1397
- city: headers.get("x-vercel-ip-city"),
1398
- latitude: headers.get("x-vercel-ip-latitude"),
1399
- longitude: headers.get("x-vercel-ip-longitude")
1400
- };
1401
- }
1402
- const cfCountry = headers.get("cf-ipcountry");
1403
- if (cfCountry) {
1404
- return {
1405
- country: cfCountry,
1406
- region: headers.get("cf-region"),
1407
- city: headers.get("cf-city"),
1408
- latitude: headers.get("cf-latitude"),
1409
- longitude: headers.get("cf-longitude")
1410
- };
1411
- }
1412
- return {
1413
- country: void 0,
1414
- region: void 0,
1415
- city: void 0,
1416
- latitude: void 0,
1417
- longitude: void 0
1418
- };
1419
- }
1420
- function getClientIp(request) {
1421
- const headers = request.headers;
1422
- return headers.get("x-forwarded-for")?.split(",")[0]?.trim() || headers.get("x-real-ip") || headers.get("cf-connecting-ip") || headers.get("x-vercel-forwarded-for") || void 0;
1423
- }
1424
-
1425
- // src/index.ts
1426
- function getClient(config) {
1427
- const apiClient = new ApiClient(config);
1428
- const admin = createAdminEndpoints(apiClient);
1429
- const auth = createAuthEndpoints(apiClient);
1430
- const billing = createBillingEndpoints(apiClient);
1431
- const config_endpoints = createConfigEndpoints(apiClient);
1432
- const me = createMeEndpoints(apiClient);
1433
- const users = createUsersEndpoints(apiClient);
1434
- const orgs = createOrgsEndpoints(apiClient);
1435
- const websites = createWebsitesEndpoints(apiClient);
1436
- const sessions = createSessionsEndpoints(apiClient);
1437
- const events = createEventsEndpoints(apiClient);
1438
- const reports = createReportsEndpoints(apiClient);
1439
- const segments = createSegmentsEndpoints(apiClient);
1440
- const links = createLinksEndpoints(apiClient);
1441
- const pixels = createPixelsEndpoints(apiClient);
1442
- const boards = createBoardsEndpoints(apiClient);
1443
- const webhooks = createWebhooksEndpoints(apiClient);
1444
- const integrations = createIntegrationsEndpoints(apiClient);
1445
- return {
1446
- // Auth
1447
- auth,
1448
- // Me
1449
- ...me,
1450
- // Users
1451
- ...users,
1452
- // Organizations
1453
- ...orgs,
1454
- // Websites
1455
- ...websites,
1456
- // Sessions
1457
- ...sessions,
1458
- // Events
1459
- ...events,
1460
- // Reports
1461
- ...reports,
1462
- // Segments
1463
- ...segments,
1464
- // Links
1465
- ...links,
1466
- // Pixels
1467
- ...pixels,
1468
- // Boards
1469
- ...boards,
1470
- // Config
1471
- getConfig: config_endpoints.get,
1472
- // Admin
1473
- admin,
1474
- // Webhooks
1475
- webhooks,
1476
- // Integrations
1477
- integrations,
1478
- // Billing
1479
- billing
1480
- };
1481
- }
1482
- var index_default = getClient;
1483
- export {
1484
- API_ENDPOINTS,
1485
- API_ROUTES,
1486
- ApiClient,
1487
- BILLING_ERRORS,
1488
- CLI_CONFIG,
1489
- CLI_TOKEN_STATUS,
1490
- DEFAULT_API_HOST,
1491
- DEPLOYMENT_ENV_VARS,
1492
- DEPLOYMENT_SOURCES,
1493
- ENV_VAR_NAMES,
1494
- ERROR_MESSAGES,
1495
- EVENT_TYPES,
1496
- FORM_EVENT_TYPES,
1497
- FORM_FIELD_TYPES,
1498
- FRAMEWORK_PACKAGES,
1499
- FRAMEWORK_PATTERNS,
1500
- HTTP_STATUS,
1501
- NAVIGATION_TYPES,
1502
- ONBOARDING_STEPS,
1503
- PLANS,
1504
- PLAN_FEATURES,
1505
- RATE_LIMITS,
1506
- SUCCESS_MESSAGES,
1507
- USAGE_THRESHOLDS,
1508
- USER_ROLES,
1509
- VITAL_RATINGS,
1510
- VITAL_THRESHOLDS,
1511
- VITAL_TYPES,
1512
- assertRuntime,
1513
- createAdminEndpoints,
1514
- createAuthEndpoints,
1515
- createBillingEndpoints,
1516
- createBoardsEndpoints,
1517
- createConfigEndpoints,
1518
- createEdgeFetch,
1519
- createEventsEndpoints,
1520
- createIntegrationsEndpoints,
1521
- createLinksEndpoints,
1522
- createMeEndpoints,
1523
- createOrgsEndpoints,
1524
- createPixelsEndpoints,
1525
- createReportsEndpoints,
1526
- createSegmentsEndpoints,
1527
- createSessionsEndpoints,
1528
- createUsersEndpoints,
1529
- createWebhooksEndpoints,
1530
- createWebsitesEndpoints,
1531
- index_default as default,
1532
- detectDeploymentContext,
1533
- detectRuntime,
1534
- getApiRoute,
1535
- getClient,
1536
- getClientIp,
1537
- getEdgeEnv,
1538
- getEnvVarNames,
1539
- getFrameworkPackage,
1540
- getGeoFromRequest,
1541
- getPlan,
1542
- getPlanLimit,
1543
- getRegionInfo,
1544
- getRuntimeCapabilities,
1545
- getVitalRating,
1546
- isEdgeRuntime,
1547
- isNodeRuntime,
1548
- isPlanFeatureEnabled,
1549
- isUsageCritical,
1550
- isUsageWarning,
1551
- isValidFramework,
1552
- requireEdgeEnv
1553
- };
1554
- //# sourceMappingURL=index.js.map