@pincast/api 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/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@pincast/api",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Typed client for the Pincast card registry (Placecard v1): sets, cards, collects, claims and test apps.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/pincastFM/pincast-api.git"
9
+ },
10
+ "homepage": "https://github.com/pincastFM/pincast-api#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/pincastFM/pincast-api/issues"
13
+ },
14
+ "type": "module",
15
+ "main": "./src/index.js",
16
+ "types": "./src/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./src/index.d.ts",
20
+ "default": "./src/index.js"
21
+ },
22
+ "./resend-queue": {
23
+ "types": "./src/resend-queue.d.ts",
24
+ "default": "./src/resend-queue.js"
25
+ },
26
+ "./mock": {
27
+ "types": "./src/mock.d.ts",
28
+ "default": "./src/mock.js"
29
+ },
30
+ "./openapi.json": "./openapi/placecard-v1.openapi.json",
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "src",
35
+ "openapi"
36
+ ],
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "registry": "https://registry.npmjs.org"
40
+ },
41
+ "engines": {
42
+ "node": ">=20.12"
43
+ },
44
+ "scripts": {
45
+ "generate": "node scripts/generate.mjs",
46
+ "check": "node scripts/check-operations.mjs",
47
+ "test": "node --test test/*.test.js",
48
+ "prepack": "node scripts/check-operations.mjs",
49
+ "sync": "node scripts/sync-openapi.mjs",
50
+ "changelog": "node scripts/changelog.mjs"
51
+ },
52
+ "keywords": [
53
+ "pincast",
54
+ "placecard",
55
+ "cards",
56
+ "api",
57
+ "client"
58
+ ]
59
+ }
package/src/client.js ADDED
@@ -0,0 +1,155 @@
1
+ // The client: one method per operation in the API file, named by its operationId. Each call sends
2
+ // the key in X-Pincast-Key when the operation takes one, puts an Idempotency-Key on the three writes
3
+ // (the same key on every retry of that call), waits out a 429 or 503 that says how long to wait,
4
+ // and raises a PincastError carrying code, field and fix.
5
+ import { PincastError } from './errors.js'
6
+ import { operations } from './generated/operations.js'
7
+ import { keyInfo } from './keys.js'
8
+
9
+ export const DEFAULT_BASE_URL = 'https://api.pincast.fm/v1'
10
+ export const KEY_HEADER = 'X-Pincast-Key'
11
+
12
+ const inBrowser = () => typeof globalThis.window !== 'undefined' && typeof globalThis.document !== 'undefined'
13
+
14
+ function sleep(ms, signal) {
15
+ return new Promise((resolve, reject) => {
16
+ if (signal?.aborted) return reject(signal.reason)
17
+ const onAbort = () => { clearTimeout(timer); reject(signal.reason) }
18
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve() }, ms)
19
+ signal?.addEventListener('abort', onAbort, { once: true })
20
+ })
21
+ }
22
+
23
+ // Retry-After in seconds: a number of seconds, or an HTTP date. Null when absent or unreadable.
24
+ export function retryAfterSeconds(value) {
25
+ if (value == null || value === '') return null
26
+ const n = Number(value)
27
+ if (Number.isFinite(n) && n >= 0) return n
28
+ const when = Date.parse(value)
29
+ return Number.isFinite(when) ? Math.max(0, Math.ceil((when - Date.now()) / 1000)) : null
30
+ }
31
+
32
+ function refusal(operation, where, res, data) {
33
+ const d = data && typeof data === 'object' && data.data && typeof data.data === 'object' ? data.data : {}
34
+ const code = typeof d.code === 'string' ? d.code : null
35
+ const field = typeof d.field === 'string' ? d.field : null
36
+ const fix = typeof d.fix === 'string' ? d.fix : null
37
+ const said = code
38
+ ? `${code}${field ? ` (${field})` : ''}${fix ? `: ${fix}` : ''}`
39
+ : (typeof data?.message === 'string' && data.message) || res.statusText || 'no detail'
40
+ return new PincastError({
41
+ status: res.status, code, field, fix, operation, body: data,
42
+ retryAfter: retryAfterSeconds(res.headers.get('retry-after')),
43
+ message: `${where}: ${res.status} ${said}`,
44
+ })
45
+ }
46
+
47
+ export class Pincast {
48
+ #key
49
+ #baseUrl
50
+ #fetch
51
+ #timeoutMs
52
+ #retries
53
+ #maxRetryWait
54
+ #sleep
55
+
56
+ constructor(options = {}) {
57
+ const key = options.key !== undefined ? options.key : globalThis.process?.env?.PINCAST_KEY
58
+ if (key != null && typeof key !== 'string') throw new TypeError('key must be a string')
59
+ if (key && inBrowser()) {
60
+ throw new PincastError({
61
+ code: 'browser_not_allowed',
62
+ fix: 'Call Pincast from your server and keep the key there.',
63
+ message: 'No key can be used in a web page, where anyone who opens the page can read it. Call Pincast from your server and keep the key there.',
64
+ })
65
+ }
66
+ this.#key = key || null
67
+ this.#baseUrl = String(options.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '')
68
+ this.#fetch = options.fetch || globalThis.fetch
69
+ if (typeof this.#fetch !== 'function') throw new TypeError('no fetch here: use Node 20.12 or later, or pass options.fetch')
70
+ this.#timeoutMs = options.timeoutMs ?? 10_000
71
+ this.#retries = options.retries ?? 2
72
+ this.#maxRetryWait = options.maxRetryWait ?? 60
73
+ this.#sleep = options.sleep || sleep
74
+ }
75
+
76
+ // What the key is (app, kind, test), never the key itself. Null with no key.
77
+ get keyInfo() { return this.#key ? keyInfo(this.#key) : null }
78
+ get baseUrl() { return this.#baseUrl }
79
+ toJSON() { return { baseUrl: this.#baseUrl, keyInfo: this.keyInfo } }
80
+ [Symbol.for('nodejs.util.inspect.custom')]() {
81
+ return `Pincast { baseUrl: '${this.#baseUrl}', key: ${this.#key ? '[hidden]' : 'none'} }`
82
+ }
83
+
84
+ putSet(set, body, options) { return this.#call('putSet', { set }, null, body, options) }
85
+ getSet(set, options) { return this.#call('getSet', { set }, null, undefined, options) }
86
+ postCollect(set, body, options) { return this.#call('postCollect', { set }, null, body, options) }
87
+ getCollects(set, query, options) { return this.#call('getCollects', { set }, query, undefined, options) }
88
+ postClaim(set, body, options) { return this.#call('postClaim', { set }, null, body, options) }
89
+ postPerson(body, options) { return this.#call('postPerson', {}, null, body, options) }
90
+ getApps(options) { return this.#call('getApps', {}, null, undefined, options) }
91
+ postTestApp(body, options) { return this.#call('postTestApp', {}, null, body, options) }
92
+
93
+ async #call(id, pathValues, query, body, options = {}) {
94
+ const op = operations[id]
95
+ const where = `${id} (${op.method} ${op.path})`
96
+ if (op.key && !this.#key) {
97
+ throw new PincastError({
98
+ operation: id, code: 'key_missing',
99
+ fix: 'Pass key to new Pincast({ key }) or set PINCAST_KEY. postTestApp() makes a test key.',
100
+ message: `${where}: no key. Pass key to new Pincast({ key }) or set PINCAST_KEY. postTestApp() makes a test key.`,
101
+ })
102
+ }
103
+ let path = op.path
104
+ for (const name of op.pathParams) {
105
+ const value = pathValues?.[name]
106
+ if (value == null || value === '') throw new TypeError(`${id}: ${name} is required`)
107
+ path = path.replace(`{${name}}`, encodeURIComponent(String(value)))
108
+ }
109
+ const qs = new URLSearchParams()
110
+ for (const name of op.query) {
111
+ const value = query?.[name]
112
+ if (value == null) continue
113
+ for (const one of Array.isArray(value) ? value : [value]) qs.append(name, String(one))
114
+ }
115
+ const search = qs.toString()
116
+ const url = `${this.#baseUrl}${path}${search ? `?${search}` : ''}`
117
+
118
+ const headers = { accept: 'application/json' }
119
+ if (op.key) headers[KEY_HEADER] = this.#key
120
+ if (op.idempotencyKey) headers['Idempotency-Key'] = options.idempotencyKey || globalThis.crypto.randomUUID()
121
+ let payload
122
+ if (body !== undefined && body !== null && op.body !== 'none') {
123
+ headers['content-type'] = 'application/json'
124
+ payload = JSON.stringify(body)
125
+ } else if (op.body === 'required') {
126
+ throw new TypeError(`${id}: a body is required`)
127
+ }
128
+
129
+ for (let attempt = 0; ; attempt++) {
130
+ const signals = [AbortSignal.timeout(options.timeoutMs ?? this.#timeoutMs)]
131
+ if (options.signal) signals.push(options.signal)
132
+ let res
133
+ try {
134
+ res = await this.#fetch(url, { method: op.method, headers, body: payload, signal: AbortSignal.any(signals) })
135
+ } catch (error) {
136
+ if (options.signal?.aborted) throw error
137
+ throw new PincastError({ operation: id, cause: error, message: `${where}: no answer (${error?.message || error})` })
138
+ }
139
+ const text = await res.text().catch(() => '')
140
+ let data = null
141
+ try { data = text ? JSON.parse(text) : null } catch { data = null }
142
+ if (res.ok) {
143
+ if (data === null) throw new PincastError({ status: res.status, operation: id, message: `${where}: ${res.status} with an answer that is not JSON` })
144
+ return data
145
+ }
146
+ const error = refusal(id, where, res, data)
147
+ const waits = (res.status === 429 || res.status === 503) && error.retryAfter != null
148
+ if (waits && error.retryAfter <= this.#maxRetryWait && attempt < this.#retries) {
149
+ await this.#sleep(error.retryAfter * 1000, options.signal)
150
+ continue
151
+ }
152
+ throw error
153
+ }
154
+ }
155
+ }
package/src/errors.js ADDED
@@ -0,0 +1,31 @@
1
+ // The one error the client raises. When Placecard refuses a call, the error carries the answer's
2
+ // status and its data: a code to branch on, the field at fault when there is one, and a fix in
3
+ // one sentence. When no answer came, status is null and cause holds what went wrong.
4
+ export class PincastError extends Error {
5
+ constructor({ message, status = null, code = null, field = null, fix = null, retryAfter = null, operation = null, body = null, cause } = {}) {
6
+ super(message || fix || code || 'Pincast call failed', cause === undefined ? undefined : { cause })
7
+ this.name = 'PincastError'
8
+ this.status = status
9
+ this.code = code
10
+ this.field = field
11
+ this.fix = fix
12
+ this.retryAfter = retryAfter
13
+ this.operation = operation
14
+ this.body = body
15
+ }
16
+
17
+ // What the refusal means for a call you keep and send again (the resend queue reads this):
18
+ // key a 401, a 403 other than person_not_signed_in, or no key here: fix the key, then send it again
19
+ // waiting 403 person_not_signed_in: link the person with postPerson, then send it again
20
+ // later no answer, 408, 429, a 5xx, or 404 set_not_registered (put the set again): send it again later
21
+ // refused any other 4xx: this call will not go through as it is
22
+ get kind() {
23
+ const s = this.status
24
+ if (s == null) return this.code === 'browser_not_allowed' || this.code?.startsWith('key_') ? 'key' : 'later'
25
+ if (s === 408 || s === 429 || s >= 500 || s < 400) return 'later'
26
+ if (s === 404 && this.code === 'set_not_registered') return 'later'
27
+ if (s === 401) return 'key'
28
+ if (s === 403) return this.code === 'person_not_signed_in' ? 'waiting' : 'key'
29
+ return 'refused'
30
+ }
31
+ }
@@ -0,0 +1,19 @@
1
+ // Generated by scripts/generate.mjs from openapi/placecard-v1.openapi.json
2
+ // (Placecard registry 1.0.0, sha256 0714846067829acca4724b34730facf69f17d2d564cab9917d7ef8d27b3ba36e). Do not edit: run npm run generate.
3
+
4
+ export const apiFile = Object.freeze({"title":"Placecard registry","version":"1.0.0","sha256":"0714846067829acca4724b34730facf69f17d2d564cab9917d7ef8d27b3ba36e"})
5
+
6
+ export const servers = Object.freeze(["https://api.pincast.fm/v1","https://www.pincaster.com/api/placecard/v1"])
7
+
8
+ export const operations = Object.freeze({
9
+ getSet: Object.freeze({"method":"GET","path":"/sets/{set}","pathParams":["set"],"query":[],"body":"none","key":true,"idempotencyKey":false}),
10
+ putSet: Object.freeze({"method":"PUT","path":"/sets/{set}","pathParams":["set"],"query":[],"body":"required","key":true,"idempotencyKey":true}),
11
+ getCollects: Object.freeze({"method":"GET","path":"/sets/{set}/collects","pathParams":["set"],"query":["actor"],"body":"none","key":true,"idempotencyKey":false}),
12
+ postCollect: Object.freeze({"method":"POST","path":"/sets/{set}/collects","pathParams":["set"],"query":[],"body":"required","key":true,"idempotencyKey":true}),
13
+ postClaim: Object.freeze({"method":"POST","path":"/sets/{set}/claims","pathParams":["set"],"query":[],"body":"required","key":true,"idempotencyKey":true}),
14
+ postPerson: Object.freeze({"method":"POST","path":"/people","pathParams":[],"query":[],"body":"required","key":true,"idempotencyKey":false}),
15
+ getApps: Object.freeze({"method":"GET","path":"/apps","pathParams":[],"query":[],"body":"none","key":false,"idempotencyKey":false}),
16
+ postTestApp: Object.freeze({"method":"POST","path":"/test-apps","pathParams":[],"query":[],"body":"optional","key":false,"idempotencyKey":false}),
17
+ })
18
+
19
+ export const errorCodes = Object.freeze(["key_missing","key_invalid","key_expired","key_conflict","key_ability_missing","key_kind_refused","test_person_required","test_limit_reached","test_apps_limit","browser_not_allowed","rate_limited","quota_exceeded","set_id_invalid","idempotency_key_invalid","body_not_json","field_required","field_invalid","too_many_cards","duplicate_card_key","parent_not_registered","too_many_actors","same_player","set_not_registered","card_not_registered","card_retired","actor_signed_in","idempotency_key_reused","token_invalid","token_expired","token_other_app","person_not_signed_in","signin_check_unavailable"])