prizerail 0.0.0-stage → 0.1.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/errors.js ADDED
@@ -0,0 +1,42 @@
1
+ /** An error response from the API, or a request that never got one. */
2
+ export class PrizerailError extends Error {
3
+ /** The HTTP status. 0 when the request failed before a response. */
4
+ status;
5
+ /** The API's error code, like `not_found` or `no_open_drawing`. */
6
+ code;
7
+ detail;
8
+ constructor(status, code, detail) {
9
+ super(detail ? `${code}: ${detail}` : code);
10
+ this.name = "PrizerailError";
11
+ this.status = status;
12
+ this.code = code;
13
+ this.detail = detail;
14
+ }
15
+ }
16
+ /**
17
+ * A send stopped so that no entry lands in the drawing after the one it
18
+ * targeted. Entries past `progress.sent` were not confirmed: check with
19
+ * `entries.list({ drawing })` before sending them to the next drawing.
20
+ */
21
+ export class PrizerailCutoffError extends PrizerailError {
22
+ progress;
23
+ cause;
24
+ constructor(detail, progress, cause) {
25
+ super(0, "cutoff_reached", detail);
26
+ this.name = "PrizerailCutoffError";
27
+ this.progress = progress;
28
+ this.cause = cause;
29
+ }
30
+ }
31
+ /** A batch went to a different drawing from the rest of the send. */
32
+ export class PrizerailDrawingChangedError extends PrizerailError {
33
+ progress;
34
+ /** Where the last batch went. */
35
+ landedIn;
36
+ constructor(progress, landedIn) {
37
+ super(0, "drawing_changed", `A batch went to drawing ${landedIn.id}, not ${progress.drawing.id}. Its cutoff passed mid-send.`);
38
+ this.name = "PrizerailDrawingChangedError";
39
+ this.progress = progress;
40
+ this.landedIn = landedIn;
41
+ }
42
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ export type HttpOptions = {
2
+ apiKey?: string;
3
+ baseUrl: string;
4
+ fetch: typeof fetch;
5
+ /** Per attempt. */
6
+ timeoutMs: number;
7
+ /** Retries after the first attempt, for 429s, 5xx and network errors. */
8
+ maxRetries: number;
9
+ userAgent: string;
10
+ };
11
+ export type RequestOptions = {
12
+ query?: Record<string, string | number | undefined>;
13
+ body?: unknown;
14
+ /**
15
+ * No retry is started that would wait until this time, in ms since the
16
+ * epoch. `onDeadline` builds the error thrown instead.
17
+ */
18
+ deadline?: number;
19
+ onDeadline?: (error: unknown) => Error;
20
+ };
21
+ /** A server that asks for a longer wait than this gets the error instead. */
22
+ export declare const MAX_RETRY_AFTER_MS: number;
23
+ /** Retry-After as ms from now: delta seconds or an HTTP date. */
24
+ export declare function parseRetryAfter(value: string | null, now?: number): number | null;
25
+ /** Full jitter, with Retry-After as the floor when the server sent one. */
26
+ export declare function retryDelay(attempt: number, retryAfterMs: number | null): number;
27
+ export declare class Http {
28
+ readonly options: HttpOptions;
29
+ constructor(options: HttpOptions);
30
+ url(path: string, query?: RequestOptions["query"]): string;
31
+ /** JSON from the partner API, with retries. Throws PrizerailError. */
32
+ request<T>(method: "GET" | "POST", path: string, { query, body, deadline, onDeadline }?: RequestOptions): Promise<T>;
33
+ /** Public JSON, like a draw's proof, with no key and no retries. */
34
+ getPublic<T>(url: string): Promise<T>;
35
+ }
package/dist/http.js ADDED
@@ -0,0 +1,138 @@
1
+ import { PrizerailError } from "./errors.js";
2
+ const BASE_DELAY_MS = 1000;
3
+ const MAX_DELAY_MS = 30_000;
4
+ /** A server that asks for a longer wait than this gets the error instead. */
5
+ export const MAX_RETRY_AFTER_MS = 5 * 60_000;
6
+ /** Retry-After as ms from now: delta seconds or an HTTP date. */
7
+ export function parseRetryAfter(value, now = Date.now()) {
8
+ if (!value)
9
+ return null;
10
+ const trimmed = value.trim();
11
+ if (/^\d+$/.test(trimmed)) {
12
+ return Number(trimmed) * 1000;
13
+ }
14
+ const at = Date.parse(trimmed);
15
+ if (Number.isNaN(at))
16
+ return null;
17
+ return Math.max(at - now, 0);
18
+ }
19
+ /** Full jitter, with Retry-After as the floor when the server sent one. */
20
+ export function retryDelay(attempt, retryAfterMs) {
21
+ const ceiling = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
22
+ const jitter = Math.random() * ceiling;
23
+ return retryAfterMs === null ? jitter : Math.max(retryAfterMs, jitter);
24
+ }
25
+ const retryable = (status) => status === 429 || (status >= 500 && status !== 501);
26
+ async function errorFrom(res) {
27
+ const text = await res.text().catch(() => "");
28
+ try {
29
+ const body = JSON.parse(text);
30
+ if (typeof body.error === "string") {
31
+ return new PrizerailError(res.status, body.error, typeof body.detail === "string" ? body.detail : undefined);
32
+ }
33
+ }
34
+ catch {
35
+ // Not JSON, from a proxy or CDN. Keep the start of it.
36
+ }
37
+ return new PrizerailError(res.status, `http_${res.status}`, text.slice(0, 200) || res.statusText || undefined);
38
+ }
39
+ /**
40
+ * A 2xx body as JSON. A body that isn't JSON is a broken response, not a
41
+ * network error, so it isn't retried: a POST may already be stored.
42
+ */
43
+ function parseBody(res, text) {
44
+ try {
45
+ return JSON.parse(text);
46
+ }
47
+ catch {
48
+ throw new PrizerailError(res.status, "invalid_response", `The API answered ${res.status} with a body that isn't JSON: ${text.slice(0, 200)}`);
49
+ }
50
+ }
51
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
52
+ export class Http {
53
+ options;
54
+ constructor(options) {
55
+ this.options = options;
56
+ }
57
+ url(path, query) {
58
+ const url = new URL(path.replace(/^\//, ""), `${this.options.baseUrl}/`);
59
+ for (const [k, v] of Object.entries(query ?? {})) {
60
+ if (v !== undefined)
61
+ url.searchParams.set(k, String(v));
62
+ }
63
+ return url.href;
64
+ }
65
+ /** JSON from the partner API, with retries. Throws PrizerailError. */
66
+ async request(method, path, { query, body, deadline, onDeadline } = {}) {
67
+ const { apiKey, fetch, timeoutMs, maxRetries, userAgent } = this.options;
68
+ if (!apiKey) {
69
+ throw new PrizerailError(0, "no_api_key", "Pass apiKey to new Prizerail() to call the partner API.");
70
+ }
71
+ const url = this.url(path, query);
72
+ for (let attempt = 0;; attempt++) {
73
+ let failure;
74
+ let retryAfterMs = null;
75
+ let res = null;
76
+ let text = "";
77
+ try {
78
+ res = await fetch(url, {
79
+ method,
80
+ headers: {
81
+ authorization: `Bearer ${apiKey}`,
82
+ accept: "application/json",
83
+ "user-agent": userAgent,
84
+ ...(body === undefined
85
+ ? {}
86
+ : { "content-type": "application/json" }),
87
+ },
88
+ body: body === undefined ? undefined : JSON.stringify(body),
89
+ signal: AbortSignal.timeout(timeoutMs),
90
+ });
91
+ if (res.ok)
92
+ text = await res.text();
93
+ }
94
+ catch (error) {
95
+ // No response, or the body was cut off: a timeout or network error.
96
+ res = null;
97
+ failure = new PrizerailError(0, "network_error", error instanceof Error ? error.message : String(error));
98
+ }
99
+ if (res?.ok)
100
+ return parseBody(res, text);
101
+ if (res) {
102
+ const error = await errorFrom(res);
103
+ if (!retryable(res.status))
104
+ throw error;
105
+ failure = error;
106
+ retryAfterMs = parseRetryAfter(res.headers.get("retry-after"));
107
+ }
108
+ // Set on every path that gets here.
109
+ const last = failure;
110
+ if (attempt >= maxRetries)
111
+ throw last;
112
+ if (retryAfterMs !== null && retryAfterMs > MAX_RETRY_AFTER_MS)
113
+ throw last;
114
+ const wait = retryDelay(attempt, retryAfterMs);
115
+ if (deadline !== undefined && Date.now() + wait >= deadline) {
116
+ throw onDeadline ? onDeadline(last) : last;
117
+ }
118
+ await sleep(wait);
119
+ // Timers can fire late, after a sleep or a busy event loop.
120
+ if (deadline !== undefined && Date.now() >= deadline) {
121
+ throw onDeadline ? onDeadline(last) : last;
122
+ }
123
+ }
124
+ }
125
+ /** Public JSON, like a draw's proof, with no key and no retries. */
126
+ async getPublic(url) {
127
+ const res = await this.options.fetch(url, {
128
+ headers: {
129
+ accept: "application/json",
130
+ "user-agent": this.options.userAgent,
131
+ },
132
+ signal: AbortSignal.timeout(this.options.timeoutMs),
133
+ });
134
+ if (!res.ok)
135
+ throw await errorFrom(res);
136
+ return parseBody(res, await res.text());
137
+ }
138
+ }
@@ -0,0 +1,5 @@
1
+ export { CampaignClient, DrawingsClient, ENTRIES_PER_REQUEST, EntriesClient, Prizerail, type PrizerailOptions, type SendOptions, type SendResult, VERSION, } from "./client.js";
2
+ export { hashEntrant } from "./entrant.js";
3
+ export { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, type SendProgress, } from "./errors.js";
4
+ export type * from "./types.js";
5
+ export { type Check, type DrawProof, type EntrantRow, type VerifyOptions, type VerifyResult, verifyDraw, wasEntered, } from "./verify.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { CampaignClient, DrawingsClient, ENTRIES_PER_REQUEST, EntriesClient, Prizerail, VERSION, } from "./client.js";
2
+ export { hashEntrant } from "./entrant.js";
3
+ export { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, } from "./errors.js";
4
+ export { verifyDraw, wasEntered, } from "./verify.js";
@@ -0,0 +1,169 @@
1
+ /** Shapes the Prizerail partner API returns, as documented at docs.prizerail.com. */
2
+ export type CampaignStatus = "draft" | "active" | "paused" | "ended";
3
+ export type Cadence = "hourly" | "daily" | "weekly" | "monthly";
4
+ export type DrawingStatus = "open" | "locked" | "entropy_requested" | "settled" | "paid";
5
+ export type DrawingKind = "regular" | "guarantee";
6
+ export type PayoutKind = "lump_sum" | "large_prize" | "guarantee";
7
+ export type PayoutStatus = "pending" | "submitted" | "confirmed" | "failed" | "held_manual";
8
+ export type GuaranteeStatus = "not_needed" | "drawn" | "skipped";
9
+ export type PrizeTier = {
10
+ amountCents: number;
11
+ /** A tier wins on `weight` of the table's `denominator` rolls. */
12
+ weight: number;
13
+ /** One winner's chance of this prize, from 0 to 1. */
14
+ odds: number;
15
+ };
16
+ export type PrizeTable = {
17
+ id: string;
18
+ version: number;
19
+ denominator: number;
20
+ /** Top prize first. */
21
+ tiers: PrizeTier[];
22
+ averagePrizeCents: number;
23
+ };
24
+ export type Campaign = {
25
+ slug: string;
26
+ name: string;
27
+ status: CampaignStatus;
28
+ /** The public campaign page. */
29
+ page: string;
30
+ schedule: {
31
+ cadence: Cadence;
32
+ drawHour: number | null;
33
+ drawMinute: number | null;
34
+ drawWeekday: number | null;
35
+ drawDayOfMonth: number | null;
36
+ timezone: string;
37
+ cutoffMinutes: number;
38
+ startsAt: string | null;
39
+ endsAt: string | null;
40
+ };
41
+ winnersPerDraw: number;
42
+ prizeTable: PrizeTable | null;
43
+ guarantee: {
44
+ amountCents: number;
45
+ thresholdCents: number;
46
+ periodDays: number;
47
+ } | null;
48
+ largePrizeThresholdCents: number | null;
49
+ termsUrl: string;
50
+ privacyUrl: string;
51
+ nextDrawing: {
52
+ id: string;
53
+ drawAt: string;
54
+ cutoffAt: string;
55
+ winnersPerDraw: number;
56
+ averagePrizeCents: number | null;
57
+ } | null;
58
+ };
59
+ export type DrawingRef = {
60
+ id: string;
61
+ drawAt: string;
62
+ cutoffAt: string;
63
+ };
64
+ export type Winner = {
65
+ position: number;
66
+ winner: string;
67
+ displayName: string | null;
68
+ avatarUrl: string | null;
69
+ /** The rest is set once the drawing settles. */
70
+ randomValue?: string;
71
+ roll?: number;
72
+ amountCents?: number;
73
+ heldForManualPayout?: boolean;
74
+ };
75
+ export type Payout = {
76
+ id: string;
77
+ kind: PayoutKind;
78
+ amountCents: number;
79
+ status: PayoutStatus;
80
+ chain: string;
81
+ token: string;
82
+ to: string;
83
+ txHash: string | null;
84
+ confirmedAt: string | null;
85
+ /** The winner a large-prize or guarantee payout is for. Null for the lump sum. */
86
+ winnerPosition: number | null;
87
+ };
88
+ export type Drawing = {
89
+ id: string;
90
+ kind: DrawingKind;
91
+ number: number | null;
92
+ drawAt: string;
93
+ cutoffAt: string;
94
+ status: DrawingStatus;
95
+ winnersExpected: number;
96
+ prizeTable: PrizeTable | null;
97
+ needsAttention: string | null;
98
+ winners: Winner[];
99
+ payouts: Payout[];
100
+ verification: {
101
+ winnersCommitment: string | null;
102
+ lockedAt: string | null;
103
+ entropyProvider: string | null;
104
+ entropyRequestId: string | null;
105
+ entropy: string | null;
106
+ entropyRevealedAt: string | null;
107
+ chain: Record<string, unknown> | null;
108
+ prizeTableId: string | null;
109
+ };
110
+ };
111
+ export type DrawingsPage = {
112
+ drawings: Drawing[];
113
+ nextBefore: string | null;
114
+ nextAfter: string | null;
115
+ };
116
+ /** An entrant id, or an id with a weight and how they show if they win. */
117
+ export type Entry = string | {
118
+ entrantId: string;
119
+ /** Whole number from 1. Leave it out and it's 1. */
120
+ weight?: number;
121
+ /** Up to 40 characters. */
122
+ displayName?: string;
123
+ /** https, up to 2,048 characters. */
124
+ avatarUrl?: string;
125
+ };
126
+ export type SendEntriesResponse = {
127
+ drawing: DrawingRef;
128
+ added: number;
129
+ updated: number;
130
+ unchanged: number;
131
+ /** The drawing's totals so far. */
132
+ count: number;
133
+ totalWeight: number;
134
+ };
135
+ export type SentEntry = {
136
+ entrantId: string;
137
+ weight: number;
138
+ displayName: string | null;
139
+ avatarUrl: string | null;
140
+ /** Place in the locked list. Null until the cutoff. */
141
+ position: number | null;
142
+ receivedAt: string;
143
+ };
144
+ export type EntriesPage = {
145
+ drawing: DrawingRef & {
146
+ status: DrawingStatus;
147
+ };
148
+ count: number;
149
+ totalWeight: number;
150
+ entries: SentEntry[];
151
+ /** Pass as `after` for the next page. Null on the last. */
152
+ next: string | null;
153
+ };
154
+ export type Guarantee = {
155
+ id: string;
156
+ period: number;
157
+ periodStart: string;
158
+ periodEnd: string;
159
+ status: GuaranteeStatus;
160
+ amountCents: number | null;
161
+ drawing: {
162
+ id: string;
163
+ number: number | null;
164
+ status: DrawingStatus;
165
+ entrants: number | null;
166
+ winner: string | null;
167
+ displayName: string | null;
168
+ } | null;
169
+ };
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Shapes the Prizerail partner API returns, as documented at docs.prizerail.com. */
2
+ export {};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Types for verify-draw.mjs, the public verify script, which this package
3
+ * ships unchanged (a test checks it matches public/verify/verify-draw.mjs).
4
+ */
5
+ export type Check = { ok: boolean | null; label: string; detail?: string };
6
+ /** [index, keccak256(entrantId), weight] */
7
+ export type EntrantRow = [number, string, number];
8
+ export function keccak256(bytes: Uint8Array): string;
9
+ export function winnerHash(winner: string): string;
10
+ export function entrantsRoot(list: [string, number][]): string;
11
+ export function verifyProof(proof: unknown, entrants?: EntrantRow[]): Check[];
12
+ export function readEntrants(
13
+ source: string,
14
+ options?: { fetch?: typeof fetch; timeoutMs?: number }
15
+ ): Promise<EntrantRow[]>;