@staraio/sdk 0.0.0-stage → 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.
Files changed (4) hide show
  1. package/README.md +75 -2
  2. package/client.js +89 -0
  3. package/index.js +89 -0
  4. package/package.json +8 -4
package/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # @staraio/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ JavaScript client for the [Star API](https://docs.staraio.co). Star waits in a sale's virtual
4
+ line for you and hands over each place as it reaches the front; you buy in your own browser. This
5
+ SDK turns that into a few lines: start a run, then follow it and take each hand-over as it lands.
6
+
7
+ ```bash
8
+ npm install @staraio/sdk
9
+ ```
10
+
11
+ ## Start a run and follow it
12
+
13
+ ```js
14
+ import { StarClient } from "@staraio/sdk";
15
+
16
+ const star = new StarClient({ key: process.env.STAR_API_KEY });
17
+
18
+ const run = await star.startRun({
19
+ event_url: "https://www.puntoticket.com/...",
20
+ passes: 2, // places to hand over, one per buyer
21
+ tasks: 20, // places Star holds in line to get them
22
+ proxies: ["host:port:user:pass"],
23
+ });
24
+
25
+ for await (const slot of star.handoffs(run.id)) {
26
+ if (slot.handoff?.method === "link") {
27
+ open(slot.handoff.url); // a place at the front: open and buy
28
+ } else if (slot.handoff?.method === "session") {
29
+ loadSession(slot.handoff); // url, user_agent, cookies to load into a browser you control
30
+ } else if (slot.next_action) {
31
+ // the site is asking for something (needs_login, needs_nomination, needs_seat_selection)
32
+ } else if (slot.state === "failed") {
33
+ console.error(slot.slot, slot.error);
34
+ }
35
+ }
36
+ ```
37
+
38
+ `handoffs()` yields each slot once, the moment it needs you. Queue movement never wakes the loop,
39
+ and the loop ends when the run ends. Needs Node 20+ (global `fetch`).
40
+
41
+ ## Keys and test mode
42
+
43
+ Use a test key (`sk_test_...`) to build against the simulation, a live key (`sk_live_...`) to run
44
+ for real. Create keys in the dashboard (dashboard.staraio.co, API Platform). Keep the key on the
45
+ machine that runs this, never in a browser.
46
+
47
+ ## Sites, categories and credits
48
+
49
+ ```js
50
+ const { sites } = await star.sites(); // each site's `link` and `link_example` say what to send
51
+ const { categories } = await star.categories(eventUrl); // when the site has categories: true
52
+ const category = categories.find((c) => c.open)?.code; // undefined queues for the default
53
+ await star.startRun({ event_url: eventUrl, category, passes: 1, tasks: 10, proxies });
54
+
55
+ const { url } = await star.creditsCheckout({ amount_cents: 5000 }); // a person opens url and pays
56
+ ```
57
+
58
+ ## Account sites (Ticketmaster)
59
+
60
+ Pass `accounts` to `startRun` for a site whose line only lets signed-in accounts through. Each
61
+ slot's hand-over is then that account's session. See the [sites
62
+ reference](https://docs.staraio.co/sites).
63
+
64
+ ## The raw client
65
+
66
+ `StarClient` wraps a thin HTTP client you can also use directly, plus `waitForChange` (one wait)
67
+ and `signature` (what a wait reacts to):
68
+
69
+ ```js
70
+ import { client, waitForChange, StarError } from "@staraio/sdk";
71
+ ```
72
+
73
+ Every error is a `StarError` carrying the API's `{ code, message, suggested_action }`, so you act
74
+ on `code` instead of parsing prose.
75
+
76
+ Full docs: https://docs.staraio.co
package/client.js ADDED
@@ -0,0 +1,89 @@
1
+ // Thin client for the Star API (/v1). Errors carry the API's {code, message, suggested_action}
2
+ // so the agent can act on `code` instead of parsing prose.
3
+
4
+ export class StarError extends Error {
5
+ constructor(status, detail) {
6
+ super(detail?.message ?? `HTTP ${status}`);
7
+ this.status = status;
8
+ this.detail = detail;
9
+ }
10
+ }
11
+
12
+ export function client({ baseUrl, key, fetchImpl = fetch }) {
13
+ async function call(method, path, body, headers = {}) {
14
+ const res = await fetchImpl(`${baseUrl.replace(/\/$/, "")}/v1${path}`, {
15
+ method,
16
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json", ...headers },
17
+ body: body === undefined ? undefined : JSON.stringify(body),
18
+ });
19
+ if (res.status === 204) return null;
20
+ const data = await res.json().catch(() => ({}));
21
+ if (!res.ok) throw new StarError(res.status, data.detail);
22
+ return data;
23
+ }
24
+
25
+ return {
26
+ sites: () => call("GET", "/sites"),
27
+ categories: (eventUrl) => call("GET", `/categories?${new URLSearchParams({ event_url: eventUrl })}`),
28
+ credits: () => call("GET", "/credits"),
29
+ creditsCheckout: (body) => call("POST", "/credits/checkout", body),
30
+ startRun: (body, idempotencyKey) =>
31
+ call("POST", "/runs", body, idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
32
+ getRun: (id) => call("GET", `/runs/${encodeURIComponent(id)}`),
33
+ listRuns: (params = {}) => {
34
+ const query = new URLSearchParams(Object.entries(params).filter(([, v]) => v !== undefined && v !== ""));
35
+ return call("GET", `/runs${query.size ? `?${query}` : ""}`);
36
+ },
37
+ stopRun: (id) => call("DELETE", `/runs/${encodeURIComponent(id)}`),
38
+ reportIssue: (body) => call("POST", "/support", body),
39
+ };
40
+ }
41
+
42
+ // The part of a run an agent reacts to. Queue positions move every poll, so waiting on the
43
+ // whole object would wake the agent for nothing.
44
+ export function signature(run) {
45
+ return JSON.stringify([run.state, run.ended, run.next_action, run.slots?.map((s) => [s.state, s.next_action, !!s.handoff])]);
46
+ }
47
+
48
+ // Poll until the run changes in a way that needs the agent (state, next_action, a new
49
+ // handoff) or the timeout passes. Returns the latest run either way. Pass `from` (a run already
50
+ // seen) to wait for a change relative to it, so a caller that chains waits never misses the
51
+ // read in between; without it the baseline is the first fresh read, as before.
52
+ export async function waitForChange(api, id, { timeoutMs, intervalMs = 2000, from, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
53
+ const deadline = Date.now() + timeoutMs;
54
+ // A passing engine or network hiccup must not cut the wait short: retry until the deadline.
55
+ async function read(last) {
56
+ for (;;) {
57
+ try {
58
+ return await api.getRun(id);
59
+ } catch (err) {
60
+ if (!isTransient(err)) throw err;
61
+ if (Date.now() >= deadline) {
62
+ if (last) return last;
63
+ throw err;
64
+ }
65
+ await sleep(intervalMs);
66
+ }
67
+ }
68
+ }
69
+ const baseline = from ? signature(from) : null;
70
+ let run = await read(null);
71
+ const start = baseline ?? signature(run);
72
+ while (!run.ended && signature(run) === start && Date.now() < deadline) {
73
+ await sleep(intervalMs);
74
+ run = await read(run);
75
+ }
76
+ return run;
77
+ }
78
+
79
+ function isTransient(err) {
80
+ if (err instanceof StarError) {
81
+ const action = err.detail?.suggested_action;
82
+ // 429 is the per-run read limit: waiting longer is exactly the right answer to it.
83
+ if (err.status === 429 || action === "retry") return true;
84
+ // A 5xx is the server or the load balancer in front of it, which can answer with no detail
85
+ // or a bare string. Only an explicit non-retry action from Star (e.g. "stop") ends the wait.
86
+ return err.status >= 500 && action === undefined;
87
+ }
88
+ return err instanceof TypeError; // fetch's network failure
89
+ }
package/index.js ADDED
@@ -0,0 +1,89 @@
1
+ // @staraio/sdk: the Star API in a few lines. `StarClient` wraps the HTTP calls, and
2
+ // `handoffs()` yields each slot the moment its place reaches the front, so the caller follows
3
+ // a run without polling or tracking queue movement itself. The low-level client, StarError and
4
+ // waitForChange are re-exported for callers that want the raw calls.
5
+ import { StarError, client, signature, waitForChange } from "./client.js";
6
+
7
+ export { StarError, client, signature, waitForChange };
8
+
9
+ export class StarClient {
10
+ constructor({ key, baseUrl = "https://api.staraio.co", fetchImpl } = {}) {
11
+ if (!key) throw new Error("StarClient needs an API key");
12
+ this.api = client({ baseUrl, key, fetchImpl });
13
+ }
14
+
15
+ sites() {
16
+ return this.api.sites();
17
+ }
18
+ categories(eventUrl) {
19
+ return this.api.categories(eventUrl);
20
+ }
21
+ credits() {
22
+ return this.api.credits();
23
+ }
24
+ creditsCheckout(body) {
25
+ return this.api.creditsCheckout(body);
26
+ }
27
+ startRun(body, idempotencyKey) {
28
+ return this.api.startRun(body, idempotencyKey);
29
+ }
30
+ getRun(id) {
31
+ return this.api.getRun(id);
32
+ }
33
+ listRuns(params) {
34
+ return this.api.listRuns(params);
35
+ }
36
+ stopRun(id) {
37
+ return this.api.stopRun(id);
38
+ }
39
+ reportIssue(body) {
40
+ return this.api.reportIssue(body);
41
+ }
42
+
43
+ // Follow a run and yield each slot once, the moment it needs the caller: a place reached the
44
+ // front (`slot.handoff`, a link or a session to open), the site asks for something
45
+ // (`slot.next_action`) or the slot failed. Queue movement never yields. The generator ends
46
+ // when the run ends or `timeoutMs` passes, so a plain `for await` loop drives a whole run.
47
+ async *handoffs(runId, { timeoutMs = 6 * 60 * 60 * 1000, intervalMs = 2000 } = {}) {
48
+ const seen = new Map();
49
+ const deadline = Date.now() + timeoutMs;
50
+ // Drive every read through waitForChange, including the first: `FIRST_READ` is a baseline no
51
+ // real run matches, so the first wait returns the current run at once, and `from` the run
52
+ // just scanned on every wait after, so a change between scans is never swallowed as a
53
+ // baseline. One read path means the first read retries a transient error like the rest.
54
+ let from = FIRST_READ;
55
+ for (;;) {
56
+ const run = await waitForChange(this.api, runId, { timeoutMs: deadline - Date.now(), intervalMs, from });
57
+ let index = -1;
58
+ for (const slot of run.slots ?? []) {
59
+ index += 1;
60
+ if (!needsCaller(slot)) continue;
61
+ // Slots carry a 0-based `slot` index; fall back to position so id-less slots never
62
+ // collide on one key and re-yield each other every poll.
63
+ const key = slot.slot ?? index;
64
+ const sig = slotSignature(slot);
65
+ if (seen.get(key) === sig) continue;
66
+ seen.set(key, sig);
67
+ yield slot;
68
+ }
69
+ if (run.ended || Date.now() >= deadline) return;
70
+ from = run;
71
+ }
72
+ }
73
+ }
74
+
75
+ // A baseline whose signature no real run shares (every run has a non-null state), so a wait
76
+ // seeded with it returns the current run on the first read instead of waiting for a change.
77
+ const FIRST_READ = { state: null };
78
+
79
+ // A slot the caller has to act on: one carrying a hand-over, one the site is asking something
80
+ // of, or one that failed. A slot still in line carries none of these.
81
+ function needsCaller(slot) {
82
+ return Boolean(slot.handoff || slot.next_action || slot.state === "failed");
83
+ }
84
+
85
+ // Two yields for the same slot are the same event only when state, next_action and handoff all
86
+ // match, so a slot that fails after a hand-over, or gets a fresh action, yields again.
87
+ function slotSignature(slot) {
88
+ return JSON.stringify([slot.state, slot.next_action, slot.handoff]);
89
+ }
package/package.json CHANGED
@@ -1,6 +1,10 @@
1
1
  {
2
2
  "name": "@staraio/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "JavaScript client for the Star API: start a run, follow it and take each place at the front.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "files": ["index.js", "client.js"],
8
+ "engines": { "node": ">=20" },
9
+ "scripts": { "test": "node --test" }
10
+ }