prizerail 0.0.1 → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Coordination Labs
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,7 +1,134 @@
1
1
  # prizerail
2
2
 
3
- Command line tools for [Prizerail](https://www.prizerail.com), coming soon.
3
+ The Prizerail SDK for JavaScript and TypeScript. Send entries, read results and prizes, and verify any draw from its public proof.
4
4
 
5
- The first command will be `npx prizerail verify <proof url>`, which checks a draw using only public data. Until then, use the verify script at https://www.prizerail.com/verify/verify-draw.mjs.
5
+ - Typed client for the [partner API](https://docs.prizerail.com/api/authentication), with paging and safe retries.
6
+ - `verifyDraw`, the same checks as the public verify script, plus `wasEntered` to find someone in a locked list.
7
+ - `npx prizerail verify` from the command line.
8
+ - No dependencies. Node 20 or later, Deno, Bun, and edge runtimes with `fetch` and WebCrypto.
6
9
 
7
- The API client will be published as `@prizerail/sdk`.
10
+ ```sh
11
+ npm install prizerail
12
+ ```
13
+
14
+ The API is early (v0.x), so names can change between minor versions. 0.2.0 says `entries` where 0.1.0 said `weight`: an entrant is `{ entrantId, entries }`, and totals are `entrantCount` and `totalEntries`. The old names still work, marked deprecated. Each change is in the [changelog](https://docs.prizerail.com/changelog).
15
+
16
+ ## Send entries
17
+
18
+ ```ts
19
+ import { Prizerail, hashEntrant } from "prizerail"
20
+
21
+ const prizerail = new Prizerail({ apiKey: process.env.PRIZERAIL_API_KEY })
22
+ const campaign = prizerail.campaign("your-campaign")
23
+
24
+ const entries = await Promise.all(
25
+ users.map(async user => ({
26
+ entrantId: await hashEntrant(user.id, process.env.ENTRANT_ID_KEY!),
27
+ entries: user.tickets,
28
+ }))
29
+ )
30
+
31
+ const result = await campaign.entries.send(entries)
32
+ // { drawing: { id, drawAt, cutoffAt }, sent, added, updated, unchanged, entrantCount, totalEntries, batches }
33
+ ```
34
+
35
+ `entrantCount` and `totalEntries` are the drawing's own totals, so reconcile with those. `added`, `updated` and `unchanged` add up what each batch reported, and a batch that was stored before its response was lost comes back as `unchanged` on the retry.
36
+
37
+ `send` takes any number of entries and sends them in requests of 1,000. It retries a `429`, a `5xx`, a timeout or a network error with a jittered, growing wait, and honors `Retry-After`.
38
+
39
+ Sending an entrant again before the cutoff only sets their entries, so a retry is safe until then. After the cutoff a retry would go to the next drawing, so every send is pinned to one drawing:
40
+
41
+ - Before the first batch it reads which drawing is taking entries, or uses the `drawing` you pass.
42
+ - It sends no batch and starts no retry within the request timeout (30 seconds) of that drawing's cutoff. It throws `PrizerailCutoffError` instead.
43
+ - If a batch still lands in another drawing, it throws `PrizerailDrawingChangedError`.
44
+
45
+ Both errors carry `progress`, which says how many entries the drawing confirmed. Check what it has with `entries.list({ drawing })` before you send the rest.
46
+
47
+ ```ts
48
+ import { PrizerailCutoffError } from "prizerail"
49
+
50
+ try {
51
+ await campaign.entries.send(entries)
52
+ } catch (error) {
53
+ if (!(error instanceof PrizerailCutoffError)) throw error
54
+ console.log(`${error.progress.sent} sent to ${error.progress.drawing.id}`)
55
+ }
56
+ ```
57
+
58
+ ### Entrant ids
59
+
60
+ Every locked list is published, hashed. Use an id that can't be guessed or linked back to a person. `hashEntrant(userId, key)` gives the HMAC-SHA256 of the user id as hex, the same as Node's `createHmac("sha256", key).update(id).digest("hex")`. Keep the key secret, and fixed for the life of the campaign. See [Entrant ids](https://docs.prizerail.com/getting-started/concepts#make-entrant-ids-with-an-hmac).
61
+
62
+ ### Check what Prizerail has
63
+
64
+ ```ts
65
+ let total = 0
66
+ for await (const entrant of campaign.entries.all()) total += entrant.entries
67
+ ```
68
+
69
+ `entries.all()` pages through the drawing taking entries now, pinned to it after the first page. Pass `{ drawing: id }` for another drawing.
70
+
71
+ ## Results and prizes
72
+
73
+ ```ts
74
+ const info = await campaign.get()
75
+ // schedule, prizeTable.tiers with odds, guarantee, nextDrawing, termsUrl
76
+
77
+ const latest = await campaign.drawings.latest()
78
+ // the newest settled or paid drawing, with winners and payouts
79
+
80
+ for await (const drawing of campaign.drawings.all({ status: "paid" })) {
81
+ console.log(drawing.number, drawing.winners)
82
+ }
83
+
84
+ const guarantees = await campaign.guarantees.list()
85
+ ```
86
+
87
+ ## Draw now, in test
88
+
89
+ In the test environment, `campaign.drawings.run(id)` closes a drawing's entries now and draws it, so you can see a whole draw without waiting for its cutoff. It resolves with the drawing, usually settled within seconds. Anywhere else it throws a `PrizerailError` with code `test_only`. See [Draw now](https://docs.prizerail.com/api/drawings#draw-now-test-only).
90
+
91
+ ## Errors
92
+
93
+ Every API error is a `PrizerailError` with the HTTP `status`, the API's `code` (like `not_found` or `no_open_drawing`) and a `detail`. A request that never got a response has status 0 and code `network_error`. See [Errors](https://docs.prizerail.com/api/errors).
94
+
95
+ ## Verify a draw
96
+
97
+ Anyone can check a draw from its public proof, with no API key.
98
+
99
+ ```ts
100
+ import { verifyDraw, wasEntered } from "prizerail"
101
+
102
+ const result = await verifyDraw(
103
+ "https://www.prizerail.com/campaigns/your-campaign/draws/DRAWING_ID/proof.json"
104
+ )
105
+ result.ok // true when every check passes
106
+ result.checks // [{ ok, label, detail }]
107
+
108
+ wasEntered(entrantId, result.entrants!) // { index, entries } or null
109
+ ```
110
+
111
+ With a client, `campaign.drawings.verify(id)` does the same. The checks are the public [verify script](https://docs.prizerail.com/verification/verify-a-draw), shipped unchanged: the entrant list's Merkle root, the random value, and each winner and prize.
112
+
113
+ From the command line:
114
+
115
+ ```sh
116
+ npx prizerail verify https://www.prizerail.com/campaigns/your-campaign/draws/DRAWING_ID/proof.json
117
+ npx prizerail verify your-campaign DRAWING_ID
118
+ ```
119
+
120
+ It exits 0 when every check passes, 1 when one fails, and 2 when the proof can't be read.
121
+
122
+ ## Options
123
+
124
+ ```ts
125
+ new Prizerail({
126
+ apiKey: "pr_…",
127
+ siteUrl: "https://www.prizerail.com", // the default
128
+ timeoutMs: 30_000, // per attempt
129
+ maxRetries: 4,
130
+ fetch, // your own fetch, if you need one
131
+ })
132
+ ```
133
+
134
+ Keep the API key on your server. It can send entries for every campaign under your account.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from "node:fs";
3
+ import { Prizerail, VERSION } from "./client.js";
4
+ import { verifyDraw } from "./verify.js";
5
+ const USAGE = `prizerail ${VERSION}
6
+
7
+ Usage:
8
+ prizerail verify <proof.json link or file> [entrants link or file]
9
+ prizerail verify <campaign slug> <drawing id> [--site https://www.prizerail.com]
10
+
11
+ Checks a draw from its public proof: the locked entrant list, the random
12
+ value, and every winner and prize. Exits 0 when every check passes, 1 when
13
+ one fails, and 2 when the proof can't be read.`;
14
+ function print(result) {
15
+ const { proof, checks } = result;
16
+ // A malformed proof may lack these, and its failed checks still print.
17
+ console.log(`\n${proof?.campaign?.name ?? "Unknown campaign"}, draw of ${proof?.drawing?.drawAt ?? "unknown date"} (${proof?.drawing?.id ?? "unknown drawing"})\n`);
18
+ for (const { ok, label, detail } of checks) {
19
+ const mark = ok === true ? "✓" : ok === false ? "✗" : "i";
20
+ console.log(`${mark} ${label}${detail ? `\n ${detail}` : ""}`);
21
+ }
22
+ const failed = checks.filter(c => c.ok === false).length;
23
+ console.log(failed
24
+ ? `\n${failed} check${failed === 1 ? "" : "s"} failed.`
25
+ : "\nEvery result follows from the inputs.");
26
+ return failed ? 1 : 0;
27
+ }
28
+ async function main(argv) {
29
+ const args = [...argv];
30
+ const siteAt = args.indexOf("--site");
31
+ const site = siteAt === -1 ? undefined : args.splice(siteAt, 2)[1];
32
+ const [command, a, b] = args;
33
+ if (command === "--version" || command === "-v") {
34
+ console.log(VERSION);
35
+ return 0;
36
+ }
37
+ if (command !== "verify" || !a) {
38
+ console.log(USAGE);
39
+ return command === undefined || command === "--help" || command === "-h"
40
+ ? 0
41
+ : 2;
42
+ }
43
+ // A link or any file on disk is a proof. Anything else is a campaign slug.
44
+ const looksLikeProof = /^https?:\/\//.test(a) || existsSync(a);
45
+ if (looksLikeProof)
46
+ return print(await verifyDraw(a, { entrants: b }));
47
+ if (!b) {
48
+ console.log(USAGE);
49
+ return 2;
50
+ }
51
+ const campaign = new Prizerail({ siteUrl: site }).campaign(a);
52
+ return print(await campaign.drawings.verify(b));
53
+ }
54
+ // exitCode rather than exit(), so a long report piped to a file isn't cut off.
55
+ main(process.argv.slice(2)).then(code => {
56
+ process.exitCode = code;
57
+ }, error => {
58
+ console.error(error instanceof Error ? error.message : String(error));
59
+ process.exitCode = 2;
60
+ });
@@ -0,0 +1,135 @@
1
+ import { Http } from "./http.js";
2
+ import type { Campaign, Drawing, DrawingRef, DrawingStatus, DrawingsPage, Entrant, EntriesPage, Guarantee, SendEntriesResponse, SentEntrant } from "./types.js";
3
+ import { type DrawProof, type VerifyResult } from "./verify.js";
4
+ export declare const VERSION = "0.2.0";
5
+ /** The API takes up to this many entries per request. */
6
+ export declare const ENTRIES_PER_REQUEST = 1000;
7
+ export type PrizerailOptions = {
8
+ /** Your `pr_…` key. Only the public helpers work without one. */
9
+ apiKey?: string;
10
+ /** Defaults to https://www.prizerail.com. */
11
+ siteUrl?: string;
12
+ /** Per attempt. Defaults to 30 seconds. */
13
+ timeoutMs?: number;
14
+ /** Retries for 429s, 5xx and network errors. Defaults to 4. */
15
+ maxRetries?: number;
16
+ /** Defaults to the global fetch. */
17
+ fetch?: typeof fetch;
18
+ };
19
+ export type SendOptions = {
20
+ /**
21
+ * The drawing to send to, as `entries.list()` or a previous send returned
22
+ * it. By default, the one taking entries now.
23
+ */
24
+ drawing?: DrawingRef;
25
+ /**
26
+ * No batch is sent, and no retry started, this close to the cutoff, so
27
+ * no request arrives after it. Defaults to the request timeout.
28
+ */
29
+ cutoffMarginMs?: number;
30
+ };
31
+ /**
32
+ * `entrantCount` and `totalEntries` are the drawing's totals after the last
33
+ * batch. `added`, `updated` and `unchanged` sum what each batch reported, so
34
+ * a batch stored before its response was lost, then retried, counts as
35
+ * unchanged. Reconcile with `entrantCount`, not with `added`.
36
+ */
37
+ export type SendResult = SendEntriesResponse & {
38
+ /** Entrants in the batches the drawing confirmed. */
39
+ sent: number;
40
+ batches: number;
41
+ };
42
+ export declare class Prizerail {
43
+ readonly siteUrl: string;
44
+ /** @internal */
45
+ readonly http: Http;
46
+ constructor(options?: PrizerailOptions);
47
+ /** A campaign under your account, by slug. */
48
+ campaign(slug: string): CampaignClient;
49
+ }
50
+ export declare class CampaignClient {
51
+ readonly prizerail: Prizerail;
52
+ readonly slug: string;
53
+ readonly entries: EntriesClient;
54
+ readonly drawings: DrawingsClient;
55
+ readonly guarantees: {
56
+ list(): Promise<Guarantee[]>;
57
+ };
58
+ constructor(prizerail: Prizerail, slug: string);
59
+ /** @internal */
60
+ get http(): Http;
61
+ /** @internal */
62
+ path(rest?: string): string;
63
+ /** Schedule, prize table with odds, guarantee, next drawing, terms. */
64
+ get(): Promise<Campaign>;
65
+ }
66
+ export declare class EntriesClient {
67
+ private readonly campaign;
68
+ constructor(campaign: CampaignClient);
69
+ /**
70
+ * Sends entries to one drawing, in requests of 1,000, retrying 429s, 5xx
71
+ * and network errors. Sending an entrant again before the cutoff only sets
72
+ * their weight, so a retry is safe, but a retry after the cutoff would go
73
+ * to the next drawing. So the send is pinned to one drawing: it stops with
74
+ * a PrizerailCutoffError rather than send or retry near its cutoff, and
75
+ * with a PrizerailDrawingChangedError if a batch lands anywhere else.
76
+ */
77
+ send(entrants: Entrant[], options?: SendOptions): Promise<SendResult>;
78
+ /** The drawing taking entries now. */
79
+ openDrawing(): Promise<DrawingRef>;
80
+ /** One page of a drawing's entries, in arrival order. */
81
+ list(query?: {
82
+ drawing?: string;
83
+ limit?: number;
84
+ after?: string;
85
+ }): Promise<EntriesPage>;
86
+ /**
87
+ * Every entrant in a drawing, page by page. Without `drawing`, the one
88
+ * taking entries now, pinned by id after the first page so a cutoff
89
+ * mid-read can't mix in the next drawing.
90
+ */
91
+ all(query?: {
92
+ drawing?: string;
93
+ pageSize?: number;
94
+ }): AsyncGenerator<SentEntrant>;
95
+ }
96
+ export declare class DrawingsClient {
97
+ private readonly campaign;
98
+ constructor(campaign: CampaignClient);
99
+ /**
100
+ * One page. Open drawings come soonest first and page with `after`; the
101
+ * rest come newest first and page with `before`.
102
+ */
103
+ list(query?: {
104
+ status?: DrawingStatus;
105
+ limit?: number;
106
+ before?: string;
107
+ after?: string;
108
+ }): Promise<DrawingsPage>;
109
+ /** Every drawing, following the cursors. */
110
+ all(query?: {
111
+ status?: DrawingStatus;
112
+ pageSize?: number;
113
+ }): AsyncGenerator<Drawing>;
114
+ get(id: string): Promise<Drawing>;
115
+ /**
116
+ * Test environment only: closes the drawing's entries now and draws it,
117
+ * instead of waiting for its cutoff. Resolves with the drawing, settled or
118
+ * paid, or still `entropy_requested` if the random value is on its way, in
119
+ * which case read it again with `get(id)`. Elsewhere it throws a
120
+ * PrizerailError with code `test_only`.
121
+ */
122
+ run(id: string): Promise<Drawing>;
123
+ /**
124
+ * The newest drawing with final winners, `settled` or `paid`, or null.
125
+ * A large prize paid by hand can keep a newer draw at `settled`, so this
126
+ * reads both and takes the later.
127
+ */
128
+ latest(): Promise<Drawing | null>;
129
+ /** The public proof link for a drawing. */
130
+ proofUrl(id: string): string;
131
+ /** The drawing's public proof. Needs no API key. */
132
+ proof(id: string): Promise<DrawProof>;
133
+ /** Fetches the proof and entrant list and checks the draw. */
134
+ verify(id: string): Promise<VerifyResult>;
135
+ }
package/dist/client.js ADDED
@@ -0,0 +1,330 @@
1
+ import { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, } from "./errors.js";
2
+ import { Http } from "./http.js";
3
+ import { verifyDraw } from "./verify.js";
4
+ export const VERSION = "0.2.0";
5
+ const badPage = (detail) => new PrizerailError(0, "invalid_response", `Paging stopped: ${detail}.`);
6
+ /** The API takes up to this many entries per request. */
7
+ export const ENTRIES_PER_REQUEST = 1000;
8
+ /** An entrant as the API takes it: `entries`, never the older `weight`. */
9
+ function toWire(entrant) {
10
+ if (typeof entrant === "string")
11
+ return entrant;
12
+ const { weight, ...rest } = entrant;
13
+ if (weight === undefined)
14
+ return rest;
15
+ if (rest.entries !== undefined) {
16
+ throw new TypeError(`Entrant ${rest.entrantId} has both entries and weight. Send entries.`);
17
+ }
18
+ return { ...rest, entries: weight };
19
+ }
20
+ const badResponse = (detail) => new PrizerailError(0, "invalid_response", detail);
21
+ const isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
22
+ /** One of a pair of names for the same total, which must agree if both came. */
23
+ function pick(r, current, old) {
24
+ const a = r[current];
25
+ const b = r[old];
26
+ if (a !== undefined && b !== undefined && a !== b) {
27
+ throw badResponse(`${String(current)} ${a} and ${String(old)} ${b} disagree.`);
28
+ }
29
+ const value = a ?? b;
30
+ if (!isCount(value)) {
31
+ throw badResponse(`The response has no valid ${String(current)}.`);
32
+ }
33
+ return value;
34
+ }
35
+ /** Both names for the totals, from whichever the server sent. */
36
+ function totals(r) {
37
+ const entrantCount = pick(r, "entrantCount", "count");
38
+ const totalEntries = pick(r, "totalEntries", "totalWeight");
39
+ return {
40
+ entrantCount,
41
+ totalEntries,
42
+ count: entrantCount,
43
+ totalWeight: totalEntries,
44
+ };
45
+ }
46
+ /** A page with the current names filled in, from either server shape. */
47
+ function normalizePage(page) {
48
+ const rows = page.entrants ?? page.entries;
49
+ if (!Array.isArray(rows)) {
50
+ throw badResponse("The response has no entrants list.");
51
+ }
52
+ const entrants = rows.map(e => {
53
+ const n = e.entries ?? e.weight;
54
+ if (!isCount(n) || n < 1 || typeof e.entrantId !== "string") {
55
+ throw badResponse("An entrant in the response has no valid id or entries.");
56
+ }
57
+ return { ...e, entries: n, weight: n };
58
+ });
59
+ return {
60
+ drawing: page.drawing,
61
+ ...totals(page),
62
+ entrants,
63
+ entries: entrants,
64
+ next: page.next,
65
+ };
66
+ }
67
+ export class Prizerail {
68
+ siteUrl;
69
+ /** @internal */
70
+ http;
71
+ constructor(options = {}) {
72
+ this.siteUrl = (options.siteUrl ?? "https://www.prizerail.com").replace(/\/+$/, "");
73
+ const fetchImpl = options.fetch ?? globalThis.fetch;
74
+ if (!fetchImpl)
75
+ throw new Error("No fetch here. Pass options.fetch.");
76
+ const timeoutMs = options.timeoutMs ?? 30_000;
77
+ const maxRetries = options.maxRetries ?? 4;
78
+ // AbortSignal.timeout takes whole ms up to the platform's timer limit.
79
+ if (!Number.isInteger(timeoutMs) ||
80
+ timeoutMs < 1 ||
81
+ timeoutMs > 2 ** 31 - 1) {
82
+ throw new TypeError("timeoutMs must be a whole number of ms, from 1 to 2147483647.");
83
+ }
84
+ if (!Number.isInteger(maxRetries) || maxRetries < 0) {
85
+ throw new TypeError("maxRetries must be a whole number from 0.");
86
+ }
87
+ this.http = new Http({
88
+ apiKey: options.apiKey,
89
+ baseUrl: `${this.siteUrl}/api/v1`,
90
+ fetch: fetchImpl.bind(globalThis),
91
+ timeoutMs,
92
+ maxRetries,
93
+ userAgent: `prizerail-js/${VERSION}`,
94
+ });
95
+ }
96
+ /** A campaign under your account, by slug. */
97
+ campaign(slug) {
98
+ if (!slug)
99
+ throw new Error("campaign() needs a slug.");
100
+ return new CampaignClient(this, slug);
101
+ }
102
+ }
103
+ export class CampaignClient {
104
+ prizerail;
105
+ slug;
106
+ entries;
107
+ drawings;
108
+ guarantees;
109
+ constructor(prizerail, slug) {
110
+ this.prizerail = prizerail;
111
+ this.slug = slug;
112
+ this.entries = new EntriesClient(this);
113
+ this.drawings = new DrawingsClient(this);
114
+ this.guarantees = {
115
+ list: async () => (await this.http.request("GET", this.path("/guarantees"))).guarantees,
116
+ };
117
+ }
118
+ /** @internal */
119
+ get http() {
120
+ return this.prizerail.http;
121
+ }
122
+ /** @internal */
123
+ path(rest = "") {
124
+ return `campaigns/${encodeURIComponent(this.slug)}${rest}`;
125
+ }
126
+ /** Schedule, prize table with odds, guarantee, next drawing, terms. */
127
+ async get() {
128
+ return (await this.http.request("GET", this.path()))
129
+ .campaign;
130
+ }
131
+ }
132
+ export class EntriesClient {
133
+ campaign;
134
+ constructor(campaign) {
135
+ this.campaign = campaign;
136
+ }
137
+ /**
138
+ * Sends entries to one drawing, in requests of 1,000, retrying 429s, 5xx
139
+ * and network errors. Sending an entrant again before the cutoff only sets
140
+ * their weight, so a retry is safe, but a retry after the cutoff would go
141
+ * to the next drawing. So the send is pinned to one drawing: it stops with
142
+ * a PrizerailCutoffError rather than send or retry near its cutoff, and
143
+ * with a PrizerailDrawingChangedError if a batch lands anywhere else.
144
+ */
145
+ async send(entrants, options = {}) {
146
+ const entries = entrants.map(toWire);
147
+ if (entries.length === 0)
148
+ throw new Error("send() needs entries.");
149
+ const margin = options.cutoffMarginMs ?? this.campaign.http.options.timeoutMs;
150
+ // A bad margin or cutoff would turn the cutoff guard off, so refuse them.
151
+ if (!Number.isFinite(margin) || margin < 0) {
152
+ throw new TypeError("cutoffMarginMs must be a number of ms from 0.");
153
+ }
154
+ const target = options.drawing ?? (await this.openDrawing());
155
+ const cutoff = Date.parse(target.cutoffAt);
156
+ if (!target.id || !Number.isFinite(cutoff)) {
157
+ throw new TypeError("drawing must have the id and cutoffAt that entries.list() or a send returned.");
158
+ }
159
+ const progress = {
160
+ drawing: target,
161
+ sent: 0,
162
+ added: 0,
163
+ updated: 0,
164
+ unchanged: 0,
165
+ };
166
+ const stop = (detail, cause) => new PrizerailCutoffError(detail, { ...progress }, cause);
167
+ let last;
168
+ let batches = 0;
169
+ for (let i = 0; i < entries.length; i += ENTRIES_PER_REQUEST) {
170
+ if (Date.now() + margin >= cutoff) {
171
+ throw stop(`Drawing ${target.id}'s cutoff is at ${target.cutoffAt}, so the rest wasn't sent.`);
172
+ }
173
+ const batch = entries.slice(i, i + ENTRIES_PER_REQUEST);
174
+ const res = await this.campaign.http.request("POST", this.campaign.path("/entries"), {
175
+ body: { entrants: batch },
176
+ deadline: cutoff - margin,
177
+ onDeadline: cause => stop(`A batch failed and a retry would reach drawing ${target.id}'s cutoff. Check what it has before sending again.`, cause),
178
+ });
179
+ if (res.drawing.id !== target.id) {
180
+ throw new PrizerailDrawingChangedError({ ...progress }, res.drawing);
181
+ }
182
+ progress.sent += batch.length;
183
+ progress.added += res.added;
184
+ progress.updated += res.updated;
185
+ progress.unchanged += res.unchanged;
186
+ last = res;
187
+ batches++;
188
+ }
189
+ const final = last;
190
+ return {
191
+ drawing: final.drawing,
192
+ added: progress.added,
193
+ updated: progress.updated,
194
+ unchanged: progress.unchanged,
195
+ ...totals(final),
196
+ sent: progress.sent,
197
+ batches,
198
+ };
199
+ }
200
+ /** The drawing taking entries now. */
201
+ async openDrawing() {
202
+ const { drawing } = await this.list({ limit: 1 });
203
+ return {
204
+ id: drawing.id,
205
+ drawAt: drawing.drawAt,
206
+ cutoffAt: drawing.cutoffAt,
207
+ };
208
+ }
209
+ /** One page of a drawing's entries, in arrival order. */
210
+ async list(query = {}) {
211
+ return normalizePage(await this.campaign.http.request("GET", this.campaign.path("/entries"), { query }));
212
+ }
213
+ /**
214
+ * Every entrant in a drawing, page by page. Without `drawing`, the one
215
+ * taking entries now, pinned by id after the first page so a cutoff
216
+ * mid-read can't mix in the next drawing.
217
+ */
218
+ async *all(query = {}) {
219
+ let drawing = query.drawing;
220
+ let after;
221
+ for (;;) {
222
+ const page = await this.list({
223
+ drawing,
224
+ limit: query.pageSize ?? ENTRIES_PER_REQUEST,
225
+ after,
226
+ });
227
+ drawing ??= page.drawing.id;
228
+ if (page.drawing.id !== drawing) {
229
+ throw badPage(`a page came from drawing ${page.drawing.id}, not ${drawing}`);
230
+ }
231
+ yield* page.entrants;
232
+ if (page.next === null)
233
+ return;
234
+ // Each cursor must move forward, or a bad page would loop forever.
235
+ // Cursors are whole numbers sent as strings, so compare them as numbers.
236
+ if (!/^\d+$/.test(page.next) ||
237
+ BigInt(page.next) <= BigInt(after ?? -1)) {
238
+ throw badPage(`next ${page.next} doesn't move past ${after}`);
239
+ }
240
+ after = page.next;
241
+ }
242
+ }
243
+ }
244
+ export class DrawingsClient {
245
+ campaign;
246
+ constructor(campaign) {
247
+ this.campaign = campaign;
248
+ }
249
+ /**
250
+ * One page. Open drawings come soonest first and page with `after`; the
251
+ * rest come newest first and page with `before`.
252
+ */
253
+ list(query = {}) {
254
+ return this.campaign.http.request("GET", this.campaign.path("/drawings"), { query });
255
+ }
256
+ /** Every drawing, following the cursors. */
257
+ async *all(query = {}) {
258
+ let cursor = {};
259
+ for (;;) {
260
+ const page = await this.list({
261
+ status: query.status,
262
+ limit: query.pageSize ?? 100,
263
+ ...cursor,
264
+ });
265
+ yield* page.drawings;
266
+ // Each cursor must move on, or a bad page would loop forever.
267
+ if (page.nextAfter) {
268
+ if (cursor.after && !(page.nextAfter > cursor.after)) {
269
+ throw badPage(`nextAfter ${page.nextAfter} doesn't move past ${cursor.after}`);
270
+ }
271
+ cursor = { after: page.nextAfter };
272
+ }
273
+ else if (page.nextBefore) {
274
+ if (cursor.before && !(page.nextBefore < cursor.before)) {
275
+ throw badPage(`nextBefore ${page.nextBefore} doesn't move past ${cursor.before}`);
276
+ }
277
+ cursor = { before: page.nextBefore };
278
+ }
279
+ else
280
+ return;
281
+ }
282
+ }
283
+ async get(id) {
284
+ return (await this.campaign.http.request("GET", this.campaign.path(`/drawings/${encodeURIComponent(id)}`))).drawing;
285
+ }
286
+ /**
287
+ * Test environment only: closes the drawing's entries now and draws it,
288
+ * instead of waiting for its cutoff. Resolves with the drawing, settled or
289
+ * paid, or still `entropy_requested` if the random value is on its way, in
290
+ * which case read it again with `get(id)`. Elsewhere it throws a
291
+ * PrizerailError with code `test_only`.
292
+ */
293
+ async run(id) {
294
+ return (await this.campaign.http.request("POST", this.campaign.path(`/drawings/${encodeURIComponent(id)}/run`),
295
+ // A repeat after a lost answer would only be refused, so never retry,
296
+ // and wait out the route's own 90 seconds rather than the default 30.
297
+ { maxRetries: 0, timeoutMs: 90_000 })).drawing;
298
+ }
299
+ /**
300
+ * The newest drawing with final winners, `settled` or `paid`, or null.
301
+ * A large prize paid by hand can keep a newer draw at `settled`, so this
302
+ * reads both and takes the later.
303
+ */
304
+ async latest() {
305
+ // In this order, so a draw that turns paid between the two reads still
306
+ // shows in one of them.
307
+ const settled = await this.list({ status: "settled", limit: 1 });
308
+ const paid = await this.list({ status: "paid", limit: 1 });
309
+ // Paid first, so a drawing that moved from settled to paid between the
310
+ // two reads ties to its paid copy (the sort is stable).
311
+ const found = [...paid.drawings, ...settled.drawings];
312
+ found.sort((a, b) => Date.parse(b.drawAt) - Date.parse(a.drawAt));
313
+ return found[0] ?? null;
314
+ }
315
+ /** The public proof link for a drawing. */
316
+ proofUrl(id) {
317
+ const site = this.campaign.prizerail.siteUrl;
318
+ return `${site}/campaigns/${encodeURIComponent(this.campaign.slug)}/draws/${encodeURIComponent(id)}/proof.json`;
319
+ }
320
+ /** The drawing's public proof. Needs no API key. */
321
+ proof(id) {
322
+ return this.campaign.http.getPublic(this.proofUrl(id));
323
+ }
324
+ /** Fetches the proof and entrant list and checks the draw. */
325
+ async verify(id) {
326
+ const proof = await this.proof(id);
327
+ const { fetch, timeoutMs } = this.campaign.http.options;
328
+ return verifyDraw(proof, { proofUrl: this.proofUrl(id), fetch, timeoutMs });
329
+ }
330
+ }