prizerail 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,7 @@ The Prizerail SDK for JavaScript and TypeScript. Send entries, read results and
11
11
  npm install prizerail
12
12
  ```
13
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).
14
+ The API is early (v0.x), so names can change between minor versions. 0.3.0 adds `entries.increment()`, and 0.3.1 checks every event before sending any and lists only the drawings that took entries. 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
15
 
16
16
  ## Send entries
17
17
 
@@ -55,6 +55,21 @@ try {
55
55
  }
56
56
  ```
57
57
 
58
+ ### Add entries as they happen
59
+
60
+ If you'd rather add entries when a user does something than send their running total, use `increment`. Each event carries an `eventId`, the id of the thing that happened, such as an order id or a referral id:
61
+
62
+ ```ts
63
+ await campaign.entries.increment([
64
+ { entrantId, entries: 10, eventId: referral.id },
65
+ ])
66
+ // { added, updated, duplicates, sent, batches, drawings }
67
+ ```
68
+
69
+ Prizerail records each `eventId` for the campaign and ignores it if it comes again, so retries and a queue that delivers an event twice never add twice, even across a cutoff. Set the id once, when the event happens, and send the same one every time. An id made fresh on each attempt would add the entries again. If you have no id for the event, make a UUID when it happens and store it with the event.
70
+
71
+ An increment goes to the drawing taking entries when it arrives, so an event after a cutoff counts in the next draw. `drawings` lists each drawing the events added entries to. Events Prizerail had already seen stay in the drawing they first went to.
72
+
58
73
  ### Entrant ids
59
74
 
60
75
  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).
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Http } from "./http.js";
2
- import type { Campaign, Drawing, DrawingRef, DrawingStatus, DrawingsPage, Entrant, EntriesPage, Guarantee, SendEntriesResponse, SentEntrant } from "./types.js";
2
+ import type { Campaign, Drawing, DrawingRef, DrawingStatus, DrawingsPage, Entrant, EntrantEvent, EntriesPage, Guarantee, SendEntriesResponse, SentEntrant } from "./types.js";
3
3
  import { type DrawProof, type VerifyResult } from "./verify.js";
4
- export declare const VERSION = "0.2.0";
4
+ export declare const VERSION = "0.3.1";
5
5
  /** The API takes up to this many entries per request. */
6
6
  export declare const ENTRIES_PER_REQUEST = 1000;
7
7
  export type PrizerailOptions = {
@@ -34,6 +34,27 @@ export type SendOptions = {
34
34
  * a batch stored before its response was lost, then retried, counts as
35
35
  * unchanged. Reconcile with `entrantCount`, not with `added`.
36
36
  */
37
+ /**
38
+ * What `entries.increment()` did. Its batches go to the drawing taking
39
+ * entries when each arrives, so a cutoff mid-way splits them between
40
+ * drawings, which is correct for events that happened either side of it.
41
+ */
42
+ export type IncrementResult = {
43
+ /** Entrants new to their drawing, and entrants given more entries. */
44
+ added: number;
45
+ updated: number;
46
+ /** Events Prizerail had already seen in this campaign, so ignored. */
47
+ duplicates: number;
48
+ /** Events in the batches Prizerail confirmed. */
49
+ sent: number;
50
+ batches: number;
51
+ /**
52
+ * Each drawing these events added entries to, in order. A batch that was
53
+ * all duplicates adds none, since those events are in the drawing they
54
+ * first went to, which can be an earlier one.
55
+ */
56
+ drawings: DrawingRef[];
57
+ };
37
58
  export type SendResult = SendEntriesResponse & {
38
59
  /** Entrants in the batches the drawing confirmed. */
39
60
  sent: number;
@@ -75,6 +96,15 @@ export declare class EntriesClient {
75
96
  * with a PrizerailDrawingChangedError if a batch lands anywhere else.
76
97
  */
77
98
  send(entrants: Entrant[], options?: SendOptions): Promise<SendResult>;
99
+ /**
100
+ * Adds entries to entrants, one event at a time: `{ entrantId, entries,
101
+ * eventId }`. Prizerail records each `eventId` for the campaign and
102
+ * ignores it if it comes again, so this is safe to retry and safe for a
103
+ * queue that delivers an event twice, even after a cutoff. Sent in
104
+ * requests of 1,000, retried like `send`. An `eventId` reused for a
105
+ * different entrant or count throws a PrizerailError, `event_conflict`.
106
+ */
107
+ increment(events: EntrantEvent[]): Promise<IncrementResult>;
78
108
  /** The drawing taking entries now. */
79
109
  openDrawing(): Promise<DrawingRef>;
80
110
  /** One page of a drawing's entries, in arrival order. */
package/dist/client.js CHANGED
@@ -1,10 +1,52 @@
1
1
  import { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, } from "./errors.js";
2
2
  import { Http } from "./http.js";
3
3
  import { verifyDraw } from "./verify.js";
4
- export const VERSION = "0.2.0";
4
+ export const VERSION = "0.3.1";
5
5
  const badPage = (detail) => new PrizerailError(0, "invalid_response", `Paging stopped: ${detail}.`);
6
6
  /** The API takes up to this many entries per request. */
7
7
  export const ENTRIES_PER_REQUEST = 1000;
8
+ /** The API's limits on an event, as it checks them. */
9
+ const ID_MAX = 200;
10
+ const ENTRIES_MAX = 2 ** 32 - 1;
11
+ /**
12
+ * Every event checked against the API's rules before the first request. The
13
+ * same eventId twice is fine if it's the same event, which the API ignores,
14
+ * but not for another entrant or count.
15
+ */
16
+ function checkEvents(events) {
17
+ const seen = new Map();
18
+ for (const [i, e] of events.entries()) {
19
+ const id = typeof e.entrantId === "string" ? e.entrantId.trim() : "";
20
+ if (id === "" || e.entrantId.length > ID_MAX) {
21
+ throw new TypeError(`Event ${i}: entrantId must be a non-empty string of ${ID_MAX} characters or fewer.`);
22
+ }
23
+ const eventId = typeof e.eventId === "string" ? e.eventId.trim() : "";
24
+ if (eventId === "" || e.eventId.length > ID_MAX) {
25
+ throw new TypeError(`Event ${i} (${id}) needs an eventId of ${ID_MAX} characters or fewer: the id of the event behind these entries, the same on every retry.`);
26
+ }
27
+ const entries = e.entries ?? 1;
28
+ if (!Number.isInteger(entries) || entries < 1 || entries > ENTRIES_MAX) {
29
+ throw new TypeError(`Event ${i} (${eventId}): entries must be a whole number from 1 to ${ENTRIES_MAX}.`);
30
+ }
31
+ const was = seen.get(eventId);
32
+ if (was &&
33
+ (was.entrantId.trim() !== id || (was.entries ?? 1) !== entries)) {
34
+ throw new TypeError(`eventId "${eventId}" is used for two different events. Give each event its own id.`);
35
+ }
36
+ seen.set(eventId, e);
37
+ }
38
+ }
39
+ /** An increment response, checked before its counts are added up. */
40
+ function checkIncrementResponse(r) {
41
+ const res = r;
42
+ if (typeof res?.drawing?.id !== "string" ||
43
+ !isCount(res.added) ||
44
+ !isCount(res.updated) ||
45
+ !isCount(res.duplicates ?? 0)) {
46
+ throw badResponse("The increment response has no valid drawing or counts.");
47
+ }
48
+ return res;
49
+ }
8
50
  /** An entrant as the API takes it: `entries`, never the older `weight`. */
9
51
  function toWire(entrant) {
10
52
  if (typeof entrant === "string")
@@ -197,6 +239,47 @@ export class EntriesClient {
197
239
  batches,
198
240
  };
199
241
  }
242
+ /**
243
+ * Adds entries to entrants, one event at a time: `{ entrantId, entries,
244
+ * eventId }`. Prizerail records each `eventId` for the campaign and
245
+ * ignores it if it comes again, so this is safe to retry and safe for a
246
+ * queue that delivers an event twice, even after a cutoff. Sent in
247
+ * requests of 1,000, retried like `send`. An `eventId` reused for a
248
+ * different entrant or count throws a PrizerailError, `event_conflict`.
249
+ */
250
+ async increment(events) {
251
+ if (events.length === 0)
252
+ throw new Error("increment() needs events.");
253
+ // Checked before anything is sent, so a bad event late in the list can't
254
+ // leave the batches before it stored and the call failed.
255
+ checkEvents(events);
256
+ const result = {
257
+ added: 0,
258
+ updated: 0,
259
+ duplicates: 0,
260
+ sent: 0,
261
+ batches: 0,
262
+ drawings: [],
263
+ };
264
+ for (let i = 0; i < events.length; i += ENTRIES_PER_REQUEST) {
265
+ const batch = events.slice(i, i + ENTRIES_PER_REQUEST);
266
+ // Retries are safe here at any time: a repeated eventId is ignored.
267
+ const res = checkIncrementResponse(await this.campaign.http.request("POST", this.campaign.path("/entries"), { body: { mode: "increment", entrants: batch } }));
268
+ result.added += res.added;
269
+ result.updated += res.updated;
270
+ result.duplicates += res.duplicates ?? 0;
271
+ result.sent += batch.length;
272
+ result.batches++;
273
+ // Only a batch that added entries names where they went. One that was
274
+ // all duplicates, such as a retry after the cutoff of a batch already
275
+ // stored, names the next drawing, not the one the events are in.
276
+ if (res.added + res.updated > 0 &&
277
+ result.drawings.at(-1)?.id !== res.drawing.id) {
278
+ result.drawings.push(res.drawing);
279
+ }
280
+ }
281
+ return result;
282
+ }
200
283
  /** The drawing taking entries now. */
201
284
  async openDrawing() {
202
285
  const { drawing } = await this.list({ limit: 1 });
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { CampaignClient, DrawingsClient, ENTRIES_PER_REQUEST, EntriesClient, Prizerail, type PrizerailOptions, type SendOptions, type SendResult, VERSION, } from "./client.js";
1
+ export { CampaignClient, DrawingsClient, ENTRIES_PER_REQUEST, EntriesClient, type IncrementResult, Prizerail, type PrizerailOptions, type SendOptions, type SendResult, VERSION, } from "./client.js";
2
2
  export { hashEntrant } from "./entrant.js";
3
3
  export { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, type SendProgress, } from "./errors.js";
4
4
  export type * from "./types.js";
package/dist/types.d.ts CHANGED
@@ -127,6 +127,22 @@ export type Entrant = string | {
127
127
  };
128
128
  /** @deprecated Use `Entrant`. */
129
129
  export type Entry = Entrant;
130
+ /**
131
+ * One event that earns an entrant entries, for `entries.increment()`. The
132
+ * `eventId` names the event (an order id, a referral id, or a UUID made once
133
+ * when it happens), and must be the same on every retry or redelivery, so
134
+ * Prizerail can ignore repeats. Never make it per attempt.
135
+ */
136
+ export type EntrantEvent = {
137
+ entrantId: string;
138
+ /** Entries this event adds, a whole number from 1. Leave it out and it's 1. */
139
+ entries?: number;
140
+ eventId: string;
141
+ /** Up to 40 characters. Replaces the stored one when the event is first counted. Empty keeps it. */
142
+ displayName?: string;
143
+ /** https, up to 2,048 characters. Replaces the stored one when the event is first counted. Empty keeps it. */
144
+ avatarUrl?: string;
145
+ };
130
146
  export type SendEntriesResponse = {
131
147
  drawing: DrawingRef;
132
148
  /** Entrants in this request that were new, changed or the same. */
@@ -141,6 +157,8 @@ export type SendEntriesResponse = {
141
157
  count: number;
142
158
  /** @deprecated Use `totalEntries`. */
143
159
  totalWeight: number;
160
+ /** Increment mode: events this campaign had already seen, so ignored. */
161
+ duplicates?: number;
144
162
  };
145
163
  export type SentEntrant = {
146
164
  entrantId: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prizerail",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "The Prizerail SDK: send entries, read draws and verify them.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://docs.prizerail.com",