@proofhorn/next 0.0.0-stage → 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.
@@ -0,0 +1,53 @@
1
+ import 'server-only';
2
+ import { ProofhornError } from '../shared/http.js';
3
+ import type { ActivityInput, BatchResults, Item, ConnectExchangeInput, ConnectExchangeResult, ExactActivity, Experiment, ItemInput, Period, PrivacySubject, ReferralCode, ReferralInput, ReviewImport, ReviewRequestInput, ReviewRequestResult, SiteInfo, Summary, WriteResult } from '../shared/types.js';
4
+ /** A create call the site's plan does not allow (402). Show `upgradeUrl` to the developer or site owner, never to visitors. */
5
+ export declare class ProofhornPlanLimitError extends ProofhornError {
6
+ readonly upgradeUrl: string | undefined;
7
+ constructor(error: ProofhornError);
8
+ }
9
+ export type ServerClientOptions = {
10
+ secretKey: string;
11
+ apiBase?: string;
12
+ };
13
+ export declare function createServerClient(options: ServerClientOptions): {
14
+ testMode: boolean;
15
+ upsertItem: (itemKey: string, input: ItemInput) => Promise<{
16
+ item: Item;
17
+ }>;
18
+ upsertItems: (items: Array<ItemInput & {
19
+ itemKey: string;
20
+ }>) => Promise<BatchResults>;
21
+ /**
22
+ * Throws `ProofhornError` on failure, so a webhook can respond with an error and be retried.
23
+ * Never refused for plan reasons: past the monthly cap the activity is still recorded.
24
+ */
25
+ recordActivity<T extends ActivityInput>(input: ExactActivity<T>): Promise<WriteResult>;
26
+ recordActivities(activities: ActivityInput[]): Promise<BatchResults<WriteResult>>;
27
+ /** For refunded orders and cancelled enrolments. */
28
+ cancelActivity: (source: string, externalId: string) => Promise<{
29
+ id: string;
30
+ cancelled: boolean;
31
+ }>;
32
+ requestReview: (input: ReviewRequestInput) => Promise<ReviewRequestResult>;
33
+ importReviews: (source: string, reviews: ReviewImport[]) => Promise<BatchResults>;
34
+ createReferral: (input: ReferralInput) => Promise<ReferralCode>;
35
+ markRewardFulfilled: (rewardId: string) => Promise<{
36
+ id: string;
37
+ fulfilled: boolean;
38
+ }>;
39
+ /** Key numbers, including this month's plan usage. `plan.activitiesLimit` is null when there is no limit. */
40
+ getSummary: (period?: Period) => Promise<Summary>;
41
+ getExperiment: (widgetId: string) => Promise<Experiment>;
42
+ exportCustomer: (subject: PrivacySubject) => Promise<unknown>;
43
+ /** Runs asynchronously in the core. */
44
+ eraseCustomer: (subject: PrivacySubject) => Promise<{
45
+ status: string;
46
+ }>;
47
+ exchangeConnectCode: (input: ConnectExchangeInput) => Promise<ConnectExchangeResult>;
48
+ revokeConnection: () => Promise<{
49
+ status: string;
50
+ }>;
51
+ getSite: () => Promise<SiteInfo>;
52
+ };
53
+ export type ServerClient = ReturnType<typeof createServerClient>;
@@ -0,0 +1,98 @@
1
+ import 'server-only';
2
+ import { normalizeBase, pathKey, ProofhornError, request, WRITE_TIMEOUT_MS } from '../shared/http.js';
3
+ // Also proves in the bundle check that this entry is absent from client output.
4
+ const SERVER_ENTRY_MARKER = '@proofhorn/next/server must run on the server';
5
+ const ACTIVITY_FIELDS = new Set([
6
+ 'source',
7
+ 'externalId',
8
+ 'type',
9
+ 'occurredAt',
10
+ 'item',
11
+ 'actor',
12
+ 'customerRef',
13
+ 'value',
14
+ 'publicDisplay',
15
+ 'conversion',
16
+ 'visitorId',
17
+ 'sessionId',
18
+ 'referralCode',
19
+ ]);
20
+ const ACTOR_FIELDS = new Set(['firstName', 'city', 'countryCode']);
21
+ const ITEM_FIELDS = new Set(['key', 'type', 'title', 'url', 'image']);
22
+ /** A create call the site's plan does not allow (402). Show `upgradeUrl` to the developer or site owner, never to visitors. */
23
+ export class ProofhornPlanLimitError extends ProofhornError {
24
+ upgradeUrl;
25
+ constructor(error) {
26
+ super(error.message, error);
27
+ this.name = 'ProofhornPlanLimitError';
28
+ const url = error.details.upgradeUrl;
29
+ this.upgradeUrl = typeof url === 'string' && url.startsWith('https://') ? url : undefined;
30
+ }
31
+ }
32
+ function rejectExtraFields(value, allowed, prefix) {
33
+ for (const name of Object.keys(value ?? {})) {
34
+ if (!allowed.has(name)) {
35
+ throw new ProofhornError(`${prefix}${name} is not an accepted field`, {
36
+ code: 'invalid_request',
37
+ field: prefix + name,
38
+ });
39
+ }
40
+ }
41
+ }
42
+ /** Types stop this at compile time. This stops JavaScript callers and `any` before personal data leaves the server. */
43
+ function assertActivity(input) {
44
+ rejectExtraFields(input, ACTIVITY_FIELDS, '');
45
+ rejectExtraFields(input.actor, ACTOR_FIELDS, 'actor.');
46
+ rejectExtraFields(input.item, ITEM_FIELDS, 'item.');
47
+ }
48
+ export function createServerClient(options) {
49
+ if (typeof window !== 'undefined') {
50
+ throw new ProofhornError(SERVER_ENTRY_MARKER, { code: 'invalid_config' });
51
+ }
52
+ const { secretKey, apiBase } = options;
53
+ if (!secretKey?.startsWith('sk_')) {
54
+ throw new ProofhornError('secretKey must be a sk_live_ or sk_test_ key', { code: 'invalid_config' });
55
+ }
56
+ const base = `${normalizeBase(apiBase)}/v1`;
57
+ const call = (method, path, json) => request(base + path, {
58
+ method,
59
+ json,
60
+ timeoutMs: WRITE_TIMEOUT_MS,
61
+ headers: { Authorization: `Bearer ${secretKey}` },
62
+ init: { cache: 'no-store' },
63
+ }).catch((error) => {
64
+ throw error instanceof ProofhornError && error.code === 'plan_limit' ? new ProofhornPlanLimitError(error) : error;
65
+ });
66
+ return {
67
+ testMode: secretKey.startsWith('sk_test_'),
68
+ upsertItem: (itemKey, input) => call('PUT', `/items/${pathKey(itemKey, 'itemKey')}`, input),
69
+ upsertItems: (items) => call('POST', '/items/batch', { items }),
70
+ /**
71
+ * Throws `ProofhornError` on failure, so a webhook can respond with an error and be retried.
72
+ * Never refused for plan reasons: past the monthly cap the activity is still recorded.
73
+ */
74
+ recordActivity(input) {
75
+ assertActivity(input);
76
+ return call('POST', '/activities', input);
77
+ },
78
+ recordActivities(activities) {
79
+ activities.forEach(assertActivity);
80
+ return call('POST', '/activities/batch', { activities });
81
+ },
82
+ /** For refunded orders and cancelled enrolments. */
83
+ cancelActivity: (source, externalId) => call('DELETE', `/activities/${encodeURIComponent(source)}/${encodeURIComponent(externalId)}`),
84
+ requestReview: (input) => call('POST', '/review-requests', input),
85
+ importReviews: (source, reviews) => call('POST', '/review-imports', { source, reviews }),
86
+ createReferral: (input) => call('POST', '/referrals', input),
87
+ markRewardFulfilled: (rewardId) => call('POST', `/rewards/${encodeURIComponent(rewardId)}/fulfilled`),
88
+ /** Key numbers, including this month's plan usage. `plan.activitiesLimit` is null when there is no limit. */
89
+ getSummary: (period = '30d') => call('GET', `/summary?period=${period}`),
90
+ getExperiment: (widgetId) => call('GET', `/experiments/${encodeURIComponent(widgetId)}`),
91
+ exportCustomer: (subject) => call('POST', '/privacy/export', subject),
92
+ /** Runs asynchronously in the core. */
93
+ eraseCustomer: (subject) => call('POST', '/privacy/erase', subject),
94
+ exchangeConnectCode: (input) => call('POST', '/connect/exchange', input),
95
+ revokeConnection: () => call('POST', '/connect/revoke'),
96
+ getSite: () => call('GET', '/site'),
97
+ };
98
+ }
@@ -0,0 +1,55 @@
1
+ import 'server-only';
2
+ import type { ReviewPage, Sort } from '../shared/types.js';
3
+ /** The contract makes this label mandatory, so there is no prop to hide or replace it. */
4
+ export declare const INCENTIVE_LABEL = "Incentivized review: the reviewer received a reward for writing it.";
5
+ export type ReviewsProps = {
6
+ itemKey: string;
7
+ page?: number;
8
+ sort?: Sort;
9
+ className?: string;
10
+ };
11
+ export declare function ReviewList({ data, className }: {
12
+ data: ReviewPage;
13
+ className?: string | undefined;
14
+ }): import("react").JSX.Element;
15
+ /** Server-rendered reviews, so they reach crawlers and cannot shift the layout. Renders nothing on failure. */
16
+ export declare function Reviews({ itemKey, page, sort, className }: ReviewsProps): Promise<import("react").JSX.Element | null>;
17
+ export type ReviewJsonLdProps = {
18
+ itemKey: string;
19
+ /** The item's real name. Use this component on item pages only. */
20
+ name: string;
21
+ url?: string;
22
+ image?: string;
23
+ };
24
+ export declare function reviewJsonLd(data: ReviewPage, { name, url, image }: Omit<ReviewJsonLdProps, 'itemKey'>): {
25
+ aggregateRating: {
26
+ '@type': string;
27
+ ratingValue: number;
28
+ reviewCount: number;
29
+ bestRating: number;
30
+ worstRating: number;
31
+ };
32
+ review: {
33
+ reviewBody: string;
34
+ reviewRating: {
35
+ '@type': string;
36
+ ratingValue: number;
37
+ bestRating: number;
38
+ worstRating: number;
39
+ };
40
+ name?: string | undefined;
41
+ '@type': string;
42
+ author: {
43
+ '@type': string;
44
+ name: string;
45
+ };
46
+ datePublished: string;
47
+ }[];
48
+ image?: string | undefined;
49
+ url?: string | undefined;
50
+ '@context': string;
51
+ '@type': string;
52
+ name: string;
53
+ };
54
+ /** Renders `Product` markup only when at least one published review exists. */
55
+ export declare function ReviewJsonLd({ itemKey, name, url, image }: ReviewJsonLdProps): Promise<import("react").JSX.Element | null>;
@@ -0,0 +1,56 @@
1
+ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
+ import 'server-only';
3
+ import { getReviews } from './reads.js';
4
+ /** The contract makes this label mandatory, so there is no prop to hide or replace it. */
5
+ export const INCENTIVE_LABEL = 'Incentivized review: the reviewer received a reward for writing it.';
6
+ const stars = (rating) => '★'.repeat(Math.round(rating)) + '☆'.repeat(5 - Math.round(rating));
7
+ export function ReviewList({ data, className }) {
8
+ return (_jsxs("section", { className: className ?? 'phn-reviews', "aria-label": "Customer reviews", children: [_jsxs("p", { className: "phn-reviews-summary", children: [data.average.toFixed(1), " out of 5 from ", data.total, " ", data.total === 1 ? 'review' : 'reviews'] }), data.reviews.map((review) => (_jsxs("article", { className: "phn-review", children: [_jsx("p", { className: "phn-review-rating", "aria-label": `${review.rating} out of 5`, children: stars(review.rating) }), review.title ? _jsx("h3", { className: "phn-review-title", children: review.title }) : null, _jsxs("p", { className: "phn-review-meta", children: [_jsx("span", { className: "phn-review-author", children: review.author }), review.verified === true ? _jsx("span", { className: "phn-review-verified", children: " Verified" }) : null, ' ', _jsx("time", { dateTime: review.date, children: review.date.slice(0, 10) })] }), review.incentivized === true ? _jsx("p", { className: "phn-review-incentive", children: INCENTIVE_LABEL }) : null, _jsx("p", { className: "phn-review-body", children: review.body }), review.media
9
+ .filter((media) => media.type === 'image')
10
+ .map((media) => (_jsx("img", { className: "phn-review-image", src: media.url, alt: "", width: 120, height: 120, loading: "lazy" }, media.url))), review.reply ? _jsx("p", { className: "phn-review-reply", children: review.reply }) : null] }, review.id)))] }));
11
+ }
12
+ /** Server-rendered reviews, so they reach crawlers and cannot shift the layout. Renders nothing on failure. */
13
+ export async function Reviews({ itemKey, page, sort, className }) {
14
+ const data = await getReviews(itemKey, { page, sort });
15
+ if (!data || data.reviews.length === 0)
16
+ return null;
17
+ return _jsx(ReviewList, { data: data, className: className });
18
+ }
19
+ const MAX_JSON_LD_REVIEWS = 5;
20
+ export function reviewJsonLd(data, { name, url, image }) {
21
+ // JSON-LD has no place for the mandatory incentive label, so those reviews count in the
22
+ // aggregate but are not quoted.
23
+ const quoted = data.reviews.filter((review) => review.incentivized !== true).slice(0, MAX_JSON_LD_REVIEWS);
24
+ return {
25
+ '@context': 'https://schema.org',
26
+ '@type': 'Product',
27
+ name,
28
+ ...(url ? { url } : {}),
29
+ ...(image ? { image } : {}),
30
+ aggregateRating: {
31
+ '@type': 'AggregateRating',
32
+ ratingValue: data.average,
33
+ reviewCount: data.total,
34
+ bestRating: 5,
35
+ worstRating: 1,
36
+ },
37
+ review: quoted.map((review) => ({
38
+ '@type': 'Review',
39
+ author: { '@type': 'Person', name: review.author },
40
+ datePublished: review.date,
41
+ ...(review.title ? { name: review.title } : {}),
42
+ reviewBody: review.body,
43
+ reviewRating: { '@type': 'Rating', ratingValue: review.rating, bestRating: 5, worstRating: 1 },
44
+ })),
45
+ };
46
+ }
47
+ /** Renders `Product` markup only when at least one published review exists. */
48
+ export async function ReviewJsonLd({ itemKey, name, url, image }) {
49
+ const data = await getReviews(itemKey);
50
+ if (!data || data.total < 1)
51
+ return null;
52
+ const props = { name, ...(url ? { url } : {}), ...(image ? { image } : {}) };
53
+ // Review text is untrusted; escaping `<` keeps it from closing the script tag.
54
+ const json = JSON.stringify(reviewJsonLd(data, props)).replace(/</g, '\\u003c');
55
+ return _jsx("script", { type: "application/ld+json", dangerouslySetInnerHTML: { __html: json } });
56
+ }
@@ -0,0 +1,6 @@
1
+ import 'server-only';
2
+ import { type PublicClient } from '../shared/public-client.js';
3
+ import { type ServerClient } from './client.js';
4
+ /** Reads use the public key, so server-rendered pages see what a visitor would see. */
5
+ export declare function publicClientFromEnv(revalidate: number): PublicClient;
6
+ export declare function serverClient(): ServerClient;
@@ -0,0 +1,24 @@
1
+ import 'server-only';
2
+ import { createPublicClient } from '../shared/public-client.js';
3
+ import { ProofhornError } from '../shared/http.js';
4
+ import { createServerClient } from './client.js';
5
+ const apiBase = () => process.env.PROOFHORN_API_URL || undefined;
6
+ /** Reads use the public key, so server-rendered pages see what a visitor would see. */
7
+ export function publicClientFromEnv(revalidate) {
8
+ return createPublicClient({
9
+ publicKey: process.env.NEXT_PUBLIC_PROOFHORN_KEY ?? '',
10
+ apiBase: apiBase(),
11
+ readInit: { next: { revalidate } },
12
+ });
13
+ }
14
+ export function serverClient() {
15
+ const client = createServerClient({ secretKey: process.env.PROOFHORN_SECRET_KEY ?? '', apiBase: apiBase() });
16
+ const publicKey = process.env.NEXT_PUBLIC_PROOFHORN_KEY;
17
+ // Live writes from a test site, or the reverse, would put rows where nobody is looking for them.
18
+ if (publicKey && publicKey.startsWith('pk_test_') !== client.testMode) {
19
+ throw new ProofhornError('NEXT_PUBLIC_PROOFHORN_KEY and PROOFHORN_SECRET_KEY must both be test or both be live', {
20
+ code: 'invalid_config',
21
+ });
22
+ }
23
+ return client;
24
+ }
@@ -0,0 +1,20 @@
1
+ import 'server-only';
2
+ import type { ActivityInput, ExactActivity, ItemInput, PrivacySubject, ReferralInput, ReviewRequestInput } from '../shared/types.js';
3
+ export { createServerClient, ProofhornPlanLimitError, type ServerClient, type ServerClientOptions } from './client.js';
4
+ export { Reviews, ReviewJsonLd, INCENTIVE_LABEL, type ReviewsProps, type ReviewJsonLdProps } from './components.js';
5
+ export { getReviews, getRatings } from './reads.js';
6
+ export { verifyWebhook } from './webhook.js';
7
+ export { ProofhornError } from '../shared/http.js';
8
+ export { createPublicClient, type PublicClient, type PublicClientOptions } from '../shared/public-client.js';
9
+ export type * from '../shared/types.js';
10
+ /** Records something real that happened. Pass `getVisitor()`'s IDs for A/B and holdout attribution. */
11
+ export declare function recordActivity<T extends ActivityInput>(input: ExactActivity<T>): Promise<import("../shared/types.js").WriteResult>;
12
+ export declare function upsertItem(itemKey: string, input: ItemInput): Promise<{
13
+ item: import("../shared/types.js").Item;
14
+ }>;
15
+ /** Schedules a review request email. Send one for every eligible customer; do not filter by expected satisfaction. */
16
+ export declare function requestReview(input: ReviewRequestInput): Promise<import("../shared/types.js").ReviewRequestResult>;
17
+ export declare function createReferral(input: ReferralInput): Promise<import("../shared/types.js").ReferralCode>;
18
+ export declare function eraseCustomer(subject: PrivacySubject): Promise<{
19
+ status: string;
20
+ }>;
@@ -0,0 +1,26 @@
1
+ import 'server-only';
2
+ import { serverClient } from './env.js';
3
+ export { createServerClient, ProofhornPlanLimitError } from './client.js';
4
+ export { Reviews, ReviewJsonLd, INCENTIVE_LABEL } from './components.js';
5
+ export { getReviews, getRatings } from './reads.js';
6
+ export { verifyWebhook } from './webhook.js';
7
+ export { ProofhornError } from '../shared/http.js';
8
+ export { createPublicClient } from '../shared/public-client.js';
9
+ // Helpers read PROOFHORN_SECRET_KEY on each call. All of them throw ProofhornError on failure.
10
+ /** Records something real that happened. Pass `getVisitor()`'s IDs for A/B and holdout attribution. */
11
+ export function recordActivity(input) {
12
+ return serverClient().recordActivity(input);
13
+ }
14
+ export function upsertItem(itemKey, input) {
15
+ return serverClient().upsertItem(itemKey, input);
16
+ }
17
+ /** Schedules a review request email. Send one for every eligible customer; do not filter by expected satisfaction. */
18
+ export function requestReview(input) {
19
+ return serverClient().requestReview(input);
20
+ }
21
+ export function createReferral(input) {
22
+ return serverClient().createReferral(input);
23
+ }
24
+ export function eraseCustomer(subject) {
25
+ return serverClient().eraseCustomer(subject);
26
+ }
@@ -0,0 +1,7 @@
1
+ import 'server-only';
2
+ import type { ReviewsQuery } from '../shared/public-client.js';
3
+ import type { Rating, ReviewPage } from '../shared/types.js';
4
+ /** Published reviews, cached for about 60 seconds. Returns null on any failure so a page never breaks. */
5
+ export declare function getReviews(itemKey: string, query?: ReviewsQuery): Promise<ReviewPage | null>;
6
+ /** Star badge data for up to 50 items, cached for about 60 seconds. Returns null on any failure. */
7
+ export declare function getRatings(itemKeys: string[]): Promise<Record<string, Rating> | null>;
@@ -0,0 +1,21 @@
1
+ import 'server-only';
2
+ import { publicClientFromEnv } from './env.js';
3
+ const REVALIDATE_SECONDS = 60;
4
+ /** Published reviews, cached for about 60 seconds. Returns null on any failure so a page never breaks. */
5
+ export async function getReviews(itemKey, query = {}) {
6
+ try {
7
+ return await publicClientFromEnv(REVALIDATE_SECONDS).getItemReviews(itemKey, query);
8
+ }
9
+ catch {
10
+ return null;
11
+ }
12
+ }
13
+ /** Star badge data for up to 50 items, cached for about 60 seconds. Returns null on any failure. */
14
+ export async function getRatings(itemKeys) {
15
+ try {
16
+ return await publicClientFromEnv(REVALIDATE_SECONDS).getRatings(itemKeys);
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }
@@ -0,0 +1,7 @@
1
+ import 'server-only';
2
+ /**
3
+ * Checks a `Proofhorn-Signature` header against the raw request body. Read the body with `request.text()`;
4
+ * parsing and re-serialising JSON changes the bytes. Delivery is at least once, so dedupe on the event `id` too.
5
+ * Returns false for anything invalid and never throws.
6
+ */
7
+ export declare function verifyWebhook(rawBody: string | Uint8Array<ArrayBuffer>, header: string | null | undefined, secret: string): Promise<boolean>;
@@ -0,0 +1,41 @@
1
+ import 'server-only';
2
+ const TOLERANCE_SECONDS = 5 * 60;
3
+ function hexToBytes(hex) {
4
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex))
5
+ return null;
6
+ const bytes = new Uint8Array(hex.length / 2);
7
+ for (let i = 0; i < bytes.length; i++)
8
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
9
+ return bytes;
10
+ }
11
+ /**
12
+ * Checks a `Proofhorn-Signature` header against the raw request body. Read the body with `request.text()`;
13
+ * parsing and re-serialising JSON changes the bytes. Delivery is at least once, so dedupe on the event `id` too.
14
+ * Returns false for anything invalid and never throws.
15
+ */
16
+ export async function verifyWebhook(rawBody, header, secret) {
17
+ if (!header || !secret)
18
+ return false;
19
+ const parts = header.split(',').map((part) => part.trim().split('='));
20
+ const timestamp = parts.find(([name]) => name === 't')?.[1];
21
+ const signatures = parts.filter(([name]) => name === 'v1').map(([, value]) => hexToBytes(value ?? ''));
22
+ if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0)
23
+ return false;
24
+ if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS)
25
+ return false;
26
+ const encoder = new TextEncoder();
27
+ const body = typeof rawBody === 'string' ? encoder.encode(rawBody) : rawBody;
28
+ const prefix = encoder.encode(`${timestamp}.`);
29
+ const signed = new Uint8Array(prefix.length + body.length);
30
+ signed.set(prefix);
31
+ signed.set(body, prefix.length);
32
+ // WebCrypto's verify compares in constant time and also works in the Edge runtime.
33
+ const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [
34
+ 'verify',
35
+ ]);
36
+ for (const signature of signatures) {
37
+ if (signature && (await crypto.subtle.verify('HMAC', key, signature, signed)))
38
+ return true;
39
+ }
40
+ return false;
41
+ }
@@ -0,0 +1,38 @@
1
+ export declare const DEFAULT_API_BASE = "https://proofhorn.khushrav.com";
2
+ export declare const READ_TIMEOUT_MS = 2000;
3
+ export declare const WRITE_TIMEOUT_MS = 8000;
4
+ export declare const UPLOAD_TIMEOUT_MS = 30000;
5
+ export type ErrorInfo = {
6
+ code: string;
7
+ status?: number;
8
+ field?: string;
9
+ requestId?: string;
10
+ retryAfter?: number;
11
+ details?: Record<string, unknown>;
12
+ };
13
+ /** Every failed call throws this. A webhook handler can check `retryable` to decide its response. */
14
+ export declare class ProofhornError extends Error {
15
+ readonly code: string;
16
+ readonly status: number | undefined;
17
+ readonly field: string | undefined;
18
+ readonly requestId: string | undefined;
19
+ /** Seconds, from the `Retry-After` header. */
20
+ readonly retryAfter: number | undefined;
21
+ /** The `error` object from the response body, including any fields this version does not know. */
22
+ readonly details: Record<string, unknown>;
23
+ constructor(message: string, info: ErrorInfo);
24
+ get retryable(): boolean;
25
+ }
26
+ export declare function normalizeBase(base?: string): string;
27
+ /** Item keys, referral codes and customer refs share one pattern. `.` and `..` match it but would rewrite the path. */
28
+ export declare function pathKey(value: string, field: string): string;
29
+ export type RequestOptions = {
30
+ method?: string;
31
+ headers?: Record<string, string>;
32
+ json?: unknown;
33
+ body?: BodyInit;
34
+ timeoutMs: number;
35
+ /** Extra fetch options, such as Next's `next: { revalidate }` or `cache`. */
36
+ init?: Record<string, unknown>;
37
+ };
38
+ export declare function request<T>(url: string, options: RequestOptions): Promise<T>;
@@ -0,0 +1,81 @@
1
+ export const DEFAULT_API_BASE = 'https://proofhorn.khushrav.com';
2
+ export const READ_TIMEOUT_MS = 2000;
3
+ export const WRITE_TIMEOUT_MS = 8000;
4
+ export const UPLOAD_TIMEOUT_MS = 30000;
5
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
6
+ const KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
7
+ /** Every failed call throws this. A webhook handler can check `retryable` to decide its response. */
8
+ export class ProofhornError extends Error {
9
+ code;
10
+ status;
11
+ field;
12
+ requestId;
13
+ /** Seconds, from the `Retry-After` header. */
14
+ retryAfter;
15
+ /** The `error` object from the response body, including any fields this version does not know. */
16
+ details;
17
+ constructor(message, info) {
18
+ super(message);
19
+ this.name = 'ProofhornError';
20
+ this.code = info.code;
21
+ this.status = info.status;
22
+ this.field = info.field;
23
+ this.requestId = info.requestId;
24
+ this.retryAfter = info.retryAfter;
25
+ this.details = info.details ?? {};
26
+ }
27
+ get retryable() {
28
+ return (this.code === 'network_error' ||
29
+ this.code === 'timeout' ||
30
+ this.status === 429 ||
31
+ (this.status !== undefined && this.status >= 500));
32
+ }
33
+ }
34
+ export function normalizeBase(base = DEFAULT_API_BASE) {
35
+ const url = new URL(base);
36
+ if (url.protocol !== 'https:' && !LOCAL_HOSTS.has(url.hostname)) {
37
+ throw new ProofhornError('apiBase must use https outside localhost', { code: 'invalid_config' });
38
+ }
39
+ return url.origin + url.pathname.replace(/\/+$/, '');
40
+ }
41
+ /** Item keys, referral codes and customer refs share one pattern. `.` and `..` match it but would rewrite the path. */
42
+ export function pathKey(value, field) {
43
+ if (!KEY_PATTERN.test(value) || value === '.' || value === '..') {
44
+ throw new ProofhornError(`${field} is not a valid key`, { code: 'invalid_request', field });
45
+ }
46
+ return encodeURIComponent(value);
47
+ }
48
+ export async function request(url, options) {
49
+ const { method = 'GET', json, timeoutMs, init } = options;
50
+ const headers = { Accept: 'application/json', ...options.headers };
51
+ let body = options.body;
52
+ if (json !== undefined) {
53
+ headers['Content-Type'] = 'application/json';
54
+ body = JSON.stringify(json);
55
+ }
56
+ let response;
57
+ try {
58
+ response = await fetch(url, { ...init, method, headers, body, signal: AbortSignal.timeout(timeoutMs) });
59
+ }
60
+ catch (error) {
61
+ const timedOut = error instanceof Error && error.name === 'TimeoutError';
62
+ throw new ProofhornError(timedOut ? 'Request timed out' : 'Network request failed', {
63
+ code: timedOut ? 'timeout' : 'network_error',
64
+ });
65
+ }
66
+ if (response.status === 204)
67
+ return undefined;
68
+ const payload = await response.json().catch(() => null);
69
+ if (response.ok && payload !== null)
70
+ return payload;
71
+ const detail = payload?.error ?? {};
72
+ const retryAfter = Number(response.headers.get('Retry-After'));
73
+ throw new ProofhornError(detail.message ?? `Request failed with status ${response.status}`, {
74
+ code: detail.code ?? 'server_error',
75
+ status: response.status,
76
+ field: detail.field,
77
+ requestId: detail.requestId,
78
+ retryAfter: retryAfter > 0 ? retryAfter : undefined,
79
+ details: detail,
80
+ });
81
+ }
@@ -0,0 +1,32 @@
1
+ import { type EventBatch, type Rating, type ReferralLookup, type ReviewPage, type ReviewRequestPrefill, type SiteConfig, type Sort, type SubmitReviewInput, type SubmitReviewResult } from './types.js';
2
+ export type PublicClientOptions = {
3
+ publicKey: string;
4
+ apiBase?: string;
5
+ /** Extra fetch options for reads, such as Next's `next: { revalidate }`. */
6
+ readInit?: Record<string, unknown>;
7
+ };
8
+ export type ReviewsQuery = {
9
+ page?: number;
10
+ sort?: Sort;
11
+ };
12
+ export type SiteReviewsQuery = ReviewsQuery & {
13
+ minRating?: number;
14
+ withMedia?: boolean;
15
+ };
16
+ export declare function createPublicClient(options: PublicClientOptions): {
17
+ testMode: boolean;
18
+ getConfig: () => Promise<SiteConfig>;
19
+ getItemReviews: (itemKey: string, q?: ReviewsQuery) => Promise<ReviewPage>;
20
+ getSiteReviews: (q?: SiteReviewsQuery) => Promise<ReviewPage>;
21
+ getRatings(itemKeys: string[]): Promise<Record<string, Rating>>;
22
+ /** Analytics beacon. Never throws and has no result, as the endpoint itself returns no body. */
23
+ sendEvents(batch: EventBatch): void;
24
+ submitReview(input: SubmitReviewInput): Promise<SubmitReviewResult>;
25
+ getReviewRequest: (token: string) => Promise<ReviewRequestPrefill>;
26
+ /** Accepts one JPEG, PNG or WebP image of at most 8MB. */
27
+ uploadReviewMedia(file: Blob, token?: string): Promise<{
28
+ id: string;
29
+ }>;
30
+ getReferral: (code: string) => Promise<ReferralLookup>;
31
+ };
32
+ export type PublicClient = ReturnType<typeof createPublicClient>;