@trillboards/api-client 0.1.3 → 0.3.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/LICENSE +21 -0
- package/README.md +40 -8
- package/dist/index.d.mts +555 -27
- package/dist/index.d.ts +555 -27
- package/dist/index.js +211 -25
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +209 -26
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -2
package/dist/index.mjs
CHANGED
|
@@ -74,6 +74,47 @@ var VERSION = "0.1.3";
|
|
|
74
74
|
|
|
75
75
|
// src/http.ts
|
|
76
76
|
var PUBLIC_PATHS = ["/v1/errors", "/v1/changelog", "/api/discover", "/v1/health"];
|
|
77
|
+
function isRetryable(err) {
|
|
78
|
+
if (err instanceof TrillboardsError) {
|
|
79
|
+
return err.statusCode === 429 || err.statusCode >= 500;
|
|
80
|
+
}
|
|
81
|
+
if (err instanceof TypeError) return true;
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
function computeBackoffMs(attempt, baseMs, err) {
|
|
85
|
+
if (err instanceof TrillboardsError && err.retryAfter != null && err.retryAfter > 0) {
|
|
86
|
+
return err.retryAfter * 1e3;
|
|
87
|
+
}
|
|
88
|
+
const exponential = baseMs * Math.pow(2, attempt);
|
|
89
|
+
return Math.floor(Math.random() * exponential);
|
|
90
|
+
}
|
|
91
|
+
function sleep(ms) {
|
|
92
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
93
|
+
}
|
|
94
|
+
async function retryWithBackoff(operation, opts = {}) {
|
|
95
|
+
const retries = opts.retries ?? 6;
|
|
96
|
+
const baseMs = opts.baseMs ?? 1e3;
|
|
97
|
+
let lastError;
|
|
98
|
+
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
|
99
|
+
try {
|
|
100
|
+
return await operation();
|
|
101
|
+
} catch (err) {
|
|
102
|
+
lastError = err;
|
|
103
|
+
if (!isRetryable(err) || attempt === retries) {
|
|
104
|
+
throw err;
|
|
105
|
+
}
|
|
106
|
+
if (opts.onAttemptError) {
|
|
107
|
+
try {
|
|
108
|
+
opts.onAttemptError(attempt + 1, err);
|
|
109
|
+
} catch {
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const delayMs = computeBackoffMs(attempt, baseMs, err);
|
|
113
|
+
await sleep(delayMs);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
throw lastError;
|
|
117
|
+
}
|
|
77
118
|
var HttpClient = class {
|
|
78
119
|
constructor(config) {
|
|
79
120
|
this.config = config;
|
|
@@ -86,8 +127,9 @@ var HttpClient = class {
|
|
|
86
127
|
"User-Agent": `trillboards-typescript/${VERSION}`,
|
|
87
128
|
...options?.headers ?? {}
|
|
88
129
|
};
|
|
130
|
+
const callerSuppliedAuth = Object.keys(options?.headers ?? {}).some((h) => h.toLowerCase() === "authorization");
|
|
89
131
|
const isPublic = PUBLIC_PATHS.some((prefix) => path.startsWith(prefix));
|
|
90
|
-
if (!isPublic && this.config.apiKey) {
|
|
132
|
+
if (!isPublic && this.config.apiKey && !callerSuppliedAuth) {
|
|
91
133
|
headers["Authorization"] = `Bearer ${this.config.apiKey}`;
|
|
92
134
|
}
|
|
93
135
|
if (this.config.version) {
|
|
@@ -123,17 +165,28 @@ var HttpClient = class {
|
|
|
123
165
|
get(path, opts) {
|
|
124
166
|
return this.request("GET", path, { params: opts?.params });
|
|
125
167
|
}
|
|
126
|
-
|
|
127
|
-
|
|
168
|
+
/**
|
|
169
|
+
* POST / PUT / PATCH / DELETE auto-retry on 429 + 5xx + network TypeError
|
|
170
|
+
* via `retryWithBackoff()`. Callers can opt into observability by passing
|
|
171
|
+
* `retry.onAttemptError` to receive a callback per transient failure.
|
|
172
|
+
*
|
|
173
|
+
* The retry behavior is identical across all four methods because all of
|
|
174
|
+
* them are state-changing operations subject to the same transient-failure
|
|
175
|
+
* classes (rate limit, upstream-down, network-flap). The wire idempotency
|
|
176
|
+
* of POST vs DELETE is enforced server-side via Idempotency-Key headers,
|
|
177
|
+
* which the caller can attach via `opts.headers`.
|
|
178
|
+
*/
|
|
179
|
+
post(path, body, opts) {
|
|
180
|
+
return retryWithBackoff(() => this.request("POST", path, { body, headers: opts?.headers }), opts?.retry);
|
|
128
181
|
}
|
|
129
|
-
put(path, body) {
|
|
130
|
-
return this.request("PUT", path, { body });
|
|
182
|
+
put(path, body, opts) {
|
|
183
|
+
return retryWithBackoff(() => this.request("PUT", path, { body, headers: opts?.headers }), opts?.retry);
|
|
131
184
|
}
|
|
132
|
-
patch(path, body) {
|
|
133
|
-
return this.request("PATCH", path, { body });
|
|
185
|
+
patch(path, body, opts) {
|
|
186
|
+
return retryWithBackoff(() => this.request("PATCH", path, { body, headers: opts?.headers }), opts?.retry);
|
|
134
187
|
}
|
|
135
|
-
delete(path) {
|
|
136
|
-
return this.request("DELETE", path);
|
|
188
|
+
delete(path, opts) {
|
|
189
|
+
return retryWithBackoff(() => this.request("DELETE", path, { headers: opts?.headers }), opts?.retry);
|
|
137
190
|
}
|
|
138
191
|
buildUrl(path, params) {
|
|
139
192
|
const base = `${this.config.baseUrl}${path}`;
|
|
@@ -194,9 +247,20 @@ var DevicesClient = class {
|
|
|
194
247
|
async delete(deviceId) {
|
|
195
248
|
return this.http.delete(`/v1/partner/device/${deviceId}`);
|
|
196
249
|
}
|
|
197
|
-
/**
|
|
198
|
-
|
|
199
|
-
|
|
250
|
+
/**
|
|
251
|
+
* Send heartbeat for a device.
|
|
252
|
+
*
|
|
253
|
+
* Auto-retries on 429 + 5xx + network TypeError via the shared
|
|
254
|
+
* retryWithBackoff() helper (see http.ts). Pass `opts.retry.onAttemptError`
|
|
255
|
+
* to observe transient failures (e.g. emit an `upload_error` event from
|
|
256
|
+
* the CTV SDK without coupling the retry loop to its event emitter).
|
|
257
|
+
*/
|
|
258
|
+
async heartbeat(deviceId, body, opts) {
|
|
259
|
+
return this.http.post(
|
|
260
|
+
`/v1/partner/device/${deviceId}/heartbeat`,
|
|
261
|
+
body ?? {},
|
|
262
|
+
{ retry: opts?.retry }
|
|
263
|
+
);
|
|
200
264
|
}
|
|
201
265
|
};
|
|
202
266
|
|
|
@@ -380,26 +444,145 @@ var TrillboardsClient = class {
|
|
|
380
444
|
this.billing = new BillingClient(this._http);
|
|
381
445
|
}
|
|
382
446
|
};
|
|
383
|
-
|
|
447
|
+
var DEFAULT_TOLERANCE_SECONDS = 300;
|
|
448
|
+
function parseSignatureHeader(rawSig) {
|
|
449
|
+
const versions = /* @__PURE__ */ new Map();
|
|
450
|
+
let timestamp;
|
|
451
|
+
let legacy;
|
|
452
|
+
const trimmed = rawSig.trim();
|
|
453
|
+
if (trimmed.startsWith("sha256=")) {
|
|
454
|
+
legacy = trimmed.slice("sha256=".length);
|
|
455
|
+
return { timestamp, versions, legacy };
|
|
456
|
+
}
|
|
457
|
+
for (const part of trimmed.split(",")) {
|
|
458
|
+
const eq = part.indexOf("=");
|
|
459
|
+
if (eq < 0) continue;
|
|
460
|
+
const key = part.slice(0, eq).trim();
|
|
461
|
+
const value = part.slice(eq + 1).trim();
|
|
462
|
+
if (!key || !value) continue;
|
|
463
|
+
if (key === "t") {
|
|
464
|
+
const ts = Number(value);
|
|
465
|
+
if (Number.isFinite(ts)) timestamp = ts;
|
|
466
|
+
} else if (/^v\d+$/.test(key)) {
|
|
467
|
+
versions.set(key, value);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return { timestamp, versions, legacy };
|
|
471
|
+
}
|
|
472
|
+
function getHeader(headers, name) {
|
|
473
|
+
const lc = name.toLowerCase();
|
|
474
|
+
for (const key of Object.keys(headers)) {
|
|
475
|
+
if (key.toLowerCase() === lc) {
|
|
476
|
+
const v = headers[key];
|
|
477
|
+
if (Array.isArray(v)) return v[0];
|
|
478
|
+
return v;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return void 0;
|
|
482
|
+
}
|
|
483
|
+
function constantTimeEqual(a, b) {
|
|
484
|
+
const aBuf = Buffer.from(a, "utf8");
|
|
485
|
+
const bBuf = Buffer.from(b, "utf8");
|
|
486
|
+
if (aBuf.length !== bBuf.length) return false;
|
|
487
|
+
return timingSafeEqual(aBuf, bBuf);
|
|
488
|
+
}
|
|
489
|
+
function authError(message) {
|
|
490
|
+
return new TrillboardsError({
|
|
491
|
+
type: "authentication_error",
|
|
492
|
+
code: "webhook_signature_invalid",
|
|
493
|
+
message,
|
|
494
|
+
statusCode: 401
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
function constructEvent(payload, headers, secret, opts = {}) {
|
|
498
|
+
let signatureHeader;
|
|
499
|
+
let timestampHeader;
|
|
500
|
+
if (typeof headers === "string") {
|
|
501
|
+
signatureHeader = headers;
|
|
502
|
+
} else if (headers && typeof headers === "object") {
|
|
503
|
+
signatureHeader = getHeader(headers, "X-Trillboards-Signature");
|
|
504
|
+
timestampHeader = getHeader(headers, "X-Trillboards-Timestamp");
|
|
505
|
+
}
|
|
506
|
+
if (!signatureHeader) {
|
|
507
|
+
throw authError("Missing X-Trillboards-Signature header.");
|
|
508
|
+
}
|
|
384
509
|
const payloadStr = typeof payload === "string" ? payload : payload.toString("utf8");
|
|
385
|
-
const
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
510
|
+
const parsed = parseSignatureHeader(signatureHeader);
|
|
511
|
+
let ts = parsed.timestamp;
|
|
512
|
+
if (ts === void 0 && timestampHeader) {
|
|
513
|
+
const fromHeader = Number(timestampHeader);
|
|
514
|
+
if (Number.isFinite(fromHeader)) ts = fromHeader;
|
|
515
|
+
}
|
|
516
|
+
if (ts === void 0 || !Number.isFinite(ts)) {
|
|
517
|
+
throw authError(
|
|
518
|
+
"Webhook signature missing timestamp. Provide either `t=<unix_seconds>` inside X-Trillboards-Signature OR a separate X-Trillboards-Timestamp header."
|
|
519
|
+
);
|
|
520
|
+
}
|
|
521
|
+
const tolerance = opts.tolerance ?? DEFAULT_TOLERANCE_SECONDS;
|
|
522
|
+
const now = opts.nowSec ?? Math.floor(Date.now() / 1e3);
|
|
523
|
+
if (Math.abs(now - ts) > tolerance) {
|
|
524
|
+
throw authError(
|
|
525
|
+
`Webhook timestamp ${ts} outside tolerance window of ${tolerance}s (now ${now}). Possible replay attack.`
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
const v1Expected = createHmac("sha256", secret).update(`${ts}.${payloadStr}`).digest("hex");
|
|
529
|
+
const v0Expected = createHmac("sha256", secret).update(payloadStr).digest("hex");
|
|
530
|
+
const v1Provided = parsed.versions.get("v1");
|
|
531
|
+
const v0Provided = parsed.versions.get("v0");
|
|
532
|
+
if (v1Provided) {
|
|
533
|
+
if (constantTimeEqual(v1Provided, v1Expected)) {
|
|
534
|
+
return JSON.parse(payloadStr);
|
|
535
|
+
}
|
|
536
|
+
throw authError(
|
|
537
|
+
"Webhook v1 signature verification failed. The payload may have been tampered with, or your webhook secret may be incorrect."
|
|
538
|
+
);
|
|
539
|
+
}
|
|
540
|
+
if (v0Provided && constantTimeEqual(v0Provided, v0Expected)) {
|
|
541
|
+
return JSON.parse(payloadStr);
|
|
542
|
+
}
|
|
543
|
+
if (parsed.legacy) {
|
|
544
|
+
if (constantTimeEqual(parsed.legacy, v1Expected)) {
|
|
545
|
+
return JSON.parse(payloadStr);
|
|
546
|
+
}
|
|
547
|
+
if (constantTimeEqual(parsed.legacy, v0Expected)) {
|
|
548
|
+
return JSON.parse(payloadStr);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
throw authError(
|
|
552
|
+
"Webhook signature verification failed. The payload may have been tampered with, or your webhook secret may be incorrect."
|
|
553
|
+
);
|
|
554
|
+
}
|
|
555
|
+
var legacyWarned = false;
|
|
556
|
+
function constructEventLegacy(payload, signature, secret) {
|
|
557
|
+
if (!legacyWarned) {
|
|
558
|
+
console.warn(
|
|
559
|
+
"[@trillboards/api-client] constructEventLegacy is deprecated and unsafe (no replay protection). Migrate to Webhooks.constructEvent(payload, req.headers, secret). See https://api.trillboards.com/docs/integrations/webhook-signature-verification.md"
|
|
560
|
+
);
|
|
561
|
+
legacyWarned = true;
|
|
562
|
+
}
|
|
563
|
+
const payloadStr = typeof payload === "string" ? payload : payload.toString("utf8");
|
|
564
|
+
const expected = createHmac("sha256", secret).update(payloadStr).digest("hex");
|
|
565
|
+
if (!constantTimeEqual(signature, expected)) {
|
|
566
|
+
throw authError(
|
|
567
|
+
"Legacy webhook signature mismatch. If your server has been upgraded to the compound-header emitter, switch to Webhooks.constructEvent instead."
|
|
568
|
+
);
|
|
395
569
|
}
|
|
396
570
|
return JSON.parse(payloadStr);
|
|
397
571
|
}
|
|
398
|
-
var Webhooks = {
|
|
572
|
+
var Webhooks = {
|
|
573
|
+
constructEvent,
|
|
574
|
+
constructEventLegacy,
|
|
575
|
+
parseSignatureHeader
|
|
576
|
+
};
|
|
399
577
|
|
|
400
578
|
// src/generated/index.ts
|
|
401
|
-
var generatedTypes = {
|
|
579
|
+
var generatedTypes = {
|
|
580
|
+
schemaCount: 71,
|
|
581
|
+
operationCount: 175,
|
|
582
|
+
schemas: ["Ad", "AdSettings", "AudienceAnalyticsResponse", "AudienceAttentionPrediction", "AudienceExportResponse", "AudienceLoyaltyFeaturesRow", "AudienceMetricsResponse", "AudienceSegment", "AudienceSocialAttention", "BatchResult", "BleScanResultData", "ChangelogEntry", "ChangelogResponse", "ContentPreferencesInput", "ContentPreferencesResponse", "ContentPreset", "DashboardResponse", "DataExportSummaryResponse", "DemographicsResponse", "Device", "DeviceCapabilityPayload", "DeviceSummary", "DisplaySettingsInput", "DisplaySettingsResponse", "EarningsBreakdownResponse", "EarningsResponse", "Error", "HeaderBiddingSettings", "HttpProbeResult", "MdnsNetworkDevice", "Pagination", "Partner", "PartnerAdDeliveryProfile", "PartnerDefaultStream", "PartnerDefaultStreamCreate", "PartnerDefaultStreamUpdate", "PartnerDeviceHeartbeatBody", "PartnerHeartbeatCommand", "PartnerHeartbeatData", "PartnerHeartbeatMeasurementMetadata", "PartnerHeartbeatQueryData", "PartnerHeartbeatQueryResponse", "PartnerHeartbeatRequest", "PartnerHeartbeatResponse", "PartnerHeartbeatTelemetry", "PartnerLBarContent", "PartnerLBarDisplayPreferences", "PartnerLBarSettings", "PartnerSafeHeartbeatTelemetry", "PartnerSelfPromoAd", "PartnerSelfPromoCreate", "PartnerSelfPromoPlacement", "PartnerStats", "PayoutResponse", "PlaygroundResult", "PlaygroundValidationError", "ProgrammaticSettingsInput", "ProgrammaticSettingsResponse", "RequestMetadataResponse", "RolePermissions", "SDKConfig", "ScreenAnalyticsResponse", "SsdpDeviceInfo", "TeamInviteResponse", "TeamMember", "Transaction", "Webhook", "WebhookDelivery", "WebhookEvent", "WifiEnvironmentSnapshot", "WifiScanResult"],
|
|
583
|
+
operations: ["listPartnerSelfPromoAds", "createPartnerSelfPromoAd", "listPartnerSelfPromoPlacements", "schedulePartnerSelfPromo", "createPartnerSelfPromoUpload", "disableSelfPromoAd", "registerAgent", "getAnalytics", "getAudienceContinuity", "getAudienceProfile", "getBleSummary", "getContentPerformance", "searchCreativeCatalog", "getCreativeScenes", "getCrossScreenFlow", "getPartnerAnalyticsDashboard", "getDeviceSuiteSignature", "exportPartnerAnalytics", "exportPartnerAdsByDay", "getFleetHourly", "getHaloFunnel", "getLoyaltyClock", "getNetworkSummary", "getNetworkTrend", "getProximitySummary", "getRevenueAttentionCorrelation", "getSceneFeed", "getSceneIntelligence", "rotateApiKey", "getAudienceAnalytics", "exportAudienceData", "getAudienceHeatmap", "getLiveAudience", "getLookalikeScreens", "predictScreenAudience", "getResolvedHouseholdReach", "listAudienceSegments", "createAudienceSegment", "deleteAudienceSegment", "getAudienceSegment", "updateAudienceSegment", "matchAudienceSegment", "estimateSegmentReach", "generateSegmentVastTag", "getAudienceStats", "cancelBillingSubscription", "purchaseCredits", "createCreditCheckout", "listBillingPlans", "setupBilling", "createBillingSubscription", "getBillingSubscription", "getBillingUsage", "getUsageSummary", "stripeWebhookCallback", "getConnectDashboard", "getConnectEarningsChart", "getConnectScreenHealth", "listContentPresets", "getContentPreset", "getDashboard", "exportProximityGraphEdges", "getDataExportSummary", "exportDataset", "getGeohashAudiencePanel", "registerDevice", "deleteDevice", "getDevice", "updateDevice", "getAdsForDevice", "ackDeviceCommand", "getDeviceHeartbeat", "heartbeat", "recordProgrammaticEvent", "listDevices", "registerDevicesBatch", "batchUpdateDeviceOrientation", "partnerDocsBrowser", "getEarnings", "getEarningsBreakdown", "requestPayout", "getTransactions", "getActiveSSEConnections", "subscribeToEvents", "getFleetAnalytics", "pushFleetCommand", "getFleetOverview", "updateFleetSettings", "recordImpressionGet", "recordImpressionPost", "recordImpressionsBatch", "getPartnerInfo", "listIntentCategories", "getIntentCategory", "getIntentPricing", "getMeasurementMethodology", "getNetworkConfig", "patchNetworkConfig", "updateNetworkConfig", "getNetworkTrends", "partnerPing", "partnerPingAuth", "getPricing", "quickStart", "registerPartner", "generateSandboxEvent", "resetSandbox", "createSandboxScreen", "getSandboxStatus", "getScreenAudienceSegments", "batchUpdateContentPreferences", "batchUpdateDisplaySettings", "batchUpdateProgrammaticSettings", "resolvePartnerScreen", "getScreenAnalytics", "getPartnerScreenAtmosphere", "getPartnerScreenIntelligence", "getPartnerScreenTasteProfile", "getPartnerScreenTraffic", "getPartnerScreenVAS", "applyContentPreset", "getAudienceMetrics", "getContentPreferences", "patchContentPreferences", "updateContentPreferences", "listPartnerDefaultStreams", "createPartnerDefaultStream", "createPartnerDefaultStreamImages", "reorderPartnerDefaultStreams", "createPartnerDefaultStreamUpload", "deletePartnerDefaultStream", "updatePartnerDefaultStream", "getScreenDemographics", "getDisplaySettings", "patchDisplaySettings", "updateDisplaySettings", "getPartnerLBarSettings", "updatePartnerLBarSettings", "updatePartnerLBarLiveUpdates", "getProgrammaticSettings", "patchProgrammaticSettings", "updateProgrammaticSettings", "createStripeConnectAccount", "getStripeLoginLink", "getStripeOnboardingLink", "requestStripePayout", "getStripePayoutHistory", "getStripeAccountStatus", "handleStripeWebhook", "listTeamMembers", "acceptInvitation", "inviteTeamMember", "getInvitationByToken", "resendInvitation", "removeTeamMember", "changeTeamMemberRole", "getTrackingPublicKey", "recordTrackingBatch", "getUsageSummary__get__usage", "getUsageDashboard", "getRateLimitStatus", "queryChangelog", "playgroundDryRun", "getRequestMetadata", "getVastConfig", "getVenuesNearby", "getVenueAtmosphere", "getVenueTraffic", "getVenueIntelligence", "listWebhooks", "createWebhook", "deleteWebhook", "updateWebhook", "getWebhookDeliveries", "testWebhook"]
|
|
584
|
+
};
|
|
402
585
|
|
|
403
|
-
export { AnalyticsClient, AudienceClient, BillingClient, DataClient, DevicesClient, EarningsClient, ErrorsClient, FleetClient, ImpressionsClient, ScreensClient, TrillboardsClient, TrillboardsError, VERSION, Webhooks, WebhooksClient, constructEvent, generatedTypes };
|
|
586
|
+
export { AnalyticsClient, AudienceClient, BillingClient, DataClient, DevicesClient, EarningsClient, ErrorsClient, FleetClient, ImpressionsClient, ScreensClient, TrillboardsClient, TrillboardsError, VERSION, Webhooks, WebhooksClient, constructEvent, constructEventLegacy, generatedTypes, parseSignatureHeader, retryWithBackoff };
|
|
404
587
|
//# sourceMappingURL=index.mjs.map
|
|
405
588
|
//# sourceMappingURL=index.mjs.map
|