@arcosmos/sdk 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/LICENSE +202 -0
- package/README.md +157 -2
- package/dist/api.d.ts +2695 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +34 -0
- package/dist/api.js.map +1 -0
- package/dist/client.d.ts +74 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +214 -0
- package/dist/client.js.map +1 -0
- package/dist/errors.d.ts +41 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +42 -0
- package/dist/errors.js.map +1 -0
- package/dist/helpers.d.ts +42 -0
- package/dist/helpers.d.ts.map +1 -0
- package/dist/helpers.js +29 -0
- package/dist/helpers.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/paging.d.ts +32 -0
- package/dist/paging.d.ts.map +1 -0
- package/dist/paging.js +46 -0
- package/dist/paging.js.map +1 -0
- package/dist/resources.d.ts +122 -0
- package/dist/resources.d.ts.map +1 -0
- package/dist/resources.js +123 -0
- package/dist/resources.js.map +1 -0
- package/package.json +46 -3
- package/src/api.ts +2335 -0
- package/src/client.ts +261 -0
- package/src/errors.ts +58 -0
- package/src/helpers.ts +61 -0
- package/src/index.ts +12 -0
- package/src/paging.ts +60 -0
- package/src/resources.ts +175 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// The request core: one method, `request`, for every operation the API documents, by its
|
|
2
|
+
// operationId. It builds the URL from the path and query, sends the key, retries what can be
|
|
3
|
+
// retried, and turns the API's error envelope into an ArcosmosError.
|
|
4
|
+
import { Quantity } from '@arcosmos/astronomy'
|
|
5
|
+
import { OPERATIONS, type Operations } from './api.ts'
|
|
6
|
+
import { ArcosmosError, type AnyErrorCode, ConnectionError, type DetailsOf } from './errors.ts'
|
|
7
|
+
|
|
8
|
+
/** The API's production address, with its version. */
|
|
9
|
+
export const DEFAULT_BASE_URL = 'https://api.arcosmos.space/api/v1'
|
|
10
|
+
|
|
11
|
+
/** Every operation the API documents, by its operationId. */
|
|
12
|
+
export type OperationId = keyof Operations
|
|
13
|
+
|
|
14
|
+
/** What an operation takes: its path parameters, query and body, where it has them. */
|
|
15
|
+
export type Input<O extends OperationId> =
|
|
16
|
+
& ({} extends Operations[O]['path'] ? { path?: undefined } : { path: Operations[O]['path'] })
|
|
17
|
+
& ({} extends Operations[O]['query'] ? { query?: Operations[O]['query'] } : { query: Operations[O]['query'] })
|
|
18
|
+
& ([Operations[O]['body']] extends [never] ? { body?: undefined } : { body: Operations[O]['body'] })
|
|
19
|
+
|
|
20
|
+
/** What an operation answers with: its JSON body, or the Response itself for an Arrow stream. */
|
|
21
|
+
export type Output<O extends OperationId> = (typeof OPERATIONS)[O]['response'] extends 'arrow' ? Response
|
|
22
|
+
: Operations[O]['response']
|
|
23
|
+
|
|
24
|
+
export interface ClientOptions {
|
|
25
|
+
/**
|
|
26
|
+
* The API key, `arc_` and 32 characters. Default: the ARCOSMOS_API_KEY environment variable,
|
|
27
|
+
* where there is one (Node, Deno, Bun). Never put a key in code a browser downloads.
|
|
28
|
+
*/
|
|
29
|
+
apiKey?: string
|
|
30
|
+
/** The API's address with its version. Default: https://api.arcosmos.space/api/v1. */
|
|
31
|
+
baseUrl?: string
|
|
32
|
+
/** The fetch to send requests with. Default: the global fetch. */
|
|
33
|
+
fetch?: typeof fetch
|
|
34
|
+
/** How many times to retry a request the API couldn't answer for now. Default 2. */
|
|
35
|
+
maxRetries?: number
|
|
36
|
+
/** Milliseconds to wait for each attempt before giving up. Default 60,000. */
|
|
37
|
+
timeout?: number
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Options for one request, overriding the client's. */
|
|
41
|
+
export interface RequestOptions {
|
|
42
|
+
/** Abandons the request, with the signal's reason. */
|
|
43
|
+
signal?: AbortSignal
|
|
44
|
+
timeout?: number
|
|
45
|
+
maxRetries?: number
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The month's quota, as the last counted response gave it. */
|
|
49
|
+
export interface Quota {
|
|
50
|
+
/** Requests the plan allows each calendar month (UTC). */
|
|
51
|
+
limit: number
|
|
52
|
+
/** Requests left this month, after that response. Approximate while others are in flight. */
|
|
53
|
+
remaining: number
|
|
54
|
+
/** When the month ends and the count starts again. */
|
|
55
|
+
resetsAt: Date
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The longest Retry-After the client waits for itself, in seconds. Longer, the error is thrown. */
|
|
59
|
+
const MAX_RETRY_AFTER_S = 60
|
|
60
|
+
/** The first backoff after a failed attempt, in milliseconds; each retry doubles it. */
|
|
61
|
+
const BACKOFF_MS = 500
|
|
62
|
+
/** Statuses that say the API couldn't answer for now, so the same request may succeed later. */
|
|
63
|
+
const TRANSIENT = new Set([502, 503, 504])
|
|
64
|
+
|
|
65
|
+
function environmentKey(): string | undefined {
|
|
66
|
+
const process = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process
|
|
67
|
+
return process?.env?.ARCOSMOS_API_KEY
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A number as plain decimal text, never in exponent form, which the API's patterns refuse. */
|
|
71
|
+
export function decimal(value: number): string {
|
|
72
|
+
if (!Number.isFinite(value)) throw new RangeError(`A query value must be a finite number, not ${value}`)
|
|
73
|
+
const text = String(value)
|
|
74
|
+
if (!/e/i.test(text)) return text
|
|
75
|
+
return value.toLocaleString('en-US', { useGrouping: false, maximumFractionDigits: 100 })
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** One query value as text. A quantity is written in a unit the parameter takes. */
|
|
79
|
+
function queryValue(name: string, value: unknown, units: readonly string[] | undefined): string {
|
|
80
|
+
if (value === true) return 'true'
|
|
81
|
+
if (typeof value === 'number') return decimal(value)
|
|
82
|
+
if (typeof value === 'string') return value
|
|
83
|
+
if (Array.isArray(value)) return value.map((v) => queryValue(name, v, units)).join(',')
|
|
84
|
+
if (value instanceof Quantity) {
|
|
85
|
+
if (!units) throw new TypeError(`${name} takes no quantity`)
|
|
86
|
+
if (value.uncertainty || value.limit) {
|
|
87
|
+
throw new TypeError(`${name} is a bound, not a measurement: give it a quantity without an uncertainty or limit`)
|
|
88
|
+
}
|
|
89
|
+
const unit = value.unit.toString()
|
|
90
|
+
const sent = units.includes(unit) ? value : value.to(units[0]!)
|
|
91
|
+
return `${decimal(sent.value)} ${units.includes(unit) ? unit : units[0]}`
|
|
92
|
+
}
|
|
93
|
+
throw new TypeError(`${name} can't be sent as ${typeof value}`)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The URL of an operation: its path with the parameters filled in, then the query. */
|
|
97
|
+
export function urlOf<O extends OperationId>(baseUrl: string, op: O, input: Input<O>): string {
|
|
98
|
+
const spec = OPERATIONS[op]
|
|
99
|
+
const pathParams = (input.path ?? {}) as Record<string, string>
|
|
100
|
+
const path = spec.path.replace(/\{(\w+)\}/g, (_, name: string) => {
|
|
101
|
+
const value = pathParams[name]
|
|
102
|
+
if (typeof value !== 'string' || value === '') throw new TypeError(`${op} needs ${name}`)
|
|
103
|
+
return encodeURIComponent(value)
|
|
104
|
+
})
|
|
105
|
+
// Spaces as %20, not URLSearchParams' +: `radius=10%20ly`, as the API's own examples write it.
|
|
106
|
+
const params: string[] = []
|
|
107
|
+
const known = spec.query as Record<string, { units?: readonly string[] }>
|
|
108
|
+
for (const [name, value] of Object.entries((input.query ?? {}) as Record<string, unknown>)) {
|
|
109
|
+
if (value === undefined || value === null) continue
|
|
110
|
+
const param = known[name]
|
|
111
|
+
if (!param) throw new TypeError(`${op} takes no query parameter ${name}`)
|
|
112
|
+
params.push(`${name}=${encodeURIComponent(queryValue(name, value, param.units))}`)
|
|
113
|
+
}
|
|
114
|
+
return `${baseUrl.replace(/\/+$/, '')}${path}${params.length ? `?${params.join('&')}` : ''}`
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Seconds from a Retry-After header: a number of seconds or an HTTP date. */
|
|
118
|
+
function retryAfterOf(response: Response): number | null {
|
|
119
|
+
const header = response.headers.get('retry-after')
|
|
120
|
+
if (header === null) return null
|
|
121
|
+
const seconds = Number(header)
|
|
122
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds)
|
|
123
|
+
const date = Date.parse(header)
|
|
124
|
+
return Number.isNaN(date) ? null : Math.max(0, (date - Date.now()) / 1000)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function errorOf(response: Response): Promise<ArcosmosError> {
|
|
128
|
+
const retryAfter = retryAfterOf(response)
|
|
129
|
+
const text = await response.text().catch(() => '')
|
|
130
|
+
try {
|
|
131
|
+
const body = JSON.parse(text) as { error?: { code?: unknown; message?: unknown; details?: unknown } }
|
|
132
|
+
const e = body.error
|
|
133
|
+
if (e && typeof e.code === 'string' && typeof e.message === 'string') {
|
|
134
|
+
return new ArcosmosError(response.status, e.code as AnyErrorCode, e.message, e.details as DetailsOf<string>, retryAfter)
|
|
135
|
+
}
|
|
136
|
+
} catch {
|
|
137
|
+
// Not the API's envelope: a proxy's or the platform's answer.
|
|
138
|
+
}
|
|
139
|
+
const message = text.trim().slice(0, 200) || response.statusText || `HTTP ${response.status}`
|
|
140
|
+
return new ArcosmosError(response.status, `http_${response.status}`, message, undefined, retryAfter)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
|
|
144
|
+
return new Promise((resolve, reject) => {
|
|
145
|
+
if (signal?.aborted) return reject(signal.reason)
|
|
146
|
+
const timer = setTimeout(() => {
|
|
147
|
+
signal?.removeEventListener('abort', abort)
|
|
148
|
+
resolve()
|
|
149
|
+
}, ms)
|
|
150
|
+
const abort = () => {
|
|
151
|
+
clearTimeout(timer)
|
|
152
|
+
reject(signal!.reason)
|
|
153
|
+
}
|
|
154
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
155
|
+
})
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The wait before retry `attempt` (from 0): exponential, with jitter so clients spread out. */
|
|
159
|
+
function backoff(attempt: number): number {
|
|
160
|
+
return BACKOFF_MS * 2 ** attempt * (0.75 + Math.random() / 2)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The part of the client that sends requests. `Arcosmos` adds the API's resources over it.
|
|
165
|
+
* `request` reaches any operation by its operationId, typed from the API's OpenAPI document.
|
|
166
|
+
*/
|
|
167
|
+
export class Client {
|
|
168
|
+
readonly baseUrl: string
|
|
169
|
+
readonly #apiKey: string
|
|
170
|
+
readonly #fetch: typeof fetch
|
|
171
|
+
readonly #maxRetries: number
|
|
172
|
+
readonly #timeout: number
|
|
173
|
+
#quota: Quota | null = null
|
|
174
|
+
|
|
175
|
+
constructor(options: ClientOptions = {}) {
|
|
176
|
+
const apiKey = options.apiKey ?? environmentKey()
|
|
177
|
+
if (!apiKey) {
|
|
178
|
+
throw new TypeError('An API key is needed: pass apiKey, or set ARCOSMOS_API_KEY. Get one at https://arcosmos.space/api-keys')
|
|
179
|
+
}
|
|
180
|
+
this.#apiKey = apiKey
|
|
181
|
+
this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL
|
|
182
|
+
this.#fetch = options.fetch ?? ((...args) => globalThis.fetch(...args))
|
|
183
|
+
this.#maxRetries = options.maxRetries ?? 2
|
|
184
|
+
this.#timeout = options.timeout ?? 60_000
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The month's quota from the last response that carried it; null before one has. */
|
|
188
|
+
get quota(): Quota | null {
|
|
189
|
+
return this.#quota
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Sends one operation and returns its answer: `request('getObject', { path: { identifier:
|
|
194
|
+
* 'Vega' } })`. Throws an ArcosmosError when the API answers with an error, and a
|
|
195
|
+
* ConnectionError when it doesn't answer at all.
|
|
196
|
+
*/
|
|
197
|
+
async request<O extends OperationId>(op: O, input: Input<O>, options: RequestOptions = {}): Promise<Output<O>> {
|
|
198
|
+
const spec = OPERATIONS[op]
|
|
199
|
+
const url = urlOf(this.baseUrl, op, input)
|
|
200
|
+
const headers: Record<string, string> = {
|
|
201
|
+
Authorization: `Bearer ${this.#apiKey}`,
|
|
202
|
+
Accept: spec.response === 'arrow' ? 'application/vnd.apache.arrow.stream' : 'application/json',
|
|
203
|
+
}
|
|
204
|
+
let body: string | undefined
|
|
205
|
+
if (input.body !== undefined) {
|
|
206
|
+
headers['Content-Type'] = 'application/json'
|
|
207
|
+
body = JSON.stringify(input.body)
|
|
208
|
+
}
|
|
209
|
+
const maxRetries = options.maxRetries ?? this.#maxRetries
|
|
210
|
+
const timeout = options.timeout ?? this.#timeout
|
|
211
|
+
|
|
212
|
+
for (let attempt = 0; ; attempt++) {
|
|
213
|
+
let response: Response
|
|
214
|
+
const timer = AbortSignal.timeout(timeout)
|
|
215
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timer]) : timer
|
|
216
|
+
try {
|
|
217
|
+
response = await this.#fetch(url, { method: spec.method, headers, body, signal })
|
|
218
|
+
} catch (cause) {
|
|
219
|
+
if (options.signal?.aborted) throw options.signal.reason
|
|
220
|
+
const timedOut = timer.aborted
|
|
221
|
+
if (attempt < maxRetries) {
|
|
222
|
+
await sleep(backoff(attempt), options.signal)
|
|
223
|
+
continue
|
|
224
|
+
}
|
|
225
|
+
throw new ConnectionError(
|
|
226
|
+
timedOut ? `${spec.method} ${url} got no answer within ${timeout} ms` : `${spec.method} ${url} failed: ${String(cause)}`,
|
|
227
|
+
{ cause, timedOut },
|
|
228
|
+
)
|
|
229
|
+
}
|
|
230
|
+
this.#readQuota(response)
|
|
231
|
+
if (response.ok) {
|
|
232
|
+
if (spec.response === 'arrow') return response as Output<O>
|
|
233
|
+
return await response.json() as Output<O>
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const error = await errorOf(response)
|
|
237
|
+
if (attempt < maxRetries) {
|
|
238
|
+
if (error.code === 'rate_limited' && (error.retryAfter ?? 0) <= MAX_RETRY_AFTER_S) {
|
|
239
|
+
await sleep((error.retryAfter ?? backoff(attempt) / 1000) * 1000, options.signal)
|
|
240
|
+
continue
|
|
241
|
+
}
|
|
242
|
+
if (TRANSIENT.has(response.status)) {
|
|
243
|
+
const wait = error.retryAfter !== null && error.retryAfter <= MAX_RETRY_AFTER_S ? error.retryAfter * 1000 : backoff(attempt)
|
|
244
|
+
await sleep(wait, options.signal)
|
|
245
|
+
continue
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
throw error
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
#readQuota(response: Response): void {
|
|
253
|
+
const limit = response.headers.get('x-quota-limit')
|
|
254
|
+
const remaining = response.headers.get('x-quota-remaining')
|
|
255
|
+
const reset = response.headers.get('x-quota-reset')
|
|
256
|
+
if (limit === null || remaining === null || reset === null) return
|
|
257
|
+
const resetsAt = new Date(reset)
|
|
258
|
+
if (!Number.isFinite(Number(limit)) || !Number.isFinite(Number(remaining)) || Number.isNaN(resetsAt.getTime())) return
|
|
259
|
+
this.#quota = { limit: Number(limit), remaining: Number(remaining), resetsAt }
|
|
260
|
+
}
|
|
261
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// The errors the client throws: the API's own (ArcosmosError, with its code and details), and
|
|
2
|
+
// a request that got no answer (ConnectionError).
|
|
3
|
+
import type { ErrorDetails } from './api.ts'
|
|
4
|
+
|
|
5
|
+
/** Every error code the API documents. Within v1 it may add more: handle a code you don't know. */
|
|
6
|
+
export type ErrorCode = keyof ErrorDetails
|
|
7
|
+
|
|
8
|
+
/** An error code: one the API documents, or one added after this SDK was built. */
|
|
9
|
+
export type AnyErrorCode = ErrorCode | (string & {})
|
|
10
|
+
|
|
11
|
+
/** The details an error code carries. */
|
|
12
|
+
export type DetailsOf<C extends string> = C extends ErrorCode ? ErrorDetails[C] : unknown
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* An answer the API gave instead of data: `{ error: { code, message, details } }` and its HTTP
|
|
16
|
+
* status. A name several objects share is a 300 `ambiguous_identifier`, with the candidates in
|
|
17
|
+
* `details`; an unknown name is a 404 `not_found`, with suggestions. Narrow it with `is`:
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* if (e instanceof ArcosmosError && e.is('ambiguous_identifier')) e.details.candidates
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export class ArcosmosError<C extends AnyErrorCode = AnyErrorCode> extends Error {
|
|
24
|
+
override readonly name = 'ArcosmosError'
|
|
25
|
+
/** The HTTP status. */
|
|
26
|
+
readonly status: number
|
|
27
|
+
/** The API's error code, such as `not_found`; `http_<status>` when the answer wasn't the API's. */
|
|
28
|
+
readonly code: C
|
|
29
|
+
/** What the code says it carries, such as `candidates` for `ambiguous_identifier`. */
|
|
30
|
+
readonly details: DetailsOf<C>
|
|
31
|
+
/** Seconds to wait before trying again, from Retry-After; null when not given. */
|
|
32
|
+
readonly retryAfter: number | null
|
|
33
|
+
|
|
34
|
+
constructor(status: number, code: C, message: string, details: DetailsOf<C>, retryAfter: number | null = null) {
|
|
35
|
+
super(message)
|
|
36
|
+
this.status = status
|
|
37
|
+
this.code = code
|
|
38
|
+
this.details = details
|
|
39
|
+
this.retryAfter = retryAfter
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Whether this is the error with that code, narrowing its details. */
|
|
43
|
+
is<K extends ErrorCode>(code: K): this is ArcosmosError<K> {
|
|
44
|
+
return (this.code as string) === code
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A request that got no answer: the network failed, or it ran past its timeout. */
|
|
49
|
+
export class ConnectionError extends Error {
|
|
50
|
+
override readonly name = 'ConnectionError'
|
|
51
|
+
/** Whether it was abandoned at its timeout, rather than failing. */
|
|
52
|
+
readonly timedOut: boolean
|
|
53
|
+
|
|
54
|
+
constructor(message: string, options: { cause?: unknown; timedOut?: boolean } = {}) {
|
|
55
|
+
super(message, { cause: options.cause })
|
|
56
|
+
this.timedOut = options.timedOut ?? false
|
|
57
|
+
}
|
|
58
|
+
}
|
package/src/helpers.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Responses stay JSON, as the API sends them. These turn the parts that are values into
|
|
2
|
+
// @arcosmos/astronomy's types, to convert units, propagate errors or change frames.
|
|
3
|
+
import {
|
|
4
|
+
type Kind, type MeasurementLike, type MotionInput, type Quantity, type SkyCoord, fromMeasurement, q, skyCoord as coordinate,
|
|
5
|
+
time,
|
|
6
|
+
} from '@arcosmos/astronomy'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A measurement as a Quantity, with its uncertainty and limit:
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* const parallax = quantity(m, 'angle') // Quantity<'angle'>, or throws if it isn't an angle
|
|
13
|
+
* parallax.to('arcsec')
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* Give the kind to have the type say what it is; it is checked when it runs. The error
|
|
17
|
+
* ellipse SIMBAD gives a proper motion is kept, and follows a change of unit. A label (a
|
|
18
|
+
* spectral type) isn't a quantity, and throws.
|
|
19
|
+
*/
|
|
20
|
+
export function quantity(measurement: MeasurementLike): Quantity
|
|
21
|
+
export function quantity<K extends Kind>(measurement: MeasurementLike, kind: K): Quantity<K>
|
|
22
|
+
export function quantity(measurement: MeasurementLike, kind?: Kind): Quantity {
|
|
23
|
+
const value = fromMeasurement(measurement)
|
|
24
|
+
return kind === undefined ? value : value.as(kind)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A position as the API gives one: ICRS degrees, at a Julian epoch or none. */
|
|
28
|
+
export interface PositionLike {
|
|
29
|
+
readonly ra: number
|
|
30
|
+
readonly dec: number
|
|
31
|
+
readonly unit: 'deg'
|
|
32
|
+
readonly frame: string | null
|
|
33
|
+
readonly epoch: number | null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A star's distance and motion, any of them optional, for `skyCoord`. Without uncertainties. */
|
|
37
|
+
export interface SkyMotion extends MotionInput {
|
|
38
|
+
readonly pmRaCosdec?: Quantity<'angular speed'>
|
|
39
|
+
readonly pmDec?: Quantity<'angular speed'>
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A position as a SkyCoord in ICRS, its `obstime` the position's epoch (a Julian year, in TT):
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* const { data } = await astro.objects.get('Vega')
|
|
47
|
+
* skyCoord(data.position!).galactic
|
|
48
|
+
* ```
|
|
49
|
+
*
|
|
50
|
+
* Give its distance and motion, chosen from the object's measurements, to move it with
|
|
51
|
+
* `applySpaceMotion`. A SkyCoord takes no uncertainties yet, so pass plain values. A position
|
|
52
|
+
* whose frame isn't ICRS throws.
|
|
53
|
+
*/
|
|
54
|
+
export function skyCoord(position: PositionLike, motion: SkyMotion = {}): SkyCoord {
|
|
55
|
+
if (position.frame === null || position.frame.toUpperCase() !== 'ICRS') {
|
|
56
|
+
throw new TypeError(`This position's frame is ${position.frame === null ? 'not stated' : position.frame}, not ICRS`)
|
|
57
|
+
}
|
|
58
|
+
if (position.unit !== 'deg') throw new TypeError(`A position in ${String(position.unit)} isn't one the API gives`)
|
|
59
|
+
const obstime = motion.obstime ?? (position.epoch === null ? undefined : time(position.epoch, { format: 'jyear' }))
|
|
60
|
+
return coordinate({ ...motion, ra: q(position.ra, 'deg'), dec: q(position.dec, 'deg'), frame: 'icrs', obstime })
|
|
61
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @arcosmos/sdk: the Arcosmos API from TypeScript. Its methods mirror the API's routes, its
|
|
2
|
+
// types come from the API's OpenAPI document, and its answers are the API's JSON as sent, with
|
|
3
|
+
// helpers that turn values into @arcosmos/astronomy's quantities and coordinates.
|
|
4
|
+
export type { ErrorDetails, Operations, Schemas } from './api.ts'
|
|
5
|
+
export { OPERATIONS } from './api.ts'
|
|
6
|
+
export {
|
|
7
|
+
Client, type ClientOptions, DEFAULT_BASE_URL, type Input, type OperationId, type Output, type Quota, type RequestOptions,
|
|
8
|
+
} from './client.ts'
|
|
9
|
+
export { type AnyErrorCode, ArcosmosError, ConnectionError, type DetailsOf, type ErrorCode } from './errors.ts'
|
|
10
|
+
export { type PositionLike, type SkyMotion, quantity, skyCoord } from './helpers.ts'
|
|
11
|
+
export { type PageLike, Paged } from './paging.ts'
|
|
12
|
+
export { Arcosmos, type MatchInput } from './resources.ts'
|
package/src/paging.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// A paged list: awaited, it is its first page; iterated, it is every result across the pages,
|
|
2
|
+
// following `metadata.page.next_cursor` until the last.
|
|
3
|
+
|
|
4
|
+
/** A page of a list, as the API sends one. */
|
|
5
|
+
export interface PageLike<T> {
|
|
6
|
+
data: T[]
|
|
7
|
+
metadata: { page: { next_cursor: string | null } }
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A request for a paged list. `await` it for the first page, as the API sends it, or iterate
|
|
12
|
+
* it for every result across the pages:
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* const first = await astro.stars.search({ distance_max: '10 pc' })
|
|
16
|
+
* for await (const star of astro.stars.search({ distance_max: '10 pc' })) { ... }
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* Nothing is requested until it is awaited or iterated, and the first page is requested once.
|
|
20
|
+
*/
|
|
21
|
+
export class Paged<R extends PageLike<unknown>> implements PromiseLike<R>, AsyncIterable<R['data'][number]> {
|
|
22
|
+
readonly #fetchPage: (cursor: string | undefined) => Promise<R>
|
|
23
|
+
#first: Promise<R> | undefined
|
|
24
|
+
|
|
25
|
+
/** @internal The client makes these; `fetchPage` asks for the page after a cursor, or the first. */
|
|
26
|
+
constructor(fetchPage: (cursor: string | undefined) => Promise<R>) {
|
|
27
|
+
this.#fetchPage = fetchPage
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
#firstPage(): Promise<R> {
|
|
31
|
+
this.#first ??= this.#fetchPage(undefined)
|
|
32
|
+
return this.#first
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
then<A = R, B = never>(
|
|
36
|
+
onFulfilled?: ((page: R) => A | PromiseLike<A>) | null,
|
|
37
|
+
onRejected?: ((reason: unknown) => B | PromiseLike<B>) | null,
|
|
38
|
+
): Promise<A | B> {
|
|
39
|
+
return this.#firstPage().then(onFulfilled, onRejected)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Every page in turn, the first included. */
|
|
43
|
+
async *pages(): AsyncGenerator<R, void, undefined> {
|
|
44
|
+
let page = await this.#firstPage()
|
|
45
|
+
yield page
|
|
46
|
+
while (page.metadata.page.next_cursor !== null) {
|
|
47
|
+
page = await this.#fetchPage(page.metadata.page.next_cursor)
|
|
48
|
+
yield page
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Every result across the pages, in the API's order. Same as iterating the request itself. */
|
|
53
|
+
async *all(): AsyncGenerator<R['data'][number], void, undefined> {
|
|
54
|
+
for await (const page of this.pages()) yield* page.data as R['data'][number][]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
[Symbol.asyncIterator](): AsyncGenerator<R['data'][number], void, undefined> {
|
|
58
|
+
return this.all()
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/resources.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// The API's routes as methods, grouped as its paths are: astro.objects.get('Vega') is
|
|
2
|
+
// GET /objects/Vega. Path parameters come first, then the query or body with the API's own
|
|
3
|
+
// names, then options for the request. Each returns the API's JSON as sent.
|
|
4
|
+
import type { Quantity } from '@arcosmos/astronomy'
|
|
5
|
+
import type { Operations, Schemas } from './api.ts'
|
|
6
|
+
import { Client, type ClientOptions, type Input, type OperationId, type RequestOptions, decimal } from './client.ts'
|
|
7
|
+
import { Paged } from './paging.ts'
|
|
8
|
+
|
|
9
|
+
type Query<O extends OperationId> = Operations[O]['query']
|
|
10
|
+
type Answer<O extends OperationId> = Promise<Operations[O]['response']>
|
|
11
|
+
type Pages<O extends OperationId> = Operations[O]['response'] extends { data: unknown[]; metadata: { page: { next_cursor: string | null } } }
|
|
12
|
+
? Paged<Operations[O]['response']>
|
|
13
|
+
: never
|
|
14
|
+
|
|
15
|
+
/** The radius units POST /sky/match takes, in its body. */
|
|
16
|
+
const MATCH_RADIUS_UNITS = ['arcsec', 'arcmin', 'deg'] as const
|
|
17
|
+
|
|
18
|
+
/** What `sky.match` takes: the API's body, with the radius also as an angle. */
|
|
19
|
+
export type MatchInput = Omit<Schemas['MatchRequest'], 'radius'> & {
|
|
20
|
+
/** How far from each position to look, at most 60 arcsec: `'2 arcsec'` or `q(2, 'arcsec')`. */
|
|
21
|
+
radius: Schemas['MatchRequest']['radius'] | Quantity<'angle'>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function call<O extends OperationId>(
|
|
25
|
+
client: Client, op: O, input: { path?: object; query?: object; body?: unknown }, options?: RequestOptions,
|
|
26
|
+
): Answer<O> {
|
|
27
|
+
return client.request(op, input as Input<O>, options) as Answer<O>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function paged<O extends OperationId>(
|
|
31
|
+
client: Client, op: O, path: object | undefined, query: object | undefined, options?: RequestOptions,
|
|
32
|
+
): Pages<O> {
|
|
33
|
+
return new Paged((cursor) => call(client, op, { path, query: cursor === undefined ? query : { ...query, cursor } }, options) as never) as Pages<O>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function angleText(radius: string | Quantity<'angle'>): string {
|
|
37
|
+
if (typeof radius === 'string') return radius
|
|
38
|
+
if (radius.uncertainty || radius.limit) throw new TypeError('radius is a bound: give it without an uncertainty or limit')
|
|
39
|
+
const unit = radius.unit.toString()
|
|
40
|
+
const known = (MATCH_RADIUS_UNITS as readonly string[]).includes(unit)
|
|
41
|
+
return `${decimal(known ? radius.value : radius.valueIn('arcsec'))} ${known ? unit : 'arcsec'}`
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The Arcosmos API: `new Arcosmos({ apiKey })`, or `new Arcosmos()` to read ARCOSMOS_API_KEY.
|
|
46
|
+
*
|
|
47
|
+
* ```ts
|
|
48
|
+
* const astro = new Arcosmos()
|
|
49
|
+
* const { data } = await astro.objects.get('Proxima Centauri')
|
|
50
|
+
* for await (const star of astro.objects.nearby('Proxima Centauri', { radius: '10 ly' })) { ... }
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* Every method returns the API's JSON as it sends it, typed from its OpenAPI document. Lists
|
|
54
|
+
* in pages return a `Paged`: await it for the first page, iterate it for every result.
|
|
55
|
+
*/
|
|
56
|
+
export class Arcosmos extends Client {
|
|
57
|
+
/** Objects by name, designation or id, and what relates to them: `/objects`. */
|
|
58
|
+
readonly objects = {
|
|
59
|
+
/** An object with its identifiers, relations and every catalog's measurements. `GET /objects/{identifier}` */
|
|
60
|
+
get: (identifier: string, options?: RequestOptions): Answer<'getObject'> =>
|
|
61
|
+
call(this, 'getObject', { path: { identifier } }, options),
|
|
62
|
+
/** The planets an object hosts. `GET /objects/{identifier}/planets` */
|
|
63
|
+
planets: (identifier: string, options?: RequestOptions): Answer<'listPlanets'> =>
|
|
64
|
+
call(this, 'listPlanets', { path: { identifier } }, options),
|
|
65
|
+
/** Stars within a distance in space of an object, nearest first. `GET /objects/{identifier}/nearby` */
|
|
66
|
+
nearby: (identifier: string, query: Query<'listNearbyStars'>, options?: RequestOptions): Pages<'listNearbyStars'> =>
|
|
67
|
+
paged(this, 'listNearbyStars', { identifier }, query, options),
|
|
68
|
+
/** The distance in space between two stars. `GET /objects/{identifier}/distance/{other}` */
|
|
69
|
+
distance: (identifier: string, other: string, options?: RequestOptions): Answer<'getDistance'> =>
|
|
70
|
+
call(this, 'getDistance', { path: { identifier, other } }, options),
|
|
71
|
+
/** Up to 100 identifiers at once, each with its own status. `POST /objects/resolve` */
|
|
72
|
+
resolve: (body: Schemas['ResolveRequest'], options?: RequestOptions): Answer<'resolveIdentifiers'> =>
|
|
73
|
+
call(this, 'resolveIdentifiers', { body }, options),
|
|
74
|
+
/** The objects filed under an object in SIMBAD's hierarchy. `GET /objects/{identifier}/members` */
|
|
75
|
+
members: (identifier: string, query: Query<'listMembers'> = {}, options?: RequestOptions): Pages<'listMembers'> =>
|
|
76
|
+
paged(this, 'listMembers', { identifier }, query, options),
|
|
77
|
+
/** The objects an object is filed under in SIMBAD's hierarchy. `GET /objects/{identifier}/parents` */
|
|
78
|
+
parents: (identifier: string, query: Query<'listParents'> = {}, options?: RequestOptions): Pages<'listParents'> =>
|
|
79
|
+
paged(this, 'listParents', { identifier }, query, options),
|
|
80
|
+
/** Every published parameter set for a planet or its host. `GET /objects/{identifier}/solutions` */
|
|
81
|
+
solutions: (identifier: string, options?: RequestOptions): Answer<'listSolutions'> =>
|
|
82
|
+
call(this, 'listSolutions', { path: { identifier } }, options),
|
|
83
|
+
/** A star's whole system: its stars and their planets. `GET /objects/{identifier}/system` */
|
|
84
|
+
system: (identifier: string, options?: RequestOptions): Answer<'getSystem'> =>
|
|
85
|
+
call(this, 'getSystem', { path: { identifier } }, options),
|
|
86
|
+
/** Objects within an angle of an object on the sky, nearest first. `GET /objects/{identifier}/cone` */
|
|
87
|
+
cone: (identifier: string, query: Query<'listObjectsAround'>, options?: RequestOptions): Pages<'listObjectsAround'> =>
|
|
88
|
+
paged(this, 'listObjectsAround', { identifier }, query, options),
|
|
89
|
+
/** Every type SIMBAD assigns an object, with where each came from. `GET /objects/{identifier}/classifications` */
|
|
90
|
+
classifications: (identifier: string, options?: RequestOptions): Answer<'listClassifications'> =>
|
|
91
|
+
call(this, 'listClassifications', { path: { identifier } }, options),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Searches by position: `/sky`. */
|
|
95
|
+
readonly sky = {
|
|
96
|
+
/** Stars within a distance in space of a point, nearest first. `GET /sky/nearby` */
|
|
97
|
+
nearby: (query: Query<'listStarsNearPoint'>, options?: RequestOptions): Pages<'listStarsNearPoint'> =>
|
|
98
|
+
paged(this, 'listStarsNearPoint', undefined, query, options),
|
|
99
|
+
/** Objects within an angle of a point on the sky, nearest first. `GET /sky/cone` */
|
|
100
|
+
cone: (query: Query<'searchCone'>, options?: RequestOptions): Pages<'searchCone'> =>
|
|
101
|
+
paged(this, 'searchCone', undefined, query, options),
|
|
102
|
+
/** The objects near each of up to 100 positions, at their epochs. `POST /sky/match` */
|
|
103
|
+
match: (body: MatchInput, options?: RequestOptions): Answer<'matchPositions'> =>
|
|
104
|
+
call(this, 'matchPositions', { body: { ...body, radius: angleText(body.radius) } }, options),
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The nearby-stars table and the brightest stars: `/stars`. */
|
|
108
|
+
readonly stars = {
|
|
109
|
+
/** Stars within about 100 pc, filtered and sorted. `GET /stars` */
|
|
110
|
+
search: (query: Query<'searchStars'> = {}, options?: RequestOptions): Pages<'searchStars'> =>
|
|
111
|
+
paged(this, 'searchStars', undefined, query, options),
|
|
112
|
+
/** The Hipparcos stars, brightest first. `GET /stars/bright` */
|
|
113
|
+
bright: (query: Query<'listBrightStars'> = {}, options?: RequestOptions): Pages<'listBrightStars'> =>
|
|
114
|
+
paged(this, 'listBrightStars', undefined, query, options),
|
|
115
|
+
/**
|
|
116
|
+
* Every row of the nearby-stars table as an Apache Arrow IPC stream, about 25 MB. Read the
|
|
117
|
+
* Response with apache-arrow's `tableFromIPC(response)`. `GET /stars/all`
|
|
118
|
+
*/
|
|
119
|
+
all: (options?: RequestOptions): Promise<Response> => this.request('allStars', {}, options),
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The NASA Exoplanet Archive's planets: `/exoplanets`. */
|
|
123
|
+
readonly exoplanets = {
|
|
124
|
+
/** Planets filtered by distance, size, mass, orbit and discovery. `GET /exoplanets` */
|
|
125
|
+
search: (query: Query<'searchExoplanets'> = {}, options?: RequestOptions): Pages<'searchExoplanets'> =>
|
|
126
|
+
paged(this, 'searchExoplanets', undefined, query, options),
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The catalogs behind every value, their releases and rows: `/catalogs`. */
|
|
130
|
+
readonly catalogs = {
|
|
131
|
+
/** Every catalog, with its release, license and citation. `GET /catalogs` */
|
|
132
|
+
list: (options?: RequestOptions): Answer<'listCatalogs'> => call(this, 'listCatalogs', {}, options),
|
|
133
|
+
/** One catalog, with its columns' documentation. `GET /catalogs/{id}` */
|
|
134
|
+
get: (id: string, options?: RequestOptions): Answer<'getCatalog'> => call(this, 'getCatalog', { path: { id } }, options),
|
|
135
|
+
/** One row of a catalog, as published. `GET /catalogs/{id}/records/{key}` */
|
|
136
|
+
record: (id: string, key: string, options?: RequestOptions): Answer<'getCatalogRecord'> =>
|
|
137
|
+
call(this, 'getCatalogRecord', { path: { id, key } }, options),
|
|
138
|
+
/** A catalog's rows within an angle of a point, in sky order. `GET /catalogs/{id}/cone` */
|
|
139
|
+
cone: (id: string, query: Query<'catalogCone'>, options?: RequestOptions): Pages<'catalogCone'> =>
|
|
140
|
+
paged(this, 'catalogCone', { id }, query, options),
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Canonical types and SIMBAD's: `/types`. */
|
|
144
|
+
readonly types = {
|
|
145
|
+
/** Every canonical type and SIMBAD type, with the mapping between them. `GET /types` */
|
|
146
|
+
list: (options?: RequestOptions): Answer<'listTypes'> => call(this, 'listTypes', {}, options),
|
|
147
|
+
/** One SIMBAD type, with its ancestors, subtypes and candidates. `GET /types/{otype}` */
|
|
148
|
+
get: (otype: string, options?: RequestOptions): Answer<'getType'> => call(this, 'getType', { path: { otype } }, options),
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Name completion: `/names`. */
|
|
152
|
+
readonly names = {
|
|
153
|
+
/** Objects whose names start with what was typed, for a search box. `GET /names` */
|
|
154
|
+
complete: (query: Query<'completeNames'>, options?: RequestOptions): Answer<'completeNames'> =>
|
|
155
|
+
call(this, 'completeNames', { query }, options),
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The account a key belongs to: `/account`. Not counted toward the quota. */
|
|
159
|
+
readonly account = {
|
|
160
|
+
/** The plan, this month's quota, the keys and 30 days of usage. `GET /account` */
|
|
161
|
+
get: (options?: RequestOptions): Answer<'getAccount'> => call(this, 'getAccount', {}, options),
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A key's own usage, and revoking it: `/api-keys`. Keys are created on the website. */
|
|
165
|
+
readonly apiKeys = {
|
|
166
|
+
/** A key with its usage by route. `GET /api-keys/{id}` */
|
|
167
|
+
get: (id: string, options?: RequestOptions): Answer<'getApiKey'> => call(this, 'getApiKey', { path: { id } }, options),
|
|
168
|
+
/** Revokes a key at once. `DELETE /api-keys/{id}` */
|
|
169
|
+
revoke: (id: string, options?: RequestOptions): Answer<'revokeApiKey'> => call(this, 'revokeApiKey', { path: { id } }, options),
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
constructor(options: ClientOptions = {}) {
|
|
173
|
+
super(options)
|
|
174
|
+
}
|
|
175
|
+
}
|