@punchline-analytics/sdk 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OpsScale
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # @punchline-analytics/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A typed client for the [Punchline Analytics](https://punchlineanalytics.com) API. Its methods and types are generated from the same OpenAPI spec the API is tested against, so they always match. Works in Node.js 18+, Deno, Bun and edge runtimes: anywhere with `fetch`. No dependencies.
4
+
5
+ ```bash
6
+ npm install @punchline-analytics/sdk
7
+ ```
8
+
9
+ ```ts
10
+ import { Punchline } from "@punchline-analytics/sdk";
11
+
12
+ const punchline = new Punchline({ apiKey: process.env.PUNCHLINE_API_KEY! });
13
+
14
+ const { results } = await punchline.query({
15
+ site_id: process.env.PUNCHLINE_SITE_ID!,
16
+ date_range: { from: "2026-09-01", to: "2026-09-30" },
17
+ metrics: ["sessions", "agent_share"],
18
+ dimensions: ["day"],
19
+ });
20
+ ```
21
+
22
+ Keep the key server-side. Full guide: [TypeScript SDK](https://punchlineanalytics.com/docs/sdk).
23
+
24
+ MIT licensed.
@@ -0,0 +1,574 @@
1
+ interface Transport {
2
+ request<T>(method: string, path: string, opts: {
3
+ query?: Record<string, unknown>;
4
+ body?: unknown;
5
+ headers?: Record<string, string>;
6
+ }): Promise<T>;
7
+ }
8
+ interface ClientOptions {
9
+ /** A key from Site settings → API and AI access: pk_live_… */
10
+ apiKey: string;
11
+ /** Default: https://app.punchlineanalytics.com */
12
+ baseUrl?: string;
13
+ /** Custom fetch (tests, proxies). Default: global fetch. */
14
+ fetch?: typeof fetch;
15
+ /** Retries after a 429, honoring Retry-After (up to 60 s). Default 2. */
16
+ maxRetries?: number;
17
+ }
18
+ /** An API error, with the fields from the API's error shape. */
19
+ declare class PunchlineError extends Error {
20
+ readonly status: number;
21
+ readonly type: string;
22
+ readonly code: string;
23
+ readonly param: string | null;
24
+ readonly docsUrl: string | null;
25
+ constructor(status: number, type: string, code: string, message: string, param: string | null, docsUrl: string | null);
26
+ }
27
+ declare const DEFAULT_BASE_URL = "https://app.punchlineanalytics.com";
28
+
29
+ type Alert = {
30
+ id?: string;
31
+ name?: string;
32
+ kind?: "threshold" | "anomaly" | "new_operator" | "account_signal";
33
+ metric?: string | null;
34
+ filters?: unknown[];
35
+ confidence?: "confirmed" | "likely" | "all";
36
+ op?: "above" | "below" | "up" | "down" | "either" | null;
37
+ value?: number | null;
38
+ min_volume?: number | null;
39
+ active?: boolean;
40
+ /** The condition in plain words. */
41
+ description?: string;
42
+ created_at?: string;
43
+ };
44
+ type AlertInput = {
45
+ name?: string;
46
+ kind?: "threshold" | "anomaly" | "new_operator" | "account_signal";
47
+ /** A /v1/query metric */
48
+ metric?: string;
49
+ filters?: unknown[];
50
+ confidence?: "confirmed" | "likely" | "all";
51
+ op?: "above" | "below" | "up" | "down" | "either";
52
+ value?: number;
53
+ min_volume?: number;
54
+ active?: boolean;
55
+ };
56
+ type Goal = {
57
+ id?: string;
58
+ name?: string;
59
+ kind?: "event" | "page";
60
+ match?: string;
61
+ };
62
+ type GoalInput = {
63
+ name?: string;
64
+ kind?: "event" | "page";
65
+ /** An event name, or a path (=/path for exactly that page) */
66
+ match?: string;
67
+ };
68
+ type Trigger = {
69
+ id?: string;
70
+ name?: string;
71
+ kind?: "page_view" | "url_match" | "click" | "form_submit";
72
+ match?: string;
73
+ event_name?: string;
74
+ /** Goes up when the definition changes; events record the version that produced them. */
75
+ version?: number;
76
+ active?: boolean;
77
+ };
78
+ type TriggerInput = {
79
+ name?: string;
80
+ kind?: "page_view" | "url_match" | "click" | "form_submit";
81
+ /** A path (page_view, url_match with * wildcards) or a CSS selector (click, form_submit; needs the browser snippet) */
82
+ match?: string;
83
+ event_name?: string;
84
+ active?: boolean;
85
+ };
86
+ type UrlParameters = {
87
+ params?: {
88
+ name: string;
89
+ mode: "presence" | "value";
90
+ }[];
91
+ rules?: {
92
+ param: string;
93
+ op: "present" | "equals" | "starts_with";
94
+ value?: string;
95
+ channel?: string;
96
+ partner?: string;
97
+ }[];
98
+ };
99
+ type Export = {
100
+ id?: string;
101
+ status?: "ready";
102
+ format?: "csv";
103
+ /** The normalized query */
104
+ query?: Record<string, unknown>;
105
+ rows?: number;
106
+ /** Rows withheld for privacy (fewer than 5 people) */
107
+ suppressed_rows?: number;
108
+ /** More rows matched than the limit */
109
+ truncated?: boolean;
110
+ /** Compressed size */
111
+ bytes?: number;
112
+ created_at?: string;
113
+ expires_at?: string;
114
+ download_url?: string;
115
+ };
116
+ type ApiErrorBody = {
117
+ error: {
118
+ type: "authentication_error" | "permission_error" | "invalid_request_error" | "rate_limit_error" | "api_error";
119
+ code: "invalid_api_key" | "insufficient_scope" | "plan_upgrade_required" | "not_found" | "site_not_found" | "invalid_json" | "invalid_parameter" | "body_too_large" | "feature_unavailable" | "idempotency_key_reused" | "rate_limited" | "internal_error";
120
+ message: string;
121
+ param: string | null;
122
+ docs_url: string;
123
+ };
124
+ };
125
+ type QueryResult = {
126
+ /** The query as run, with defaults filled in. */
127
+ query?: Record<string, unknown>;
128
+ results?: (Record<string, string | number | null>)[];
129
+ meta?: {
130
+ audience?: string;
131
+ min_cohort?: number;
132
+ suppressed_rows?: number;
133
+ rows_before_limit?: number;
134
+ truncated?: boolean;
135
+ rollups_refreshed_at?: string | null;
136
+ };
137
+ dashboard_url?: string;
138
+ };
139
+ type Site = {
140
+ id?: string;
141
+ name?: string;
142
+ domain?: string;
143
+ setup?: {
144
+ edge_install_reporting?: boolean;
145
+ snippet_reporting?: boolean;
146
+ browser_only?: boolean;
147
+ ga4_connected?: boolean;
148
+ };
149
+ };
150
+ type Operator = {
151
+ name?: string;
152
+ operator?: string;
153
+ type?: string;
154
+ actor_class?: string;
155
+ verified_by?: string[];
156
+ docs_url?: string;
157
+ };
158
+ type Session = {
159
+ session_id?: string;
160
+ /** Display label, e.g. impostor */
161
+ type?: string;
162
+ actor_class?: string;
163
+ operator?: string | null;
164
+ operator_docs?: string | null;
165
+ tier?: string;
166
+ started_at?: string;
167
+ ended_at?: string;
168
+ pageviews?: number;
169
+ paths?: string[];
170
+ rules?: Rule[];
171
+ evidence?: Record<string, unknown>;
172
+ };
173
+ type Evidence = {
174
+ session_id?: string;
175
+ type?: string;
176
+ actor_class?: string;
177
+ operator?: string | null;
178
+ tier?: string;
179
+ rules?: Rule[];
180
+ evidence?: Record<string, unknown>;
181
+ };
182
+ type Rule = {
183
+ id?: string;
184
+ description?: string;
185
+ };
186
+ type EventInput = {
187
+ /** Starts with a letter; letters, digits and _ (max 40). GA4-compatible. */
188
+ name: string;
189
+ /** ISO time or epoch ms, within the last 36 hours. Default: now. */
190
+ ts?: string;
191
+ /** The page it relates to, like /signup (no query string). */
192
+ path?: string;
193
+ /** Up to 10 properties: string (max 100), number or boolean values. */
194
+ props?: Record<string, unknown>;
195
+ /** A numeric value, e.g. revenue. */
196
+ value?: number;
197
+ /** The visitor's IP and user agent, to tie the event to their visit and its human/agent label. Used in memory only. */
198
+ visitor?: {
199
+ ip?: string;
200
+ user_agent?: string;
201
+ };
202
+ /** The domain of a work email someone gave you (acme.com). A whole address is accepted but only the domain is kept; personal mail is skipped. With visitor, links that visitor's day to the company (Accounts). */
203
+ company_domain?: string;
204
+ };
205
+ type QueryResponse = QueryResult;
206
+ type QueryBody = {
207
+ site_id: string;
208
+ date_range: {
209
+ /** First UTC day */
210
+ from: string;
211
+ /** Last UTC day, inclusive */
212
+ to: string;
213
+ };
214
+ metrics: ("sessions" | "pageviews" | "human_sessions" | "agent_sessions" | "agent_share" | "thin_pageviews" | "events" | "event_sessions" | "event_value" | "conversions" | "conversion_rate" | "visitors" | "bounces" | "bounce_rate" | "avg_session_duration" | "pages_per_session" | "engaged_sessions" | "engagement_rate" | "exits" | "exit_rate" | "avg_time_on_page")[];
215
+ dimensions?: string[];
216
+ filters?: unknown[];
217
+ /** How strict to be about agent labels. confirmed: verified signatures and declared crawlers only. likely (default): adds high-confidence inferences. all: adds low-confidence patterns. Weaker labels count as human. */
218
+ confidence?: "confirmed" | "likely" | "all";
219
+ order_by?: unknown[];
220
+ /** Default 100 */
221
+ limit?: number;
222
+ };
223
+ type SendEventsResponse = {
224
+ accepted?: number;
225
+ };
226
+ type SendEventsBody = {
227
+ site_id: string;
228
+ events: EventInput[];
229
+ };
230
+ type CreateHandoffResponse = {
231
+ data?: {
232
+ token?: string;
233
+ param?: "pl_ho";
234
+ url?: string;
235
+ kind?: string;
236
+ expires_at?: string;
237
+ agent?: Record<string, unknown>;
238
+ };
239
+ };
240
+ type CreateHandoffBody = {
241
+ site_id: string;
242
+ kind?: "cart" | "quote" | "configuration" | "booking" | "other";
243
+ /** The cart or quote total */
244
+ value?: number;
245
+ currency?: string;
246
+ expires_in_days?: number;
247
+ /** A path or https URL on your site; the response adds the token to it */
248
+ url?: string;
249
+ /** The agent's request, used in memory only */
250
+ visitor?: {
251
+ ip: string;
252
+ user_agent: string;
253
+ };
254
+ };
255
+ type GetHandoffsResponse = Record<string, unknown>;
256
+ type GetHandoffsParams = {
257
+ /** Optional; must be the API key's site. */
258
+ site_id?: string;
259
+ /** First UTC day, YYYY-MM-DD. Default: 6 days before `to`. */
260
+ from?: string;
261
+ /** Last UTC day, YYYY-MM-DD, inclusive. Default: today. */
262
+ to?: string;
263
+ };
264
+ type ListSitesResponse = {
265
+ data?: Site[];
266
+ };
267
+ type GetSiteResponse = {
268
+ data?: Site;
269
+ };
270
+ type ListOperatorsResponse = {
271
+ registry_version?: string;
272
+ data?: Operator[];
273
+ };
274
+ type ListSessionsResponse = {
275
+ data?: Session[];
276
+ next_cursor?: string | null;
277
+ };
278
+ type ListSessionsParams = {
279
+ /** Optional; must be the API key's site. */
280
+ site_id?: string;
281
+ /** First UTC day, YYYY-MM-DD. Default: 6 days before `to`. */
282
+ from?: string;
283
+ /** Last UTC day, YYYY-MM-DD, inclusive. Default: today. */
284
+ to?: string;
285
+ actor_class?: "signed_agent" | "declared_agent" | "crawler" | "fetcher" | "suspected_agent" | "spoofed_bot";
286
+ operator?: string;
287
+ tier?: "verified" | "declared" | "inferred_high" | "inferred_low";
288
+ /** Default 25 */
289
+ limit?: number;
290
+ cursor?: string;
291
+ };
292
+ type GetSessionResponse = {
293
+ data?: Session;
294
+ dashboard_url?: string;
295
+ };
296
+ type GetSessionEvidenceResponse = {
297
+ data?: Evidence;
298
+ };
299
+ type GetContentFunnelResponse = Record<string, unknown>;
300
+ type GetContentFunnelParams = {
301
+ /** Optional; must be the API key's site. */
302
+ site_id?: string;
303
+ /** First UTC day, YYYY-MM-DD. Default: 6 days before `to`. */
304
+ from?: string;
305
+ /** Last UTC day, YYYY-MM-DD, inclusive. Default: today. */
306
+ to?: string;
307
+ /** How strict to be about agent labels. confirmed: verified signatures and declared crawlers only. likely (default): adds high-confidence inferences. all: adds low-confidence patterns. Weaker labels count as human. */
308
+ confidence?: "confirmed" | "likely" | "all";
309
+ /** Group pages by path (default), content type or topic. */
310
+ group_by?: "path" | "content_type" | "topic";
311
+ /** Default 25 */
312
+ limit?: number;
313
+ };
314
+ type GetRecommendationsResponse = Record<string, unknown>;
315
+ type GetRecommendationsParams = {
316
+ /** Optional; must be the API key's site. */
317
+ site_id?: string;
318
+ /** First UTC day, YYYY-MM-DD. Default: 6 days before `to`. */
319
+ from?: string;
320
+ /** Last UTC day, YYYY-MM-DD, inclusive. Default: today. */
321
+ to?: string;
322
+ /** How strict to be about agent labels. confirmed: verified signatures and declared crawlers only. likely (default): adds high-confidence inferences. all: adds low-confidence patterns. Weaker labels count as human. */
323
+ confidence?: "confirmed" | "likely" | "all";
324
+ };
325
+ type GetAccountsResponse = Record<string, unknown>;
326
+ type GetAccountsParams = {
327
+ /** Optional; must be the API key's site. */
328
+ site_id?: string;
329
+ /** First UTC day, YYYY-MM-DD. Default: 6 days before `to`. */
330
+ from?: string;
331
+ /** Last UTC day, YYYY-MM-DD, inclusive. Default: today. */
332
+ to?: string;
333
+ /** How strict to be about agent labels. confirmed: verified signatures and declared crawlers only. likely (default): adds high-confidence inferences. all: adds low-confidence patterns. Weaker labels count as human. */
334
+ confidence?: "confirmed" | "likely" | "all";
335
+ /** One company, e.g. acme.com */
336
+ company_domain?: string;
337
+ /** Default light (all accounts) */
338
+ min_strength?: "light" | "moderate" | "strong";
339
+ /** Default 25 */
340
+ limit?: number;
341
+ };
342
+ type GetAiInfluenceResponse = Record<string, unknown>;
343
+ type GetAiInfluenceParams = {
344
+ /** Optional; must be the API key's site. */
345
+ site_id?: string;
346
+ /** First UTC day, YYYY-MM-DD. Default: 6 days before `to`. */
347
+ from?: string;
348
+ /** Last UTC day, YYYY-MM-DD, inclusive. Default: today. */
349
+ to?: string;
350
+ /** How strict to be about agent labels. confirmed: verified signatures and declared crawlers only. likely (default): adds high-confidence inferences. all: adds low-confidence patterns. Weaker labels count as human. */
351
+ confidence?: "confirmed" | "likely" | "all";
352
+ /** One goal's conversions; default all goals */
353
+ goal?: string;
354
+ };
355
+ type GetResolutionResponse = Record<string, unknown>;
356
+ type GetResolutionParams = {
357
+ /** Optional; must be the API key's site. */
358
+ site_id?: string;
359
+ /** First UTC day, YYYY-MM-DD. Default: 6 days before `to`. */
360
+ from?: string;
361
+ /** Last UTC day, YYYY-MM-DD, inclusive. Default: today. */
362
+ to?: string;
363
+ /** How strict to be about agent labels. confirmed: verified signatures and declared crawlers only. likely (default): adds high-confidence inferences. all: adds low-confidence patterns. Weaker labels count as human. */
364
+ confidence?: "confirmed" | "likely" | "all";
365
+ };
366
+ type GetReconciliationResponse = Record<string, unknown>;
367
+ type GetReconciliationParams = {
368
+ /** Optional; must be the API key's site. */
369
+ site_id?: string;
370
+ /** First UTC day, YYYY-MM-DD. Default: 6 days before `to`. */
371
+ from?: string;
372
+ /** Last UTC day, YYYY-MM-DD, inclusive. Default: today. */
373
+ to?: string;
374
+ /** How strict to be about agent labels. confirmed: verified signatures and declared crawlers only. likely (default): adds high-confidence inferences. all: adds low-confidence patterns. Weaker labels count as human. */
375
+ confidence?: "confirmed" | "likely" | "all";
376
+ };
377
+ type ListReportsResponse = {
378
+ data?: {
379
+ id?: string;
380
+ name?: string;
381
+ params?: Record<string, string>;
382
+ updated_at?: string;
383
+ }[];
384
+ };
385
+ type CreateExportResponse = {
386
+ data?: Export;
387
+ };
388
+ type CreateExportBody = {
389
+ site_id: string;
390
+ format?: "csv";
391
+ date_range: {
392
+ /** First UTC day */
393
+ from: string;
394
+ /** Last UTC day, inclusive */
395
+ to: string;
396
+ };
397
+ metrics: ("sessions" | "pageviews" | "human_sessions" | "agent_sessions" | "agent_share" | "thin_pageviews" | "events" | "event_sessions" | "event_value" | "conversions" | "conversion_rate" | "visitors" | "bounces" | "bounce_rate" | "avg_session_duration" | "pages_per_session" | "engaged_sessions" | "engagement_rate" | "exits" | "exit_rate" | "avg_time_on_page")[];
398
+ dimensions?: string[];
399
+ filters?: unknown[];
400
+ /** How strict to be about agent labels. confirmed: verified signatures and declared crawlers only. likely (default): adds high-confidence inferences. all: adds low-confidence patterns. Weaker labels count as human. */
401
+ confidence?: "confirmed" | "likely" | "all";
402
+ order_by?: unknown[];
403
+ limit?: number;
404
+ };
405
+ type GetExportResponse = {
406
+ data?: Export;
407
+ };
408
+ type DownloadExportResponse = string;
409
+ type ListAlertsResponse = {
410
+ data?: Alert[];
411
+ };
412
+ type CreateAlertResponse = {
413
+ data?: Alert;
414
+ };
415
+ type CreateAlertBody = AlertInput;
416
+ type GetAlertResponse = {
417
+ data?: Alert;
418
+ };
419
+ type UpdateAlertResponse = {
420
+ data?: Alert;
421
+ };
422
+ type UpdateAlertBody = AlertInput;
423
+ type DeleteAlertResponse = void;
424
+ type ListGoalsResponse = {
425
+ data?: Goal[];
426
+ };
427
+ type CreateGoalResponse = {
428
+ data?: Goal;
429
+ };
430
+ type CreateGoalBody = GoalInput;
431
+ type GetGoalResponse = {
432
+ data?: Goal;
433
+ };
434
+ type UpdateGoalResponse = {
435
+ data?: Goal;
436
+ };
437
+ type UpdateGoalBody = GoalInput;
438
+ type DeleteGoalResponse = void;
439
+ type ListTriggersResponse = {
440
+ data?: Trigger[];
441
+ };
442
+ type CreateTriggerResponse = {
443
+ data?: Trigger;
444
+ };
445
+ type CreateTriggerBody = TriggerInput;
446
+ type GetTriggerResponse = {
447
+ data?: Trigger;
448
+ };
449
+ type UpdateTriggerResponse = {
450
+ data?: Trigger;
451
+ };
452
+ type UpdateTriggerBody = TriggerInput;
453
+ type DeleteTriggerResponse = void;
454
+ type GetUrlParametersResponse = {
455
+ data?: UrlParameters;
456
+ };
457
+ type UpdateUrlParametersResponse = {
458
+ data?: UrlParameters;
459
+ };
460
+ type UpdateUrlParametersBody = UrlParameters;
461
+ type DeleteUrlParametersResponse = void;
462
+ /** One typed method per API operation. */
463
+ declare class Operations {
464
+ protected readonly transport: Transport;
465
+ constructor(transport: Transport);
466
+ /** Metrics by dimensions, with filters. The main endpoint. */
467
+ query(body: QueryBody): Promise<QueryResponse>;
468
+ /** Send custom events from your servers (up to 1,000). Needs the events:write scope. Send Idempotency-Key to make retries safe. */
469
+ sendEvents(body: SendEventsBody, opts?: {
470
+ idempotencyKey?: string;
471
+ }): Promise<SendEventsResponse>;
472
+ /** Mint a handoff link for an agent that built a cart, quote, configuration or booking. Give the agent's request (visitor) to tie the link to its session; when a person opens the link, the open is recorded. Needs the events:write scope. Only the token's hash is stored. */
473
+ createHandoff(body: CreateHandoffBody): Promise<CreateHandoffResponse>;
474
+ /** Handoff links created in a date range: opened by a person, opened by an agent, and converted (the opener's session completed a goal), with values, per kind and agent operator. */
475
+ getHandoffs(params?: GetHandoffsParams): Promise<GetHandoffsResponse>;
476
+ /** The site this key can read, with setup status. */
477
+ listSites(): Promise<ListSitesResponse>;
478
+ /** One site. */
479
+ getSite(id: string): Promise<GetSiteResponse>;
480
+ /** Known agent operators and how each is verified. */
481
+ listOperators(): Promise<ListOperatorsResponse>;
482
+ /** Agent and crawler sessions, newest first. Page with cursor=next_cursor. */
483
+ listSessions(params?: ListSessionsParams): Promise<ListSessionsResponse>;
484
+ /** One agent session as a request timeline. */
485
+ getSession(id: string): Promise<GetSessionResponse>;
486
+ /** Why this session was labelled an agent: rules, evidence, tier. */
487
+ getSessionEvidence(id: string): Promise<GetSessionEvidenceResponse>;
488
+ /** Agent content funnel: fetched (live vs crawl) → delivered → cited, per page, content type or topic. */
489
+ getContentFunnel(params?: GetContentFunnelParams): Promise<GetContentFunnelResponse>;
490
+ /** Evidence-based things to try so assistants can read and cite the site, with the previous period for comparison. */
491
+ getRecommendations(params?: GetRecommendationsParams): Promise<GetRecommendationsResponse>;
492
+ /** Agent intent by company: what each company's agents and people read, grouped by intent, with a strength and a summary. Account-level only. */
493
+ getAccounts(params?: GetAccountsParams): Promise<GetAccountsResponse>;
494
+ /** Estimated AI-assisted conversions from the post-conversion survey (ai_assist_yes / _no / _not_sure events), with a 95% interval, against conversions Punchline connects directly, and the multiplier. */
495
+ getAiInfluence(params?: GetAiInfluenceParams): Promise<GetAiInfluenceResponse>;
496
+ /** Where agent sessions ran (in a person's browser, cloud, local tool) and how many joined a person's visit or a company the same day. */
497
+ getResolution(params?: GetResolutionParams): Promise<GetResolutionResponse>;
498
+ /** GA4 sessions vs Punchline's, with the gap explained. Needs GA4 connected. */
499
+ getReconciliation(params?: GetReconciliationParams): Promise<GetReconciliationResponse>;
500
+ /** Saved reports shared with this site (private reports are never listed), with their Explore parameters: tm metric, d breakdown, f filters, tt chart type, tg granularity, range, who, confidence. */
501
+ listReports(): Promise<ListReportsResponse>;
502
+ /** Run a query (the /v1/query model, limit up to 100,000, default 100,000) and keep the result as CSV for 24 hours. Same privacy suppression as /v1/query. */
503
+ createExport(body: CreateExportBody): Promise<CreateExportResponse>;
504
+ /** An export's size and download link. */
505
+ getExport(id: string): Promise<GetExportResponse>;
506
+ /** The CSV, gzip-encoded (Content-Encoding: gzip; with curl, use --compressed). Cells starting with = + - @ are prefixed with ' so spreadsheets don't run them. */
507
+ downloadExport(id: string): Promise<DownloadExportResponse>;
508
+ /** The site's alerts. Needs the admin scope. */
509
+ listAlerts(): Promise<ListAlertsResponse>;
510
+ /** Create a alert. Needs the admin scope. */
511
+ createAlert(body: CreateAlertBody, opts?: {
512
+ idempotencyKey?: string;
513
+ }): Promise<CreateAlertResponse>;
514
+ /** One alert. */
515
+ getAlert(id: string): Promise<GetAlertResponse>;
516
+ /** Change a alert: send only the fields to change. */
517
+ updateAlert(id: string, body: UpdateAlertBody, opts?: {
518
+ idempotencyKey?: string;
519
+ }): Promise<UpdateAlertResponse>;
520
+ /** Delete a alert. */
521
+ deleteAlert(id: string, opts?: {
522
+ idempotencyKey?: string;
523
+ }): Promise<DeleteAlertResponse>;
524
+ /** The site's goals. Needs the admin scope. */
525
+ listGoals(): Promise<ListGoalsResponse>;
526
+ /** Create a goal. Needs the admin scope. */
527
+ createGoal(body: CreateGoalBody, opts?: {
528
+ idempotencyKey?: string;
529
+ }): Promise<CreateGoalResponse>;
530
+ /** One goal. */
531
+ getGoal(id: string): Promise<GetGoalResponse>;
532
+ /** Change a goal: send only the fields to change. */
533
+ updateGoal(id: string, body: UpdateGoalBody, opts?: {
534
+ idempotencyKey?: string;
535
+ }): Promise<UpdateGoalResponse>;
536
+ /** Delete a goal. */
537
+ deleteGoal(id: string, opts?: {
538
+ idempotencyKey?: string;
539
+ }): Promise<DeleteGoalResponse>;
540
+ /** The site's no-code event triggers. Needs the admin scope. */
541
+ listTriggers(): Promise<ListTriggersResponse>;
542
+ /** Create a trigger. Needs the admin scope. */
543
+ createTrigger(body: CreateTriggerBody, opts?: {
544
+ idempotencyKey?: string;
545
+ }): Promise<CreateTriggerResponse>;
546
+ /** One trigger. */
547
+ getTrigger(id: string): Promise<GetTriggerResponse>;
548
+ /** Change a trigger: send only the fields to change. */
549
+ updateTrigger(id: string, body: UpdateTriggerBody, opts?: {
550
+ idempotencyKey?: string;
551
+ }): Promise<UpdateTriggerResponse>;
552
+ /** Delete a trigger. */
553
+ deleteTrigger(id: string, opts?: {
554
+ idempotencyKey?: string;
555
+ }): Promise<DeleteTriggerResponse>;
556
+ /** The URL-parameter allowlist and rules. Needs the admin scope. */
557
+ getUrlParameters(): Promise<GetUrlParametersResponse>;
558
+ /** Replace params and/or rules (send either or both). Rules may only use allowed parameters. */
559
+ updateUrlParameters(body: UpdateUrlParametersBody, opts?: {
560
+ idempotencyKey?: string;
561
+ }): Promise<UpdateUrlParametersResponse>;
562
+ /** Allow no parameters (except utm_*) and remove all rules. */
563
+ deleteUrlParameters(opts?: {
564
+ idempotencyKey?: string;
565
+ }): Promise<DeleteUrlParametersResponse>;
566
+ }
567
+
568
+ declare class Punchline extends Operations {
569
+ constructor(opts: ClientOptions);
570
+ /** Every agent session matching `params`, following next_cursor page by page. */
571
+ allSessions(params?: Omit<ListSessionsParams, "cursor">): AsyncGenerator<Session>;
572
+ }
573
+
574
+ export { type Alert, type AlertInput, type ApiErrorBody, type ClientOptions, type CreateAlertBody, type CreateAlertResponse, type CreateExportBody, type CreateExportResponse, type CreateGoalBody, type CreateGoalResponse, type CreateHandoffBody, type CreateHandoffResponse, type CreateTriggerBody, type CreateTriggerResponse, DEFAULT_BASE_URL, type DeleteAlertResponse, type DeleteGoalResponse, type DeleteTriggerResponse, type DeleteUrlParametersResponse, type DownloadExportResponse, type EventInput, type Evidence, type Export, type GetAccountsParams, type GetAccountsResponse, type GetAiInfluenceParams, type GetAiInfluenceResponse, type GetAlertResponse, type GetContentFunnelParams, type GetContentFunnelResponse, type GetExportResponse, type GetGoalResponse, type GetHandoffsParams, type GetHandoffsResponse, type GetRecommendationsParams, type GetRecommendationsResponse, type GetReconciliationParams, type GetReconciliationResponse, type GetResolutionParams, type GetResolutionResponse, type GetSessionEvidenceResponse, type GetSessionResponse, type GetSiteResponse, type GetTriggerResponse, type GetUrlParametersResponse, type Goal, type GoalInput, type ListAlertsResponse, type ListGoalsResponse, type ListOperatorsResponse, type ListReportsResponse, type ListSessionsParams, type ListSessionsResponse, type ListSitesResponse, type ListTriggersResponse, Operations, type Operator, Punchline, PunchlineError, type QueryBody, type QueryResponse, type QueryResult, type Rule, type SendEventsBody, type SendEventsResponse, type Session, type Site, type Trigger, type TriggerInput, type UpdateAlertBody, type UpdateAlertResponse, type UpdateGoalBody, type UpdateGoalResponse, type UpdateTriggerBody, type UpdateTriggerResponse, type UpdateUrlParametersBody, type UpdateUrlParametersResponse, type UrlParameters };
package/dist/index.js ADDED
@@ -0,0 +1,230 @@
1
+ // src/client.ts
2
+ var PunchlineError = class extends Error {
3
+ constructor(status, type, code, message, param, docsUrl) {
4
+ super(message);
5
+ this.status = status;
6
+ this.type = type;
7
+ this.code = code;
8
+ this.param = param;
9
+ this.docsUrl = docsUrl;
10
+ this.name = "PunchlineError";
11
+ }
12
+ status;
13
+ type;
14
+ code;
15
+ param;
16
+ docsUrl;
17
+ };
18
+ var DEFAULT_BASE_URL = "https://app.punchlineanalytics.com";
19
+ function createTransport(opts) {
20
+ if (!/^pk_(live|test)_[A-Za-z0-9]{32}$/.test(opts.apiKey)) throw new Error("apiKey should look like pk_live_ followed by 32 characters");
21
+ const base = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
22
+ const doFetch = opts.fetch ?? fetch;
23
+ const maxRetries = opts.maxRetries ?? 2;
24
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25
+ return {
26
+ async request(method, path, { query, body, headers }) {
27
+ const url = new URL(base + path);
28
+ for (const [k, v] of Object.entries(query ?? {})) if (v !== void 0 && v !== null) url.searchParams.set(k, String(v));
29
+ for (let attempt = 0; ; attempt++) {
30
+ const res = await doFetch(url, {
31
+ method,
32
+ headers: { ...headers, authorization: `Bearer ${opts.apiKey}`, ...body !== void 0 ? { "content-type": "application/json" } : {} },
33
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
34
+ });
35
+ if (res.status === 429 && attempt < maxRetries) {
36
+ const wait = Math.min(Number(res.headers.get("retry-after") ?? 1), 60);
37
+ await res.body?.cancel();
38
+ await sleep(wait * 1e3);
39
+ continue;
40
+ }
41
+ if (res.ok && res.headers.get("content-type")?.startsWith("text/csv")) return await res.text();
42
+ if (res.status === 204) return void 0;
43
+ const data = await res.json().catch(() => null);
44
+ if (!res.ok) {
45
+ const e = data?.error;
46
+ throw new PunchlineError(res.status, e?.type ?? "api_error", e?.code ?? "unknown", e?.message ?? `HTTP ${res.status}`, e?.param ?? null, e?.docs_url ?? null);
47
+ }
48
+ return data;
49
+ }
50
+ }
51
+ };
52
+ }
53
+
54
+ // src/generated.ts
55
+ var Operations = class {
56
+ constructor(transport) {
57
+ this.transport = transport;
58
+ }
59
+ transport;
60
+ /** Metrics by dimensions, with filters. The main endpoint. */
61
+ query(body) {
62
+ return this.transport.request("POST", `/v1/query`, { body });
63
+ }
64
+ /** Send custom events from your servers (up to 1,000). Needs the events:write scope. Send Idempotency-Key to make retries safe. */
65
+ sendEvents(body, opts = {}) {
66
+ return this.transport.request("POST", `/v1/events`, { body, ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
67
+ }
68
+ /** Mint a handoff link for an agent that built a cart, quote, configuration or booking. Give the agent's request (visitor) to tie the link to its session; when a person opens the link, the open is recorded. Needs the events:write scope. Only the token's hash is stored. */
69
+ createHandoff(body) {
70
+ return this.transport.request("POST", `/v1/handoffs`, { body });
71
+ }
72
+ /** Handoff links created in a date range: opened by a person, opened by an agent, and converted (the opener's session completed a goal), with values, per kind and agent operator. */
73
+ getHandoffs(params = {}) {
74
+ return this.transport.request("GET", `/v1/handoffs`, { query: params });
75
+ }
76
+ /** The site this key can read, with setup status. */
77
+ listSites() {
78
+ return this.transport.request("GET", `/v1/sites`, {});
79
+ }
80
+ /** One site. */
81
+ getSite(id) {
82
+ return this.transport.request("GET", `/v1/sites/${encodeURIComponent(id)}`, {});
83
+ }
84
+ /** Known agent operators and how each is verified. */
85
+ listOperators() {
86
+ return this.transport.request("GET", `/v1/operators`, {});
87
+ }
88
+ /** Agent and crawler sessions, newest first. Page with cursor=next_cursor. */
89
+ listSessions(params = {}) {
90
+ return this.transport.request("GET", `/v1/sessions`, { query: params });
91
+ }
92
+ /** One agent session as a request timeline. */
93
+ getSession(id) {
94
+ return this.transport.request("GET", `/v1/sessions/${encodeURIComponent(id)}`, {});
95
+ }
96
+ /** Why this session was labelled an agent: rules, evidence, tier. */
97
+ getSessionEvidence(id) {
98
+ return this.transport.request("GET", `/v1/sessions/${encodeURIComponent(id)}/evidence`, {});
99
+ }
100
+ /** Agent content funnel: fetched (live vs crawl) → delivered → cited, per page, content type or topic. */
101
+ getContentFunnel(params = {}) {
102
+ return this.transport.request("GET", `/v1/content/funnel`, { query: params });
103
+ }
104
+ /** Evidence-based things to try so assistants can read and cite the site, with the previous period for comparison. */
105
+ getRecommendations(params = {}) {
106
+ return this.transport.request("GET", `/v1/content/recommendations`, { query: params });
107
+ }
108
+ /** Agent intent by company: what each company's agents and people read, grouped by intent, with a strength and a summary. Account-level only. */
109
+ getAccounts(params = {}) {
110
+ return this.transport.request("GET", `/v1/accounts`, { query: params });
111
+ }
112
+ /** Estimated AI-assisted conversions from the post-conversion survey (ai_assist_yes / _no / _not_sure events), with a 95% interval, against conversions Punchline connects directly, and the multiplier. */
113
+ getAiInfluence(params = {}) {
114
+ return this.transport.request("GET", `/v1/ai-influence`, { query: params });
115
+ }
116
+ /** Where agent sessions ran (in a person's browser, cloud, local tool) and how many joined a person's visit or a company the same day. */
117
+ getResolution(params = {}) {
118
+ return this.transport.request("GET", `/v1/resolution`, { query: params });
119
+ }
120
+ /** GA4 sessions vs Punchline's, with the gap explained. Needs GA4 connected. */
121
+ getReconciliation(params = {}) {
122
+ return this.transport.request("GET", `/v1/reconciliation`, { query: params });
123
+ }
124
+ /** Saved reports shared with this site (private reports are never listed), with their Explore parameters: tm metric, d breakdown, f filters, tt chart type, tg granularity, range, who, confidence. */
125
+ listReports() {
126
+ return this.transport.request("GET", `/v1/reports`, {});
127
+ }
128
+ /** Run a query (the /v1/query model, limit up to 100,000, default 100,000) and keep the result as CSV for 24 hours. Same privacy suppression as /v1/query. */
129
+ createExport(body) {
130
+ return this.transport.request("POST", `/v1/exports`, { body });
131
+ }
132
+ /** An export's size and download link. */
133
+ getExport(id) {
134
+ return this.transport.request("GET", `/v1/exports/${encodeURIComponent(id)}`, {});
135
+ }
136
+ /** The CSV, gzip-encoded (Content-Encoding: gzip; with curl, use --compressed). Cells starting with = + - @ are prefixed with ' so spreadsheets don't run them. */
137
+ downloadExport(id) {
138
+ return this.transport.request("GET", `/v1/exports/${encodeURIComponent(id)}/download`, {});
139
+ }
140
+ /** The site's alerts. Needs the admin scope. */
141
+ listAlerts() {
142
+ return this.transport.request("GET", `/v1/alerts`, {});
143
+ }
144
+ /** Create a alert. Needs the admin scope. */
145
+ createAlert(body, opts = {}) {
146
+ return this.transport.request("POST", `/v1/alerts`, { body, ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
147
+ }
148
+ /** One alert. */
149
+ getAlert(id) {
150
+ return this.transport.request("GET", `/v1/alerts/${encodeURIComponent(id)}`, {});
151
+ }
152
+ /** Change a alert: send only the fields to change. */
153
+ updateAlert(id, body, opts = {}) {
154
+ return this.transport.request("PATCH", `/v1/alerts/${encodeURIComponent(id)}`, { body, ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
155
+ }
156
+ /** Delete a alert. */
157
+ deleteAlert(id, opts = {}) {
158
+ return this.transport.request("DELETE", `/v1/alerts/${encodeURIComponent(id)}`, { ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
159
+ }
160
+ /** The site's goals. Needs the admin scope. */
161
+ listGoals() {
162
+ return this.transport.request("GET", `/v1/goals`, {});
163
+ }
164
+ /** Create a goal. Needs the admin scope. */
165
+ createGoal(body, opts = {}) {
166
+ return this.transport.request("POST", `/v1/goals`, { body, ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
167
+ }
168
+ /** One goal. */
169
+ getGoal(id) {
170
+ return this.transport.request("GET", `/v1/goals/${encodeURIComponent(id)}`, {});
171
+ }
172
+ /** Change a goal: send only the fields to change. */
173
+ updateGoal(id, body, opts = {}) {
174
+ return this.transport.request("PATCH", `/v1/goals/${encodeURIComponent(id)}`, { body, ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
175
+ }
176
+ /** Delete a goal. */
177
+ deleteGoal(id, opts = {}) {
178
+ return this.transport.request("DELETE", `/v1/goals/${encodeURIComponent(id)}`, { ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
179
+ }
180
+ /** The site's no-code event triggers. Needs the admin scope. */
181
+ listTriggers() {
182
+ return this.transport.request("GET", `/v1/triggers`, {});
183
+ }
184
+ /** Create a trigger. Needs the admin scope. */
185
+ createTrigger(body, opts = {}) {
186
+ return this.transport.request("POST", `/v1/triggers`, { body, ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
187
+ }
188
+ /** One trigger. */
189
+ getTrigger(id) {
190
+ return this.transport.request("GET", `/v1/triggers/${encodeURIComponent(id)}`, {});
191
+ }
192
+ /** Change a trigger: send only the fields to change. */
193
+ updateTrigger(id, body, opts = {}) {
194
+ return this.transport.request("PATCH", `/v1/triggers/${encodeURIComponent(id)}`, { body, ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
195
+ }
196
+ /** Delete a trigger. */
197
+ deleteTrigger(id, opts = {}) {
198
+ return this.transport.request("DELETE", `/v1/triggers/${encodeURIComponent(id)}`, { ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
199
+ }
200
+ /** The URL-parameter allowlist and rules. Needs the admin scope. */
201
+ getUrlParameters() {
202
+ return this.transport.request("GET", `/v1/url-parameters`, {});
203
+ }
204
+ /** Replace params and/or rules (send either or both). Rules may only use allowed parameters. */
205
+ updateUrlParameters(body, opts = {}) {
206
+ return this.transport.request("PATCH", `/v1/url-parameters`, { body, ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
207
+ }
208
+ /** Allow no parameters (except utm_*) and remove all rules. */
209
+ deleteUrlParameters(opts = {}) {
210
+ return this.transport.request("DELETE", `/v1/url-parameters`, { ...opts.idempotencyKey ? { headers: { "idempotency-key": opts.idempotencyKey } } : {} });
211
+ }
212
+ };
213
+
214
+ // src/index.ts
215
+ var Punchline = class extends Operations {
216
+ constructor(opts) {
217
+ super(createTransport(opts));
218
+ }
219
+ /** Every agent session matching `params`, following next_cursor page by page. */
220
+ async *allSessions(params = {}) {
221
+ let cursor;
222
+ do {
223
+ const page = await this.listSessions({ ...params, ...cursor ? { cursor } : {} });
224
+ for (const s of page.data ?? []) yield s;
225
+ cursor = page.next_cursor ?? void 0;
226
+ } while (cursor);
227
+ }
228
+ };
229
+
230
+ export { DEFAULT_BASE_URL, Punchline, PunchlineError };
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@punchline-analytics/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "description": "Typed client for the Punchline Analytics API, generated from its OpenAPI spec.",
6
+ "license": "MIT",
7
+ "homepage": "https://punchlineanalytics.com/docs/sdk",
8
+ "keywords": [
9
+ "analytics",
10
+ "ai-agents",
11
+ "api-client",
12
+ "punchline"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "devDependencies": {
26
+ "tsup": "8.5.1",
27
+ "typescript": "5.9.3"
28
+ },
29
+ "sideEffects": false,
30
+ "scripts": {
31
+ "build": "tsup"
32
+ },
33
+ "types": "./dist/index.d.ts",
34
+ "main": "./dist/index.js"
6
35
  }