@zerodot/google-analytics 0.0.0-stage → 1.0.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.cjs ADDED
@@ -0,0 +1,1162 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let zod = require("zod");
3
+ let _zerodot_node_sdk = require("@zerodot/node-sdk");
4
+ // src/api.ts
5
+ const ANALYTICS_OAUTH2_CREDENTIAL = "google_analytics.oauth2";
6
+ const ANALYTICS_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
7
+ /** The Data API of Google Analytics 4. */
8
+ const DATA_API = "https://analyticsdata.googleapis.com";
9
+ /** The Reporting API v4 of Universal Analytics. It also has the user activity search. */
10
+ const REPORTING_API = "https://analyticsreporting.googleapis.com";
11
+ /** The Admin API. The credential check uses it. */
12
+ const ADMIN_API = "https://analyticsadmin.googleapis.com";
13
+ const text = (value) => typeof value === "string" && value !== "" ? value : void 0;
14
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15
+ /** The access token of a credential. The server refreshes it. */
16
+ function analyticsToken(credential) {
17
+ if (credential?.type === "google_analytics.oauth2") {
18
+ const token = text(credential.data.accessToken);
19
+ if (!token) throw new Error("The Google Analytics credential is not connected to an account yet");
20
+ return token;
21
+ }
22
+ throw new Error("The node needs a Google Analytics credential");
23
+ }
24
+ const HINTS = {
25
+ 401: " Connect the credential again.",
26
+ 403: " Check that the account can see the property or view, and turn on the Google Analytics API in the Google Cloud project.",
27
+ 404: " Check the property ID or the view ID.",
28
+ 429: " Google limits the number of requests. Try again later."
29
+ };
30
+ /** A clear error from a Google answer: `{ error: { code, message, status } }`. */
31
+ function analyticsError(status, answer, action) {
32
+ const error = isObject(answer) && isObject(answer.error) ? answer.error : {};
33
+ const message = text(error.message) ?? "no message";
34
+ const code = text(error.status);
35
+ const hint = HINTS[status] ?? "";
36
+ return /* @__PURE__ */ new Error(`Google Analytics could not ${action} (${status}${code ? ` ${code}` : ""}): ${message}.${hint}`);
37
+ }
38
+ const BASE = {
39
+ data: DATA_API,
40
+ reporting: REPORTING_API,
41
+ admin: ADMIN_API
42
+ };
43
+ function urlOf(request) {
44
+ const url = new URL(`${BASE[request.api]}${request.path}`);
45
+ for (const [key, value] of Object.entries(request.query ?? {})) if (value !== void 0 && value !== "") url.searchParams.set(key, value);
46
+ return url.toString();
47
+ }
48
+ /** One call with a JSON answer. The error text never has the token. */
49
+ async function callAnalytics(token, request, options) {
50
+ const json = request.body ? JSON.stringify(request.body) : void 0;
51
+ const response = await fetch(urlOf(request), {
52
+ method: request.method,
53
+ headers: {
54
+ authorization: `Bearer ${token}`,
55
+ accept: "application/json",
56
+ ...json ? { "content-type": "application/json" } : {}
57
+ },
58
+ body: json,
59
+ redirect: "error",
60
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
61
+ });
62
+ const answer = await response.json().catch(() => null);
63
+ if (!response.ok) throw analyticsError(response.status, answer, request.action);
64
+ return answer;
65
+ }
66
+ // src/icon.ts
67
+ const ANALYTICS_ICON = (0, _zerodot_node_sdk.fileIcon)(require("url").pathToFileURL(__filename).href, "../google-analytics.svg");
68
+ // src/credential.ts
69
+ const TIMEOUT_MS = 1e4;
70
+ /** Google sign-in. `access_type=offline` and `prompt=consent` give a refresh token. */
71
+ const GOOGLE_OAUTH2 = {
72
+ authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
73
+ tokenUrl: "https://oauth2.googleapis.com/token",
74
+ scopes: [ANALYTICS_SCOPE],
75
+ authQuery: {
76
+ access_type: "offline",
77
+ prompt: "consent"
78
+ },
79
+ authentication: "body",
80
+ pkce: true
81
+ };
82
+ /** Fields that only the server writes, after the user connects the account. */
83
+ const OAUTH2_TOKEN_FIELDS = [
84
+ "accessToken",
85
+ "refreshToken",
86
+ "expiresAt",
87
+ "tokenType",
88
+ "grantedScope"
89
+ ];
90
+ /** Lists one account summary. A 401 or a 403 throws with the text of Google. */
91
+ async function check(credential) {
92
+ const options = {
93
+ signal: AbortSignal.timeout(TIMEOUT_MS),
94
+ timeoutMs: TIMEOUT_MS
95
+ };
96
+ await callAnalytics(analyticsToken(credential), {
97
+ api: "admin",
98
+ method: "GET",
99
+ path: "/v1beta/accountSummaries",
100
+ query: { pageSize: "1" },
101
+ action: "check the credential"
102
+ }, options);
103
+ }
104
+ const analyticsOAuth2Credential = {
105
+ type: ANALYTICS_OAUTH2_CREDENTIAL,
106
+ label: "Google Analytics OAuth2",
107
+ fields: zod.z.object({
108
+ clientId: zod.z.string().min(1).meta({ placeholder: "…apps.googleusercontent.com" }),
109
+ clientSecret: zod.z.string().min(1),
110
+ accessToken: zod.z.string().min(1).optional(),
111
+ refreshToken: zod.z.string().min(1).optional(),
112
+ /** ISO 8601 time. */
113
+ expiresAt: zod.z.iso.datetime().optional(),
114
+ tokenType: zod.z.string().min(1).optional(),
115
+ grantedScope: zod.z.string().optional()
116
+ }),
117
+ secretFields: [
118
+ "clientSecret",
119
+ "accessToken",
120
+ "refreshToken"
121
+ ],
122
+ serverFields: [...OAUTH2_TOKEN_FIELDS],
123
+ oauth2: GOOGLE_OAUTH2,
124
+ icon: "Analytics01Icon",
125
+ iconUrl: ANALYTICS_ICON,
126
+ test: check
127
+ };
128
+ // src/config.ts
129
+ const RESOURCES = ["report", "userActivity"];
130
+ const OPERATIONS_OF = {
131
+ report: ["get"],
132
+ userActivity: ["search"]
133
+ };
134
+ const PROPERTY_TYPES = ["ga4", "universal"];
135
+ const DATE_RANGES = [
136
+ "last7days",
137
+ "last30days",
138
+ "today",
139
+ "yesterday",
140
+ "lastCalendarWeek",
141
+ "lastCalendarMonth",
142
+ "custom"
143
+ ];
144
+ const ACTIVITY_TYPES = [
145
+ "ECOMMERCE",
146
+ "EVENT",
147
+ "GOAL",
148
+ "PAGEVIEW",
149
+ "SCREENVIEW"
150
+ ];
151
+ /** The most rows of one `runReport` page. */
152
+ const GA4_PAGE_SIZE = 1e5;
153
+ const valuesOf = (options) => options.map(([value]) => value);
154
+ const labelsOf = (options) => Object.fromEntries(options.map(([value, label]) => [value, label]));
155
+ const GA4_DIMENSIONS = [
156
+ ["browser", "Browser"],
157
+ ["campaignName", "Campaign"],
158
+ ["city", "City"],
159
+ ["country", "Country"],
160
+ ["date", "Date"],
161
+ ["deviceCategory", "Device Category"],
162
+ ["itemName", "Item Name"],
163
+ ["language", "Language"],
164
+ ["pageLocation", "Page Location"],
165
+ ["sourceMedium", "Source / Medium"],
166
+ ["other", "Other dimensions…"]
167
+ ];
168
+ const GA4_METRICS = [
169
+ ["active1DayUsers", "1 Day Active Users"],
170
+ ["active28DayUsers", "28 Day Active Users"],
171
+ ["active7DayUsers", "7 Day Active Users"],
172
+ ["checkouts", "Checkouts"],
173
+ ["eventCount", "Events"],
174
+ ["screenPageViews", "Page Views"],
175
+ ["userEngagementDuration", "Session Duration"],
176
+ ["sessions", "Sessions"],
177
+ ["sessionsPerUser", "Sessions per User"],
178
+ ["totalUsers", "Total Users"],
179
+ ["other", "Other metrics…"],
180
+ ["custom", "Custom metric…"]
181
+ ];
182
+ const UA_DIMENSIONS = [
183
+ ["ga:browser", "Browser"],
184
+ ["ga:campaign", "Campaign"],
185
+ ["ga:city", "City"],
186
+ ["ga:country", "Country"],
187
+ ["ga:date", "Date"],
188
+ ["ga:deviceCategory", "Device Category"],
189
+ ["ga:productName", "Item Name"],
190
+ ["ga:language", "Language"],
191
+ ["ga:pagePath", "Page"],
192
+ ["ga:sourceMedium", "Source / Medium"],
193
+ ["other", "Other dimensions…"]
194
+ ];
195
+ const UA_METRICS = [
196
+ ["ga:productCheckouts", "Checkouts"],
197
+ ["ga:totalEvents", "Events"],
198
+ ["ga:pageviews", "Page Views"],
199
+ ["ga:sessionDuration", "Session Duration"],
200
+ ["ga:sessions", "Sessions"],
201
+ ["ga:sessionsPerUser", "Sessions per User"],
202
+ ["ga:users", "Total Users"],
203
+ ["other", "Other metrics…"],
204
+ ["custom", "Custom metric…"]
205
+ ];
206
+ const ga4Dimension = zod.z.enum(valuesOf(GA4_DIMENSIONS)).default("date").meta({
207
+ title: "Dimension",
208
+ labels: labelsOf(GA4_DIMENSIONS)
209
+ });
210
+ const ga4Metric = zod.z.enum(valuesOf(GA4_METRICS)).default("totalUsers").meta({
211
+ title: "Metric",
212
+ labels: labelsOf(GA4_METRICS)
213
+ });
214
+ const valueType = zod.z.enum(["doubleValue", "int64Value"]).default("doubleValue").meta({
215
+ title: "Value Type",
216
+ labels: {
217
+ doubleValue: "Double Value",
218
+ int64Value: "Integer Value"
219
+ }
220
+ });
221
+ const numericOperation = zod.z.enum([
222
+ "EQUAL",
223
+ "GREATER_THAN",
224
+ "GREATER_THAN_OR_EQUAL",
225
+ "LESS_THAN",
226
+ "LESS_THAN_OR_EQUAL"
227
+ ]).default("EQUAL").meta({
228
+ title: "Operation",
229
+ labels: {
230
+ EQUAL: "Equal",
231
+ GREATER_THAN: "Greater Than",
232
+ GREATER_THAN_OR_EQUAL: "Greater than or Equal",
233
+ LESS_THAN: "Less Than",
234
+ LESS_THAN_OR_EQUAL: "Less than or Equal"
235
+ }
236
+ });
237
+ const filterGroup$1 = zod.z.enum(["andGroup", "orGroup"]).default("andGroup").meta({
238
+ title: "Filter Expression Type",
239
+ labels: {
240
+ andGroup: "And Group",
241
+ orGroup: "Or Group"
242
+ }
243
+ });
244
+ const nameField = zod.z.string().optional().meta({
245
+ title: "Name",
246
+ description: "The API name. Used when the list name is \"other\""
247
+ });
248
+ const ga4MetricItem = zod.z.object({
249
+ listName: ga4Metric,
250
+ name: nameField.meta({ description: "The API name of the metric. For \"Custom metric\", any name for the column" }),
251
+ expression: zod.z.string().optional().meta({
252
+ title: "Expression",
253
+ description: "A mathematical expression for derived metrics. For example, the metric Event count per user is eventCount/totalUsers"
254
+ }),
255
+ invisible: zod.z.boolean().default(false).meta({
256
+ title: "Invisible",
257
+ description: "Whether a metric is invisible in the report response. An invisible metric has no column, but a filter, an order, or an expression can use it"
258
+ })
259
+ });
260
+ const ga4DimensionItem = zod.z.object({
261
+ listName: ga4Dimension,
262
+ name: nameField
263
+ });
264
+ const stringFilter = zod.z.object({
265
+ listName: ga4Dimension,
266
+ name: nameField,
267
+ value: zod.z.string().default(""),
268
+ caseSensitive: zod.z.boolean().default(true),
269
+ matchType: zod.z.enum([
270
+ "BEGINS_WITH",
271
+ "CONTAINS",
272
+ "ENDS_WITH",
273
+ "EXACT",
274
+ "FULL_REGEXP",
275
+ "PARTIAL_REGEXP"
276
+ ]).default("EXACT").meta({
277
+ title: "Match Type",
278
+ labels: {
279
+ BEGINS_WITH: "Begins With",
280
+ CONTAINS: "Contains Value",
281
+ ENDS_WITH: "Ends With",
282
+ EXACT: "Exact Match",
283
+ FULL_REGEXP: "Full Match for the Regular Expression",
284
+ PARTIAL_REGEXP: "Partial Match for the Regular Expression"
285
+ }
286
+ })
287
+ });
288
+ const inListFilter = zod.z.object({
289
+ listName: ga4Dimension,
290
+ name: nameField,
291
+ values: zod.z.string().default("").meta({ description: "Comma separated list of values. Must be non-empty" }),
292
+ caseSensitive: zod.z.boolean().default(true)
293
+ });
294
+ const dimensionNumericFilter = zod.z.object({
295
+ listName: ga4Dimension,
296
+ name: nameField,
297
+ valueType,
298
+ value: zod.z.string().default(""),
299
+ operation: numericOperation
300
+ });
301
+ const metricNumericFilter = zod.z.object({
302
+ listName: ga4Metric,
303
+ name: nameField,
304
+ valueType,
305
+ value: zod.z.string().default(""),
306
+ operation: numericOperation
307
+ });
308
+ const betweenFilter = zod.z.object({
309
+ listName: ga4Metric,
310
+ name: nameField,
311
+ valueType,
312
+ fromValue: zod.z.string().default(""),
313
+ toValue: zod.z.string().default("")
314
+ });
315
+ const dimensionFilters = zod.z.object({ filterExpressions: zod.z.object({
316
+ filterExpressionType: filterGroup$1,
317
+ expression: zod.z.object({
318
+ stringFilter: zod.z.array(stringFilter).default([]),
319
+ inListFilter: zod.z.array(inListFilter).default([]),
320
+ numericFilter: zod.z.array(dimensionNumericFilter).default([])
321
+ }).optional()
322
+ }).optional() });
323
+ const metricFilters = zod.z.object({ filterExpressions: zod.z.object({
324
+ filterExpressionType: filterGroup$1,
325
+ expression: zod.z.object({
326
+ betweenFilter: zod.z.array(betweenFilter).default([]),
327
+ numericFilter: zod.z.array(metricNumericFilter).default([])
328
+ }).optional()
329
+ }).optional() });
330
+ const orderBy = zod.z.object({
331
+ metricOrderBy: zod.z.array(zod.z.object({
332
+ desc: zod.z.boolean().default(false).meta({ title: "Descending" }),
333
+ metricName: zod.z.string().default("").meta({ title: "Metric Name" })
334
+ })).default([]),
335
+ dimmensionOrderBy: zod.z.array(zod.z.object({
336
+ desc: zod.z.boolean().default(false).meta({ title: "Descending" }),
337
+ dimensionName: zod.z.string().default("").meta({ title: "Dimension Name" }),
338
+ orderType: zod.z.enum([
339
+ "ALPHANUMERIC",
340
+ "CASE_INSENSITIVE_ALPHANUMERIC",
341
+ "NUMERIC",
342
+ "ORDER_TYPE_UNSPECIFIED"
343
+ ]).default("ORDER_TYPE_UNSPECIFIED").meta({
344
+ title: "Order Type",
345
+ labels: {
346
+ ALPHANUMERIC: "Alphanumeric",
347
+ CASE_INSENSITIVE_ALPHANUMERIC: "Case Insensitive Alphanumeric",
348
+ NUMERIC: "Numeric",
349
+ ORDER_TYPE_UNSPECIFIED: "Unspecified"
350
+ }
351
+ })
352
+ })).default([])
353
+ });
354
+ const ga4AdditionalFields = zod.z.object({
355
+ currencyCode: zod.z.string().optional().meta({
356
+ title: "Currency Code",
357
+ description: "A currency code in ISO4217 format, such as \"AED\", \"USD\", \"JPY\". Empty: the default currency of the property"
358
+ }),
359
+ dimensionFiltersUI: dimensionFilters.optional().meta({ title: "Dimensions Filters" }),
360
+ metricAggregations: zod.z.array(zod.z.enum([
361
+ "MAXIMUM",
362
+ "MINIMUM",
363
+ "TOTAL"
364
+ ])).default([]).meta({
365
+ title: "Metric Aggregation",
366
+ description: "Only when Simplify Output is off"
367
+ }),
368
+ metricsFiltersUI: metricFilters.optional().meta({ title: "Metrics Filters" }),
369
+ keepEmptyRows: zod.z.boolean().default(false).meta({
370
+ title: "Keep Empty Rows",
371
+ description: "Off: a row with all metrics equal to 0 is not returned. On: these rows are returned if no filter removes them"
372
+ }),
373
+ orderByUI: orderBy.optional().meta({
374
+ title: "Order By",
375
+ description: "How rows are ordered in the response"
376
+ }),
377
+ returnPropertyQuota: zod.z.boolean().default(false).meta({
378
+ title: "Return Property Quota",
379
+ description: "Return the state of the quota of the property. Only when Simplify Output is off"
380
+ })
381
+ });
382
+ const uaMetricItem = zod.z.object({
383
+ listName: zod.z.enum(valuesOf(UA_METRICS)).default("ga:users").meta({
384
+ title: "Metric",
385
+ labels: labelsOf(UA_METRICS)
386
+ }),
387
+ name: nameField.meta({ description: "The name of the metric. For \"Custom metric\", any name for the column" }),
388
+ expression: zod.z.string().optional().meta({
389
+ title: "Expression",
390
+ description: "A metric expression, for example ga:totalRefunds/ga:users"
391
+ }),
392
+ formattingType: zod.z.enum([
393
+ "CURRENCY",
394
+ "FLOAT",
395
+ "INTEGER",
396
+ "PERCENT",
397
+ "TIME"
398
+ ]).default("INTEGER").meta({
399
+ title: "Formatting Type",
400
+ description: "How the metric expression is formatted",
401
+ labels: {
402
+ CURRENCY: "Currency",
403
+ FLOAT: "Float",
404
+ INTEGER: "Integer",
405
+ PERCENT: "Percent",
406
+ TIME: "Time"
407
+ }
408
+ })
409
+ });
410
+ const uaDimension = zod.z.enum(valuesOf(UA_DIMENSIONS)).default("ga:date").meta({
411
+ title: "Dimension",
412
+ labels: labelsOf(UA_DIMENSIONS)
413
+ });
414
+ const uaDimensionItem = zod.z.object({
415
+ listName: uaDimension,
416
+ name: nameField
417
+ });
418
+ const uaDimensionFilter = zod.z.object({
419
+ listName: uaDimension,
420
+ name: nameField,
421
+ operator: zod.z.enum([
422
+ "BEGINS_WITH",
423
+ "ENDS_WITH",
424
+ "NUMERIC_EQUAL",
425
+ "EXACT",
426
+ "NUMERIC_GREATER_THAN",
427
+ "NUMERIC_LESS_THAN",
428
+ "PARTIAL",
429
+ "REGEXP"
430
+ ]).default("EXACT").meta({
431
+ title: "Operator",
432
+ description: "Operator to use in combination with the value",
433
+ labels: {
434
+ BEGINS_WITH: "Begins With",
435
+ ENDS_WITH: "Ends With",
436
+ NUMERIC_EQUAL: "Equals (Number)",
437
+ EXACT: "Exactly Matches",
438
+ NUMERIC_GREATER_THAN: "Greater Than (Number)",
439
+ NUMERIC_LESS_THAN: "Less Than (Number)",
440
+ PARTIAL: "Partly Matches",
441
+ REGEXP: "Regular Expression"
442
+ }
443
+ }),
444
+ expressions: zod.z.string().default("").meta({
445
+ title: "Value",
446
+ description: "A string or a regular expression to match against"
447
+ })
448
+ });
449
+ const uaAdditionalFields = zod.z.object({
450
+ dimensionFiltersUi: zod.z.object({ filterValues: zod.z.array(uaDimensionFilter).default([]) }).optional().meta({
451
+ title: "Dimension Filters",
452
+ description: "Dimension filters in the request"
453
+ }),
454
+ hideTotals: zod.z.boolean().default(false).meta({
455
+ title: "Hide Totals",
456
+ description: "Hide the total of all metrics for all the matching rows, for every date range"
457
+ }),
458
+ hideValueRanges: zod.z.boolean().default(false).meta({
459
+ title: "Hide Value Ranges",
460
+ description: "Hide the minimum and the maximum across all matching rows"
461
+ }),
462
+ includeEmptyRows: zod.z.boolean().default(false).meta({
463
+ title: "Include Empty Rows",
464
+ description: "Return rows where all the metrics are equal to zero"
465
+ }),
466
+ useResourceQuotas: zod.z.boolean().default(false).meta({
467
+ title: "Use Resource Quotas",
468
+ description: "Turn on resource based quotas"
469
+ })
470
+ });
471
+ const report = (extra = {}) => ({
472
+ resource: ["report"],
473
+ operation: ["get"],
474
+ ...extra
475
+ });
476
+ const GA4 = report({ propertyType: ["ga4"] });
477
+ const UNIVERSAL = report({ propertyType: ["universal"] });
478
+ const USER_ACTIVITY = {
479
+ resource: ["userActivity"],
480
+ operation: ["search"]
481
+ };
482
+ const analyticsConfig = zod.z.object({
483
+ resource: zod.z.enum(RESOURCES).default("report").meta({
484
+ labels: {
485
+ report: "Report",
486
+ userActivity: "User Activity"
487
+ },
488
+ hints: {
489
+ report: "Get the analytics data of a property or a view",
490
+ userActivity: "Get the activity of one user"
491
+ }
492
+ }),
493
+ operation: zod.z.enum(["get", "search"]).default("get").meta({
494
+ labels: {
495
+ get: "Get",
496
+ search: "Search"
497
+ },
498
+ hints: {
499
+ get: "Return the analytics data",
500
+ search: "Return user activity data"
501
+ }
502
+ }),
503
+ propertyType: zod.z.enum(PROPERTY_TYPES).default("ga4").meta({
504
+ showWhen: report(),
505
+ title: "Property Type",
506
+ description: "Google Analytics 4 is the latest version. Universal Analytics is an older version that is not fully functional after the end of June 2023",
507
+ labels: {
508
+ ga4: "Google Analytics 4",
509
+ universal: "Universal Analytics"
510
+ }
511
+ }),
512
+ propertyId: zod.z.string().optional().meta({
513
+ showWhen: GA4,
514
+ title: "Property",
515
+ description: "The ID of the property, for example 123456, or the URL of the property in Google Analytics"
516
+ }),
517
+ viewId: zod.z.string().optional().meta({
518
+ showWhen: [UNIVERSAL, USER_ACTIVITY],
519
+ title: "View",
520
+ description: "The ID of the view, for example 123456. For a report, the URL of the view in Google Analytics also works"
521
+ }),
522
+ userId: zod.z.string().optional().meta({
523
+ showWhen: USER_ACTIVITY,
524
+ title: "User ID",
525
+ description: "ID of a user"
526
+ }),
527
+ dateRange: zod.z.enum(DATE_RANGES).default("last7days").meta({
528
+ showWhen: report(),
529
+ title: "Date Range",
530
+ labels: {
531
+ last7days: "Last 7 Days",
532
+ last30days: "Last 30 Days",
533
+ today: "Today",
534
+ yesterday: "Yesterday",
535
+ lastCalendarWeek: "Last Complete Calendar Week",
536
+ lastCalendarMonth: "Last Complete Calendar Month",
537
+ custom: "Custom"
538
+ }
539
+ }),
540
+ startDate: zod.z.string().optional().meta({
541
+ showWhen: report({ dateRange: ["custom"] }),
542
+ title: "Start",
543
+ description: "A date in ISO 8601 format, for example 2026-01-31"
544
+ }),
545
+ endDate: zod.z.string().optional().meta({
546
+ showWhen: report({ dateRange: ["custom"] }),
547
+ title: "End",
548
+ description: "A date in ISO 8601 format, for example 2026-02-28"
549
+ }),
550
+ metricsGA4: zod.z.object({ metricValues: zod.z.array(ga4MetricItem).default([]) }).default({ metricValues: [{
551
+ listName: "totalUsers",
552
+ invisible: false
553
+ }] }).meta({
554
+ showWhen: GA4,
555
+ title: "Metrics",
556
+ description: "The quantitative measurements of a report. For example, the metric eventCount is the total number of events. A request allows up to 10 metrics"
557
+ }),
558
+ dimensionsGA4: zod.z.object({ dimensionValues: zod.z.array(ga4DimensionItem).default([]) }).default({ dimensionValues: [{ listName: "date" }] }).meta({
559
+ showWhen: GA4,
560
+ title: "Dimensions to split by",
561
+ description: "Dimensions are attributes of your data. For example, the dimension city is the city from which an event comes. A request allows up to 9 dimensions"
562
+ }),
563
+ metricsUA: zod.z.object({ metricValues: zod.z.array(uaMetricItem).default([]) }).default({ metricValues: [{
564
+ listName: "ga:users",
565
+ formattingType: "INTEGER"
566
+ }] }).meta({
567
+ showWhen: UNIVERSAL,
568
+ title: "Metrics",
569
+ description: "Metrics in the request"
570
+ }),
571
+ dimensionsUA: zod.z.object({ dimensionValues: zod.z.array(uaDimensionItem).default([]) }).default({ dimensionValues: [{ listName: "ga:date" }] }).meta({
572
+ showWhen: UNIVERSAL,
573
+ title: "Dimensions to split by",
574
+ description: "Dimensions are attributes of your data. For example, the dimension ga:city is the city, for example \"Paris\", from which a session comes"
575
+ }),
576
+ returnAll: zod.z.boolean().default(false).meta({
577
+ showWhen: [report(), USER_ACTIVITY],
578
+ title: "Return All",
579
+ description: "Whether to return all results or only up to a given limit"
580
+ }),
581
+ limit: zod.z.number().int().min(1).max(1e3).default(50).meta({
582
+ showWhen: [report({ returnAll: [false] }), {
583
+ ...USER_ACTIVITY,
584
+ returnAll: [false]
585
+ }],
586
+ title: "Limit",
587
+ description: "Max number of results to return. User activity allows up to 500"
588
+ }),
589
+ simple: zod.z.boolean().default(true).meta({
590
+ showWhen: report(),
591
+ title: "Simplify Output",
592
+ description: "Whether to return a simplified version of the response instead of the raw data"
593
+ }),
594
+ additionalFields: ga4AdditionalFields.default({
595
+ keepEmptyRows: false,
596
+ returnPropertyQuota: false,
597
+ metricAggregations: []
598
+ }).meta({
599
+ showWhen: GA4,
600
+ title: "Additional Fields"
601
+ }),
602
+ additionalFieldsUA: uaAdditionalFields.default({
603
+ hideTotals: false,
604
+ hideValueRanges: false,
605
+ includeEmptyRows: false,
606
+ useResourceQuotas: false
607
+ }).meta({
608
+ showWhen: UNIVERSAL,
609
+ title: "Additional Fields"
610
+ }),
611
+ activityTypes: zod.z.array(zod.z.enum(ACTIVITY_TYPES)).default([]).meta({
612
+ showWhen: USER_ACTIVITY,
613
+ title: "Activity Types",
614
+ description: "Type of activities requested",
615
+ labels: {
616
+ ECOMMERCE: "Ecommerce",
617
+ EVENT: "Event",
618
+ GOAL: "Goal",
619
+ PAGEVIEW: "Pageview",
620
+ SCREENVIEW: "Screenview"
621
+ }
622
+ }),
623
+ timeoutMs: zod.z.number().int().min(1).max(3e5).default(3e4)
624
+ }).superRefine((config, context) => {
625
+ if (!OPERATIONS_OF[config.resource].includes(config.operation)) context.addIssue({
626
+ code: "custom",
627
+ path: ["operation"],
628
+ message: `"${config.operation}" is not an operation of "${config.resource}"`
629
+ });
630
+ });
631
+ // src/request.ts
632
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
633
+ const asList$1 = (value) => Array.isArray(value) ? value : [];
634
+ const records = (value) => asList$1(value).filter(isRecord$1);
635
+ const str = (value) => typeof value === "string" ? value : "";
636
+ /** The ID of a GA4 property, from its URL, `properties/123`, or the bare number. */
637
+ function parsePropertyId(input) {
638
+ const value = (input ?? "").trim();
639
+ if (!value) throw new Error("\"propertyId\" is needed: the ID or the URL of the property");
640
+ const fromUrl = /analytics\.google\.com\/analytics.*\/p(\d+)/.exec(value)?.[1];
641
+ if (fromUrl) return fromUrl;
642
+ const fromName = /^properties\/(\d+)$/.exec(value)?.[1];
643
+ if (fromName) return fromName;
644
+ if (/^\d+$/.test(value)) return value;
645
+ throw new Error(`"${value}" is not a Google Analytics property ID or URL`);
646
+ }
647
+ /** The ID of a Universal Analytics view, from its URL or the bare number. */
648
+ function parseViewId(input) {
649
+ const value = (input ?? "").trim();
650
+ if (!value) throw new Error("\"viewId\" is needed: the ID of the view");
651
+ const fromUrl = /analytics\.google\.com\/analytics.*p(\d+)/.exec(value)?.[1];
652
+ if (fromUrl) return fromUrl;
653
+ if (/^\d+$/.test(value)) return value;
654
+ throw new Error(`"${value}" is not a Google Analytics view ID or URL`);
655
+ }
656
+ const pad = (n) => String(n).padStart(2, "0");
657
+ const isoDate = (date) => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
658
+ const addDays = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
659
+ /** A date as `YYYY-MM-DD`. A date with a time keeps its date part. */
660
+ function dateOf(value, name) {
661
+ const text = (value ?? "").trim();
662
+ const match = /^(\d{4}-\d{2}-\d{2})/.exec(text);
663
+ if (match?.[1]) return match[1];
664
+ const parsed = new Date(text);
665
+ if (!text || Number.isNaN(parsed.getTime())) throw new Error(`"${name}" is needed for a custom date range, as a date like 2026-01-31`);
666
+ return isoDate(parsed);
667
+ }
668
+ /** The date range of a period, in local time. Weeks start on Monday. */
669
+ function prepareDateRange(period, custom = {}, now = /* @__PURE__ */ new Date()) {
670
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
671
+ switch (period) {
672
+ case "today": return [{
673
+ startDate: isoDate(today),
674
+ endDate: isoDate(today)
675
+ }];
676
+ case "yesterday": {
677
+ const day = isoDate(addDays(today, -1));
678
+ return [{
679
+ startDate: day,
680
+ endDate: day
681
+ }];
682
+ }
683
+ case "lastCalendarWeek": {
684
+ const monday = addDays(today, -((today.getDay() + 6) % 7));
685
+ return [{
686
+ startDate: isoDate(addDays(monday, -7)),
687
+ endDate: isoDate(addDays(monday, -1))
688
+ }];
689
+ }
690
+ case "lastCalendarMonth": {
691
+ const first = new Date(today.getFullYear(), today.getMonth() - 1, 1);
692
+ const last = new Date(today.getFullYear(), today.getMonth(), 0);
693
+ return [{
694
+ startDate: isoDate(first),
695
+ endDate: isoDate(last)
696
+ }];
697
+ }
698
+ case "last7days": return [{
699
+ startDate: isoDate(addDays(today, -7)),
700
+ endDate: isoDate(today)
701
+ }];
702
+ case "last30days": return [{
703
+ startDate: isoDate(addDays(today, -30)),
704
+ endDate: isoDate(today)
705
+ }];
706
+ case "custom": {
707
+ const startDate = dateOf(custom.startDate, "startDate");
708
+ const endDate = dateOf(custom.endDate, "endDate");
709
+ if (startDate > endDate) throw new Error(`Parameter Start: ${startDate} cannot be after End: ${endDate}`);
710
+ return [{
711
+ startDate,
712
+ endDate
713
+ }];
714
+ }
715
+ default: throw new Error(`The period '${period}' is not supported, to specify own period use 'custom' option`);
716
+ }
717
+ }
718
+ /** Throws when a name is in the list more than once. */
719
+ function checkDuplicates(items, key, type) {
720
+ const names = items.map((item) => String(item[key]));
721
+ const duplicates = [...new Set(names.filter((name, i) => names.indexOf(name) !== i))];
722
+ if (duplicates.length > 0) throw new Error(`A ${type} is specified more than once (${duplicates.join(", ")})`);
723
+ }
724
+ /** The API name of a list entry. "other" (and "custom") use the free name field. */
725
+ function nameOf(item, kind) {
726
+ const listName = str(item.listName);
727
+ if (listName === "other") {
728
+ const name = str(item.name).trim();
729
+ if (!name) throw new Error(`"name" is needed when the ${kind} is "Other"`);
730
+ return name;
731
+ }
732
+ return listName;
733
+ }
734
+ /** A number for a filter. `doubleValue` is a JSON number, `int64Value` stays a string. */
735
+ const numberValue = (type, value) => {
736
+ const text = str(value).trim();
737
+ if (type === "doubleValue") {
738
+ const number = Number(text);
739
+ if (text === "" || !Number.isFinite(number)) throw new Error(`"${text}" is not a number`);
740
+ return { doubleValue: number };
741
+ }
742
+ if (!/^-?\d+$/.test(text)) throw new Error(`"${text}" is not an integer`);
743
+ return { int64Value: text };
744
+ };
745
+ /** One filter entry, with the field name and the kind of filter. */
746
+ function fieldOf(item, kind) {
747
+ const listName = str(item.listName);
748
+ if (listName === "other" || listName === "custom") {
749
+ const name = str(item.name).trim();
750
+ if (!name) throw new Error(`"name" is needed when the ${kind} is "${listName}"`);
751
+ return name;
752
+ }
753
+ return listName;
754
+ }
755
+ /** The filter entries of a group, in the form of the API. */
756
+ function processFilters(expression, source) {
757
+ const out = [];
758
+ for (const item of records(expression.stringFilter)) out.push({ filter: {
759
+ fieldName: fieldOf(item, source),
760
+ stringFilter: {
761
+ value: str(item.value),
762
+ caseSensitive: item.caseSensitive,
763
+ matchType: item.matchType
764
+ }
765
+ } });
766
+ for (const item of records(expression.inListFilter)) out.push({ filter: {
767
+ fieldName: fieldOf(item, source),
768
+ inListFilter: {
769
+ values: str(item.values).split(",").map((value) => value.trim()).filter((value) => value !== ""),
770
+ caseSensitive: item.caseSensitive
771
+ }
772
+ } });
773
+ for (const item of records(expression.betweenFilter)) {
774
+ const type = str(item.valueType);
775
+ out.push({ filter: {
776
+ fieldName: fieldOf(item, source),
777
+ betweenFilter: {
778
+ fromValue: numberValue(type, item.fromValue),
779
+ toValue: numberValue(type, item.toValue)
780
+ }
781
+ } });
782
+ }
783
+ for (const item of records(expression.numericFilter)) out.push({ filter: {
784
+ fieldName: fieldOf(item, source),
785
+ numericFilter: {
786
+ operation: item.operation,
787
+ value: numberValue(str(item.valueType), item.value)
788
+ }
789
+ } });
790
+ return out;
791
+ }
792
+ /** A filter group: `{ andGroup: { expressions } }`. Empty gives undefined. */
793
+ function filterGroup(ui, source) {
794
+ const group = isRecord$1(ui) && isRecord$1(ui.filterExpressions) ? ui.filterExpressions : void 0;
795
+ if (!group || !isRecord$1(group.expression)) return void 0;
796
+ const expressions = processFilters(group.expression, source);
797
+ if (expressions.length === 0) return void 0;
798
+ return { [str(group.filterExpressionType) || "andGroup"]: { expressions } };
799
+ }
800
+ function ga4Metrics(collection) {
801
+ const metrics = records(isRecord$1(collection) ? collection.metricValues : []).map((metric) => {
802
+ switch (metric.listName) {
803
+ case "other": return { name: nameOf(metric, "metric") };
804
+ case "custom": {
805
+ const out = { name: str(metric.name).trim() || "custom_metric" };
806
+ if (str(metric.expression) !== "") out.expression = metric.expression;
807
+ if (metric.invisible === true) out.invisible = true;
808
+ return out;
809
+ }
810
+ default: return { name: metric.listName };
811
+ }
812
+ });
813
+ checkDuplicates(metrics, "name", "metrics");
814
+ return metrics;
815
+ }
816
+ function ga4Dimensions(collection) {
817
+ const dimensions = records(isRecord$1(collection) ? collection.dimensionValues : []).map((dimension) => ({ name: nameOf(dimension, "dimension") }));
818
+ checkDuplicates(dimensions, "name", "dimensions");
819
+ return dimensions;
820
+ }
821
+ function orderBys(ui) {
822
+ if (!isRecord$1(ui)) return [];
823
+ return [...records(ui.metricOrderBy).map((order) => ({
824
+ desc: order.desc,
825
+ metric: { metricName: order.metricName }
826
+ })), ...records(ui.dimmensionOrderBy).map((order) => ({
827
+ desc: order.desc,
828
+ dimension: {
829
+ dimensionName: order.dimensionName,
830
+ orderType: order.orderType
831
+ }
832
+ }))];
833
+ }
834
+ /** The body of `runReport`, without `limit` and `offset`. */
835
+ function ga4Body(config, dateRanges) {
836
+ const fields = config.additionalFields;
837
+ const body = { dateRanges };
838
+ const metrics = ga4Metrics(config.metricsGA4);
839
+ if (metrics.length > 0) body.metrics = metrics;
840
+ const dimensions = ga4Dimensions(config.dimensionsGA4);
841
+ if (dimensions.length > 0) body.dimensions = dimensions;
842
+ if (fields.currencyCode) body.currencyCode = fields.currencyCode;
843
+ const dimensionFilter = filterGroup(fields.dimensionFiltersUI, "dimension");
844
+ if (dimensionFilter) body.dimensionFilter = dimensionFilter;
845
+ const metricFilter = filterGroup(fields.metricsFiltersUI, "metric");
846
+ if (metricFilter) body.metricFilter = metricFilter;
847
+ if (fields.metricAggregations.length > 0) body.metricAggregations = fields.metricAggregations;
848
+ if (fields.keepEmptyRows) body.keepEmptyRows = true;
849
+ const order = orderBys(fields.orderByUI);
850
+ if (order.length > 0) body.orderBys = order;
851
+ if (fields.returnPropertyQuota) body.returnPropertyQuota = true;
852
+ return body;
853
+ }
854
+ const runReportRequest = (propertyId, body) => ({
855
+ api: "data",
856
+ method: "POST",
857
+ path: `/v1beta/properties/${encodeURIComponent(propertyId)}:runReport`,
858
+ body,
859
+ action: "get the report"
860
+ });
861
+ /** The rows of a `runReport` answer as flat objects: dimension and metric names are the keys. */
862
+ function simplifyGA4(response) {
863
+ if (!isRecord$1(response) || !Array.isArray(response.rows)) return [];
864
+ const dimensionNames = records(response.dimensionHeaders).map((header) => str(header.name));
865
+ const metricNames = records(response.metricHeaders).map((header) => str(header.name));
866
+ const out = [];
867
+ for (const row of records(response.rows)) {
868
+ const dimensionValues = records(row.dimensionValues);
869
+ const metricValues = records(row.metricValues);
870
+ const item = {};
871
+ dimensionNames.forEach((name, index) => {
872
+ item[name] = dimensionValues[index]?.value;
873
+ });
874
+ metricNames.forEach((name, index) => {
875
+ item[name] = metricValues[index]?.value;
876
+ });
877
+ out.push(item);
878
+ }
879
+ return out;
880
+ }
881
+ function uaMetrics(collection) {
882
+ const metrics = records(isRecord$1(collection) ? collection.metricValues : []).map((metric) => {
883
+ switch (metric.listName) {
884
+ case "other": {
885
+ const name = nameOf(metric, "metric");
886
+ return {
887
+ alias: name,
888
+ expression: name
889
+ };
890
+ }
891
+ case "custom": return {
892
+ alias: str(metric.name).trim() || "custom_metric",
893
+ expression: metric.expression,
894
+ formattingType: metric.formattingType
895
+ };
896
+ default: return {
897
+ alias: metric.listName,
898
+ expression: metric.listName
899
+ };
900
+ }
901
+ });
902
+ checkDuplicates(metrics, "alias", "metrics");
903
+ return metrics;
904
+ }
905
+ /** The body of one report request of `reports:batchGet`, without `pageSize` and `pageToken`. */
906
+ function uaBody(config, dateRanges) {
907
+ const fields = config.additionalFieldsUA;
908
+ const body = {
909
+ viewId: parseViewId(config.viewId),
910
+ dateRanges
911
+ };
912
+ const metrics = uaMetrics(config.metricsUA);
913
+ if (metrics.length > 0) body.metrics = metrics;
914
+ const dimensions = records(isRecord$1(config.dimensionsUA) ? config.dimensionsUA.dimensionValues : []).map((dimension) => ({ name: nameOf(dimension, "dimension") }));
915
+ checkDuplicates(dimensions, "name", "dimensions");
916
+ if (dimensions.length > 0) body.dimensions = dimensions;
917
+ const filters = records(fields.dimensionFiltersUi?.filterValues).map((filter) => ({
918
+ dimensionName: nameOf(filter, "dimension"),
919
+ operator: filter.operator,
920
+ expressions: [filter.expressions]
921
+ }));
922
+ if (filters.length > 0) body.dimensionFilterClauses = [{ filters }];
923
+ if (fields.includeEmptyRows) body.includeEmptyRows = true;
924
+ if (fields.hideTotals) body.hideTotals = true;
925
+ if (fields.hideValueRanges) body.hideValueRanges = true;
926
+ return body;
927
+ }
928
+ const batchGetRequest = (reportRequest, useResourceQuotas) => ({
929
+ api: "reporting",
930
+ method: "POST",
931
+ path: "/v4/reports:batchGet",
932
+ query: { useResourceQuotas: useResourceQuotas ? "true" : void 0 },
933
+ body: { reportRequests: [reportRequest] },
934
+ action: "get the report"
935
+ });
936
+ /** The rows of the reports as flat objects. A report with no rows gives nothing. */
937
+ function simplifyUA(reports) {
938
+ const out = [];
939
+ for (const report of records(reports)) {
940
+ const header = isRecord$1(report.columnHeader) ? report.columnHeader : {};
941
+ const data = isRecord$1(report.data) ? report.data : {};
942
+ if (!Array.isArray(data.rows)) continue;
943
+ const dimensions = asList$1(header.dimensions).map(str);
944
+ const metricHeader = isRecord$1(header.metricHeader) ? header.metricHeader : {};
945
+ const metrics = records(metricHeader.metricHeaderEntries).map((entry) => str(entry.name));
946
+ for (const row of records(data.rows)) {
947
+ const item = {};
948
+ const rowDimensions = asList$1(row.dimensions);
949
+ dimensions.forEach((name, index) => {
950
+ item[name] = rowDimensions[index];
951
+ });
952
+ const firstMetrics = records(row.metrics)[0];
953
+ const values = asList$1(firstMetrics?.values);
954
+ metrics.forEach((name, index) => {
955
+ item[name] = values[index];
956
+ });
957
+ out.push(item);
958
+ }
959
+ }
960
+ return out;
961
+ }
962
+ /** One report with the rows of all the reports. */
963
+ function mergeUA(reports) {
964
+ const list = records(reports);
965
+ const first = list[0];
966
+ if (!first) return [];
967
+ const data = isRecord$1(first.data) ? first.data : {};
968
+ const rows = list.flatMap((report) => isRecord$1(report.data) ? asList$1(report.data.rows) : []);
969
+ return [{
970
+ columnHeader: first.columnHeader,
971
+ data: {
972
+ ...data,
973
+ rows
974
+ }
975
+ }];
976
+ }
977
+ function userActivityBody(config) {
978
+ const userId = (config.userId ?? "").trim();
979
+ if (!userId) throw new Error("\"userId\" is needed to search user activity");
980
+ const body = {
981
+ viewId: parseViewId(config.viewId),
982
+ user: { userId }
983
+ };
984
+ if (config.activityTypes.length > 0) body.activityTypes = config.activityTypes;
985
+ return body;
986
+ }
987
+ const userActivityRequest = (body) => ({
988
+ api: "reporting",
989
+ method: "POST",
990
+ path: "/v4/userActivity:search",
991
+ body,
992
+ action: "search the user activity"
993
+ });
994
+ // src/node.ts
995
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
996
+ const asList = (value) => Array.isArray(value) ? value : [];
997
+ /** The most pages of one Return All, so a loop never runs for ever. */
998
+ const MAX_PAGES = 1e3;
999
+ const dateRangeOf = (config) => prepareDateRange(config.dateRange, {
1000
+ startDate: config.startDate,
1001
+ endDate: config.endDate
1002
+ });
1003
+ /** A report of Google Analytics 4. */
1004
+ async function ga4Report(call, config) {
1005
+ const propertyId = parsePropertyId(config.propertyId);
1006
+ const body = ga4Body(config, dateRangeOf(config));
1007
+ let response;
1008
+ if (config.returnAll) {
1009
+ const first = await call(runReportRequest(propertyId, {
1010
+ ...body,
1011
+ limit: GA4_PAGE_SIZE,
1012
+ offset: 0
1013
+ }));
1014
+ response = isRecord(first) ? first : {};
1015
+ const rows = asList(response.rows);
1016
+ const total = typeof response.rowCount === "number" ? response.rowCount : rows.length;
1017
+ for (let page = 1; total > rows.length && page < MAX_PAGES; page++) {
1018
+ const next = await call(runReportRequest(propertyId, {
1019
+ ...body,
1020
+ limit: GA4_PAGE_SIZE,
1021
+ offset: rows.length
1022
+ }));
1023
+ const more = isRecord(next) ? asList(next.rows) : [];
1024
+ if (more.length === 0) break;
1025
+ rows.push(...more);
1026
+ }
1027
+ response = {
1028
+ ...response,
1029
+ rows
1030
+ };
1031
+ } else {
1032
+ const answer = await call(runReportRequest(propertyId, {
1033
+ ...body,
1034
+ limit: config.limit
1035
+ }));
1036
+ response = isRecord(answer) ? answer : {};
1037
+ }
1038
+ return config.simple ? simplifyGA4(response) : response;
1039
+ }
1040
+ /** A report of Universal Analytics. */
1041
+ async function universalReport(call, config) {
1042
+ const body = uaBody(config, dateRangeOf(config));
1043
+ const quotas = config.additionalFieldsUA.useResourceQuotas;
1044
+ let reports = [];
1045
+ if (config.returnAll) {
1046
+ let pageToken;
1047
+ for (let page = 0; page < MAX_PAGES; page++) {
1048
+ const answer = await call(batchGetRequest(pageToken ? {
1049
+ ...body,
1050
+ pageToken
1051
+ } : body, quotas));
1052
+ const pageReports = isRecord(answer) ? asList(answer.reports) : [];
1053
+ reports.push(...pageReports);
1054
+ const token = isRecord(pageReports[0]) ? pageReports[0].nextPageToken : void 0;
1055
+ pageToken = typeof token === "string" && token !== "" ? token : void 0;
1056
+ if (!pageToken) break;
1057
+ }
1058
+ } else {
1059
+ const answer = await call(batchGetRequest({
1060
+ ...body,
1061
+ pageSize: config.limit
1062
+ }, quotas));
1063
+ reports = isRecord(answer) ? asList(answer.reports) : [];
1064
+ }
1065
+ if (config.simple) return simplifyUA(reports);
1066
+ return config.returnAll && reports.length > 1 ? mergeUA(reports) : reports;
1067
+ }
1068
+ /** The sessions of one user. */
1069
+ async function userActivity(call, config) {
1070
+ const body = userActivityBody(config);
1071
+ if (!config.returnAll) {
1072
+ if (config.limit > 500) throw new Error(`"limit" is at most 500 for user activity`);
1073
+ const answer = await call(userActivityRequest({
1074
+ ...body,
1075
+ pageSize: config.limit
1076
+ }));
1077
+ return isRecord(answer) ? asList(answer.sessions) : [];
1078
+ }
1079
+ const sessions = [];
1080
+ let pageToken;
1081
+ for (let page = 0; page < MAX_PAGES; page++) {
1082
+ const answer = await call(userActivityRequest(pageToken ? {
1083
+ ...body,
1084
+ pageToken
1085
+ } : body));
1086
+ if (!isRecord(answer)) break;
1087
+ sessions.push(...asList(answer.sessions));
1088
+ pageToken = typeof answer.nextPageToken === "string" && answer.nextPageToken !== "" ? answer.nextPageToken : void 0;
1089
+ if (!pageToken) break;
1090
+ }
1091
+ return sessions;
1092
+ }
1093
+ // src/index.ts
1094
+ const nodes = [(0, _zerodot_node_sdk.defineNode)({
1095
+ type: "google_analytics.api",
1096
+ label: "Google Analytics",
1097
+ description: "Get reports and user activity from Google Analytics",
1098
+ category: "integration",
1099
+ app: "Google Analytics",
1100
+ actions: [{
1101
+ label: "Get a report",
1102
+ config: {
1103
+ resource: "report",
1104
+ operation: "get"
1105
+ }
1106
+ }, {
1107
+ label: "Search user activity data",
1108
+ config: {
1109
+ resource: "userActivity",
1110
+ operation: "search"
1111
+ }
1112
+ }],
1113
+ icon: "Analytics01Icon",
1114
+ iconUrl: ANALYTICS_ICON,
1115
+ config: analyticsConfig,
1116
+ defaultConfig: {
1117
+ resource: "report",
1118
+ operation: "get",
1119
+ propertyType: "ga4",
1120
+ dateRange: "last7days",
1121
+ metricsGA4: { metricValues: [{
1122
+ listName: "totalUsers",
1123
+ invisible: false
1124
+ }] },
1125
+ dimensionsGA4: { dimensionValues: [{ listName: "date" }] },
1126
+ metricsUA: { metricValues: [{
1127
+ listName: "ga:users",
1128
+ formattingType: "INTEGER"
1129
+ }] },
1130
+ dimensionsUA: { dimensionValues: [{ listName: "ga:date" }] },
1131
+ returnAll: false,
1132
+ limit: 50,
1133
+ simple: true,
1134
+ activityTypes: [],
1135
+ timeoutMs: 3e4
1136
+ },
1137
+ credentialTypes: [ANALYTICS_OAUTH2_CREDENTIAL],
1138
+ ports: {
1139
+ in: ["in"],
1140
+ out: ["out"]
1141
+ },
1142
+ subtitle: (config) => typeof config.operation === "string" ? `${String(config.operation)}: ${String(config.resource ?? "report")}` : void 0,
1143
+ async run({ config, credential, signal }) {
1144
+ const options = {
1145
+ signal,
1146
+ timeoutMs: config.timeoutMs
1147
+ };
1148
+ const token = analyticsToken(credential);
1149
+ const call = (request) => callAnalytics(token, request, options);
1150
+ if (config.resource === "userActivity") return {
1151
+ port: "out",
1152
+ data: await userActivity(call, config)
1153
+ };
1154
+ return {
1155
+ port: "out",
1156
+ data: config.propertyType === "universal" ? await universalReport(call, config) : await ga4Report(call, config)
1157
+ };
1158
+ }
1159
+ })];
1160
+ const credentialTypes = [analyticsOAuth2Credential];
1161
+ exports.credentialTypes = credentialTypes;
1162
+ exports.nodes = nodes;