astromansion 0.1.0-alpha.0 → 0.1.0-alpha.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
@@ -1,46 +1,949 @@
1
+ ![Astro Mansion, Official JavaScript SDK](https://raw.githubusercontent.com/mustafayavuzak/astromansion-js/main/banner.webp)
2
+
1
3
  # AstroMansion
2
4
 
3
- Official JavaScript and TypeScript client for the [AstroMansion](https://astromansion.com) astrology API.
5
+ [![npm](https://img.shields.io/npm/v/astromansion)](https://www.npmjs.com/package/astromansion)
6
+ [![Node.js](https://img.shields.io/node/v/astromansion)](https://www.npmjs.com/package/astromansion)
7
+ [![License](https://img.shields.io/npm/l/astromansion)](LICENSE)
4
8
 
5
- > Early alpha. `0.1.0-alpha.0` holds the core client, whose `request()`
6
- > reaches every published endpoint. A typed method for each endpoint comes in
7
- > the next alpha.
9
+ Official JavaScript and TypeScript client for the [AstroMansion](https://astromansion.com) astrology API.
8
10
 
9
11
  Nothing is computed locally. Every call reaches `https://api.astromansion.com`,
10
12
  which owns the ephemeris, your plan, your quota and your rate limit. The
11
13
  package never opens a feature the server did not grant.
12
14
 
15
+ It is the JavaScript twin of the
16
+ [Python SDK](https://github.com/mustafayavuzak/astromansion-python): the same
17
+ methods under the same names, written in camelCase, the same arguments, the
18
+ same answers, and the same errors.
19
+
13
20
  ## Install
14
21
 
15
22
  ```bash
16
- npm install astromansion@next
23
+ npm install astromansion
24
+ ```
25
+
26
+ Node.js 22 or newer, Bun, Deno, and edge runtimes such as Cloudflare Workers.
27
+ The package has no dependency. It sends through the platform's own `fetch`,
28
+ with types included.
29
+
30
+ Behind a corporate proxy, a SOCKS proxy or Tor, pass a `fetch` that goes
31
+ through it. The package adds no dependency for that. With undici's
32
+ `ProxyAgent`:
33
+
34
+ ```js
35
+ import { fetch as undiciFetch, ProxyAgent } from "undici";
36
+ import { AstroMansion } from "astromansion";
37
+
38
+ const proxy = new ProxyAgent("http://proxy.example:8080");
39
+ const client = new AstroMansion({
40
+ fetch: (input, init) => undiciFetch(input, { ...init, dispatcher: proxy }),
41
+ });
42
+ ```
43
+
44
+ A SOCKS dispatcher, such as the one `fetch-socks` builds for Tor, goes in the
45
+ same place.
46
+
47
+ ## Try it without an account
48
+
49
+ The natal chart endpoint also answers visitors, under the API's
50
+ [visitor limits](https://astromansion.com/en/docs#limits), which are counted
51
+ per IP address. Ask for that explicitly:
52
+
53
+ ```js
54
+ import { AstroMansion } from "astromansion";
55
+
56
+ const client = new AstroMansion({ requireKey: false });
57
+
58
+ const chart = await client.natal({
59
+ date: "2000-01-01",
60
+ time: "12:00",
61
+ lat: 51.4779,
62
+ lon: 0,
63
+ timezone: "Europe/London",
64
+ });
65
+
66
+ console.log(chart.summary.Sun.sign);
67
+ ```
68
+
69
+ Without `requireKey: false` a missing key is still an error, so an application
70
+ that lost its key fails at once instead of quietly running on visitor limits.
71
+
72
+ ## Get an API key
73
+
74
+ [Create a free account](https://astromansion.com/en/developers?ref=js-sdk#register),
75
+ confirm your email address, then open your account page and generate a key.
76
+ The Free plan costs nothing. Requests made with the key count against that
77
+ account, under the plan it already has.
78
+
79
+ ## First chart
80
+
81
+ Put the key in the environment rather than in your source.
82
+
83
+ macOS and Linux:
84
+
85
+ ```bash
86
+ export ASTROMANSION_API_KEY="your key"
87
+ ```
88
+
89
+ Windows PowerShell:
90
+
91
+ ```powershell
92
+ $env:ASTROMANSION_API_KEY = "your key"
93
+ ```
94
+
95
+ Windows Command Prompt:
96
+
97
+ ```bat
98
+ set ASTROMANSION_API_KEY=your key
99
+ ```
100
+
101
+ Each of these lasts for the current terminal. On Windows,
102
+ `setx ASTROMANSION_API_KEY "your key"` keeps it for every terminal opened
103
+ afterwards.
104
+
105
+ ```js
106
+ import { AstroMansion } from "astromansion";
107
+
108
+ const client = new AstroMansion();
109
+
110
+ const chart = await client.natal({
111
+ date: "2000-01-01",
112
+ time: "12:00",
113
+ lat: 51.4779,
114
+ lon: 0,
115
+ timezone: "Europe/London",
116
+ });
117
+
118
+ console.log(chart.summary.Sun.sign);
119
+ console.log(chart.planets[0].house);
120
+ ```
121
+
122
+ Birth data is passed flat. The API nests it under `birth`, and the client does
123
+ that for you.
124
+
125
+ Fields: `date` as `YYYY-MM-DD`, `time` as `HH:MM` (leave it out if unknown),
126
+ `lat` and `lon` in decimal degrees, `timezone` as an hour offset or an IANA
127
+ zone name, `houses` for a house system. The client checks them before
128
+ anything is sent, so a malformed date is reported by the field you wrote.
129
+
130
+ JavaScript has no keyword arguments, so a method takes one object where the
131
+ Python SDK takes keywords. The method's other arguments, such as `options`,
132
+ may stand beside the birth fields or come in a second object:
133
+
134
+ ```js
135
+ const chart = await client.natal({
136
+ date: "2000-01-01",
137
+ lat: 51.4779,
138
+ lon: 0,
139
+ options: { wheel: true },
140
+ });
141
+ const same = await client.natal(
142
+ { date: "2000-01-01", lat: 51.4779, lon: 0 },
143
+ { options: { wheel: true } },
144
+ );
145
+ ```
146
+
147
+ An argument given in both objects, or a field the method does not take, is
148
+ refused before a request is sent.
149
+
150
+ ## Where the key comes from
151
+
152
+ In order: the `apiKey` option, then `setApiKey(...)`, then
153
+ `ASTROMANSION_API_KEY`. With none of them the constructor throws
154
+ `AuthenticationError` before any request is sent, so a forgotten key is
155
+ reported as a forgotten key.
156
+
157
+ ```js
158
+ const client = new AstroMansion({ apiKey: "your key" });
159
+ ```
160
+
161
+ `new AstroMansion({ requireKey: false })` lifts that check. A key found in any
162
+ of the three places is still sent, and without one the request goes out as a
163
+ visitor's.
164
+
165
+ `reset()` drops the module key and the shared client, which is what a test
166
+ wants between cases.
167
+
168
+ ## Quick use
169
+
170
+ For a notebook or a one-file script:
171
+
172
+ ```js
173
+ import * as am from "astromansion";
174
+
175
+ am.setApiKey("your key"); // or rely on the environment
176
+ const chart = await am.natal({ date: "2000-01-01", lat: 51.4779, lon: 0 });
177
+ ```
178
+
179
+ Applications should build a client instead. Two of them can carry two
180
+ different keys, and neither depends on the module's shared state.
181
+
182
+ ## Practical examples
183
+
184
+ The repository includes a complete, runnable natal-chart program and a
185
+ cookbook for the main API workflows:
186
+
187
+ - [`examples/natal_chart.ts`](https://github.com/mustafayavuzak/astromansion-js/blob/main/examples/natal_chart.ts)
188
+ prints a chart, its aspects, and Arabic lots.
189
+ - [`EXAMPLES.md`](https://github.com/mustafayavuzak/astromansion-js/blob/main/EXAMPLES.md)
190
+ covers concurrent requests, extended bodies, synastry, predictive
191
+ techniques, MansionSQL, rendered files, batch jobs, and error handling.
192
+
193
+ Three common calls use the same birth object:
194
+
195
+ ```js
196
+ import { AstroMansion } from "astromansion";
197
+
198
+ const birth = {
199
+ date: "2000-01-01",
200
+ time: "12:00",
201
+ lat: 51.4779,
202
+ lon: 0,
203
+ timezone: "Europe/London",
204
+ };
205
+
206
+ const client = new AstroMansion();
207
+ const natal = await client.natal(birth);
208
+ const transits = await client.transits(birth, { options: { year: 2027 } });
209
+ await client.renderSvg(birth, { output: "birth-chart.svg" });
210
+
211
+ console.log(natal.summary.Sun.sign);
212
+ console.log(transits.data);
17
213
  ```
18
214
 
19
- The package targets Node.js 22 or newer, Bun, Deno, edge runtimes such as
20
- Cloudflare Workers, and React Native. It has no runtime dependencies.
215
+ JavaScript has no `with` block. `fetch` keeps no connection pool for a client
216
+ to release, so a client needs no closing. `client.close()` ends one when you
217
+ want any later call refused.
218
+
219
+ ## Async
21
220
 
22
- ## Use
221
+ Every method returns a promise:
23
222
 
24
- ```ts
223
+ ```js
25
224
  import { AstroMansion } from "astromansion";
26
225
 
27
- const client = new AstroMansion(); // reads ASTROMANSION_API_KEY
28
- const chart = await client.request("POST", "/v1/natal", {
29
- json: {
30
- birth: {
31
- date: "2000-01-01",
32
- time: "12:00",
33
- lat: 51.4779,
34
- lon: 0,
35
- timezone: "Europe/London",
36
- },
226
+ const client = new AstroMansion();
227
+ const [natal, aspects] = await Promise.all([
228
+ client.natal(birth),
229
+ client.aspects(birth, { options: { orb: 1, limit: 25 } }),
230
+ ]);
231
+ ```
232
+
233
+ The Python SDK has two clients, `AstroMansion` and `AsyncAstroMansion`,
234
+ because Python cannot make one class serve both. Networking in JavaScript is
235
+ asynchronous, so the one `AstroMansion` is the counterpart of Python's
236
+ `AsyncAstroMansion`, with the same method names, the same arguments, and the
237
+ same errors.
238
+
239
+ ## Reading a response
240
+
241
+ The response is the server's own JSON, readable either way:
242
+
243
+ ```js
244
+ chart.summary.Sun.sign;
245
+ chart["summary"]["Sun"]["sign"];
246
+ chart.toDict();
247
+ ```
248
+
249
+ Nothing is remodelled, so a field the API adds reaches you instead of being
250
+ dropped, and no field it did not send is invented.
251
+
252
+ Some endpoints answer with the data itself and some wrap it as
253
+ `{"technique": ..., "result": ...}`. The client opens that wrapper, so every
254
+ response reads the same way and you never have to remember which kind you
255
+ called:
256
+
257
+ ```js
258
+ const chart = await client.vedicChart({
259
+ date: "2000-01-01",
260
+ lat: 51.4779,
261
+ lon: 0,
262
+ });
263
+
264
+ chart.data; // the payload, wrapper removed
265
+ chart.technique; // what the server called it, when it said
266
+ chart.raw; // the untouched body, wrapper included
267
+ ```
268
+
269
+ A body that carries a real `result` field of its own is left alone. The
270
+ wrapper is recognised by its exact shape rather than by the presence of a
271
+ name that data is allowed to use.
272
+
273
+ Where JavaScript reads differently from Python:
274
+
275
+ - A field the answer does not carry reads as `undefined`. Python's `Result`
276
+ raises `AttributeError` there and lists the fields it has. In JavaScript,
277
+ `await`, `JSON.stringify`, `console.log`, and React look up names an object
278
+ may lack, and a `Result` that threw would break them. TypeScript names a
279
+ mistyped field before the code runs.
280
+ - `data`, `raw`, `technique`, `toDict`, and `toString` belong to the
281
+ `Result`. Python can read `chart.technique` and `chart["technique"]` apart.
282
+ In JavaScript the two are one, so a data field of one of these names is read
283
+ through `data`, as in `chart.data.technique`.
284
+ - Each answer is checked against the shape the API publishes before it is
285
+ returned, which is what lets TypeScript type it field by field. An answer
286
+ outside that shape rejects with an `AstroMansionError` whose `errorCode` is
287
+ `unexpected_answer`, and the answer itself is the error's `details`. The
288
+ Python SDK returns such an answer as it arrived.
289
+ - An answer whose shape the API's schema leaves open, as most techniques'
290
+ results are, comes back as JSON values. In TypeScript, narrow them before
291
+ reading a field.
292
+
293
+ ## Arabic lots, fixed stars and the rest of the catalog
294
+
295
+ `natal` answers with the chart proper. Anything beyond it is named on `chart`,
296
+ through `options.categories`:
297
+
298
+ ```js
299
+ const lots = await client.chart(
300
+ {
301
+ date: "2000-01-01",
302
+ time: "12:00",
303
+ lat: 51.4779,
304
+ lon: 0,
305
+ timezone: "Europe/London",
37
306
  },
307
+ { options: { categories: ["arabic_lots"] } },
308
+ );
309
+
310
+ for (const lot of lots.data.bodies.arabic_lots) {
311
+ console.log(lot.name, lot.sign, lot.dms, lot.house);
312
+ }
313
+ ```
314
+
315
+ Bodies come back grouped under the category that produced them, so read the
316
+ group you asked for. The catalog publishes 38 Arabic lots and 908 named
317
+ fixed-star entries, along with `planets`, `dwarfs`, `asteroids`, `centaurs`,
318
+ `comets`, `hypotheticals`, `points`, `advanced_points`, `lilith`,
319
+ `planetary_nodes`, `exoplanets`, `antiscia` and `eclipses`. The API still
320
+ accepts the retired `moons` selector as an input alias, but responses use
321
+ `antiscia`.
322
+
323
+ White Moon is filed under `hypotheticals` and comes back named
324
+ `Selena/White Moon`. The retired `white_moon` selector is still accepted, but
325
+ it now answers the whole `hypotheticals` group. For White Moon alone, pass
326
+ `options: { include: ["White Moon"], exclusive: true }`.
327
+
328
+ The `fixed_stars` calculation category resolves 906 unambiguous targets.
329
+ `Isis` and `Ketu` remain discoverable catalog names, but a bare-name lookup for
330
+ either resolves the higher-priority non-stellar point with the same name.
331
+
332
+ `chart` answers one page at a time, and a large category is more than one
333
+ page. Use `bodies` to read the whole of it and let the client follow the
334
+ paging:
335
+
336
+ ```js
337
+ const found = await client.bodies("fixed_stars", "arabic_lots", {
338
+ date: "2000-01-01",
339
+ time: "12:00",
340
+ lat: 51.4779,
341
+ lon: 0,
342
+ timezone: "Europe/London",
343
+ });
344
+
345
+ found.fixed_stars.length; // 906, in six requests
346
+ found.arabic_lots.length; // 38
347
+ ```
348
+
349
+ Naming several categories reads them in one walk. The return is always an
350
+ object keyed by the categories you asked for, one or several, so the shape
351
+ never depends on how many.
352
+
353
+ Each page costs a network round trip and the calculation inside it is a
354
+ rounding error beside that, so `bodies` asks for the largest page the API
355
+ serves. `pageSize` lowers it, and lowering it buys nothing. The 906
356
+ calculation targets take six requests at the default page size.
357
+
358
+ Some categories are enormous. `asteroids` holds twenty-eight thousand bodies,
359
+ which is a hundred and seventy-seven round trips with nothing printed until
360
+ the last one lands, and a program that prints nothing for a minute cannot be
361
+ told apart from one that has hung. A walk that large stops after the first
362
+ page and tells you the size:
363
+
364
+ ```js
365
+ await am.bodies("asteroids", { date: "2000-01-01", lat: 51.4779, lon: 0 });
366
+ // ValidationError: asteroids holds 28214 bodies, which is 177 requests and
367
+ // will print nothing until the last one lands. Pass confirmLarge: true ...
368
+ ```
369
+
370
+ Read it anyway, or watch it arrive:
371
+
372
+ ```js
373
+ const found = await client.bodies("asteroids", {
374
+ date: "2000-01-01",
375
+ lat: 51.4779,
376
+ lon: 0,
377
+ confirmLarge: true,
378
+ onPage: (done, left, rows) => console.log(`${done} done, ${left} to go`),
379
+ });
380
+ ```
381
+
382
+ For a handful of named bodies there is no walk at all:
383
+
384
+ ```js
385
+ const page = await client.chart(
386
+ { date: "2000-01-01", lat: 51.4779, lon: 0 },
387
+ {
388
+ options: { include: ["Ceres", "Pallas", "Juno", "Vesta"], exclusive: true },
389
+ },
390
+ );
391
+
392
+ for (const rows of Object.values(page.data.bodies)) {
393
+ for (const body of rows) {
394
+ console.log(body.name, body.sign, body.dms);
395
+ }
396
+ }
397
+ ```
398
+
399
+ Read every group rather than the one you expected. Bodies are filed under the
400
+ category the catalog puts them in, not the category you were thinking of when
401
+ you named them. Ceres was an asteroid in 1801 and has been a dwarf planet
402
+ since 2006, so it arrives under `dwarfs` while Pallas, Juno and Vesta arrive
403
+ under `asteroids`. A loop over `bodies.asteroids` alone finds three of the
404
+ four and reports the fourth as missing.
405
+
406
+ `exclusive` narrows the catalog, not the chart. The angles and the derived
407
+ points are calculated either way, so `points` and `advanced_points` are still
408
+ in the answer. Filter by name if you want only what you asked for:
409
+
410
+ ```js
411
+ const wanted = new Set(["Ceres", "Pallas", "Juno", "Vesta"]);
412
+
413
+ for (const rows of Object.values(page.data.bodies)) {
414
+ for (const body of rows) {
415
+ if (wanted.has(body.name)) {
416
+ console.log(body.name, body.sign, body.dms);
417
+ }
418
+ }
419
+ }
420
+ ```
421
+
422
+ Reach for `chart` directly when you want one page rather than the category,
423
+ and read the group with `?? []`. The chart's own bodies are calculated
424
+ alongside the categories you name and the page is a window over that whole
425
+ selection, so a small `catalog_limit` can fill the first page with planets
426
+ and angles before a single star appears, leaving no `fixed_stars` key at all.
427
+ `catalog_page.total` counts the whole selection rather than any one category.
428
+
429
+ There is no ceiling on how many you may read this way. `options.all_bodies`
430
+ walks every category at once and needs the full-catalog scope that comes with
431
+ Pro and Enterprise. Naming the categories yourself does not.
432
+
433
+ ## MansionSQL
434
+
435
+ A chart is a table of bodies, a table of houses and a table of aspects, and
436
+ the questions people ask of one are the questions SQL was written for: which
437
+ planets are retrograde, which aspects are inside a degree, how the signs are
438
+ distributed. `query` sends a `SELECT` and the server calculates the chart and
439
+ answers it.
440
+
441
+ ```js
442
+ const rows = await client.query({
443
+ birth: {
444
+ date: "2000-01-01",
445
+ time: "12:00",
446
+ lat: 51.4779,
447
+ lon: 0,
448
+ timezone: 0,
449
+ },
450
+ sql: "SELECT name, sign, dms FROM planets WHERE retrograde = 1",
38
451
  });
452
+
453
+ for (const row of rows.data) {
454
+ console.log(row.name, row.sign, row.dms);
455
+ }
456
+ // Saturn Taurus 10°23′44″
457
+ ```
458
+
459
+ `query` takes the request body rather than flat birth fields, because a
460
+ statement may name two charts and a moment, and each of them needs its own
461
+ birth block. It needs the `advanced` scope.
462
+
463
+ ### Tables
464
+
465
+ Every table but three carries the body columns: `code`, `name`, `longitude`,
466
+ `latitude`, `distance`, `speed`, `sign`, `sign_index`, `house`, `retrograde`,
467
+ `dms`, `category`.
468
+
469
+ | Table | One row per |
470
+ | --------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
471
+ | `chart`, `bodies` | every body the chart calculated |
472
+ | `planets` | the planets |
473
+ | `points` | angles and derived points |
474
+ | `advanced_points` | the further derived points |
475
+ | `dwarfs`, `centaurs`, `comets`, `antiscia`, `eclipses`, `lilith`, `exoplanets`, `hypotheticals`, `planetary_nodes`, `arabic_lots` | that catalog category |
476
+ | `natal_a` | the `birth` chart, named for joins |
477
+ | `natal_b` | the `partner` chart |
478
+ | `transits` | the `moment` chart |
479
+
480
+ Three have columns of their own:
481
+
482
+ | Table | One row per | Columns |
483
+ | --------- | --------------------------------------------------------- | -------------------------------------------------------------------- |
484
+ | `houses` | each of the twelve | `number`, `cusp`, `sign`, `dms`, `size`, `bodies` |
485
+ | `aspects` | each aspect found | `a`, `b`, `aspect`, `angle`, `orb`, `separation`, `a_sign`, `b_sign` |
486
+ | `stars` | each point placed against a stellar position, 953 of them | `name`, `longitude`, `latitude`, `sign`, `dms`, `magnitude`, `orb` |
487
+ | `lots` | each Arabic lot the engine computes, 38 of them | `name`, `longitude`, `sign`, `dms`, `house` |
488
+
489
+ `natal_b` needs `partner`, and a statement naming it without one is refused.
490
+ `transits` uses `moment`, and without one it is the current instant at the
491
+ birth location.
492
+
493
+ There is no `asteroids` table. One chart holds at most 192 bodies and the
494
+ category is twenty-eight thousand, so the query is refused rather than
495
+ silently reduced to the first 192:
496
+
497
+ ```js
498
+ await client.query({ birth, sql: "SELECT name FROM asteroids" });
499
+ // ValidationError: The query asks for more bodies than one chart can hold.
500
+ // Narrow it with WHERE name = 'Pallas', a minor planet number such as
501
+ // WHERE name = '1198', or WHERE name IN (...). Use /v1/catalog to look a
502
+ // body up by name.
503
+ ```
504
+
505
+ `stars` answers 953 rows, the `fixed_stars` catalog lists 908 names, and the
506
+ category walk returns 906 unambiguous calculation targets. These are different
507
+ selections, so a count taken from one does not describe the others. The table
508
+ contains every catalog row the engine places against a stellar position: 908
509
+ fixed-star rows, 40 exoplanets and 5 galactic and deep-sky points filed under
510
+ `advanced_points`. One row per published name means counting rows and names
511
+ gives the same answer.
512
+
513
+ `lots` and the `arabic_lots` category do not divide that way. Both answer 38.
514
+ The table gives the lots computed for one chart, the category gives the names
515
+ those lots are looked up by, and they are the same 38 lots.
516
+
517
+ `SELECT` only. Anything else is refused before it reaches the engine, so a
518
+ statement cannot write, drop or reach outside the chart it was given.
519
+
520
+ ```js
521
+ await client.query({ birth, sql: "DELETE FROM planets" });
522
+ // ValidationError: expected SELECT at offset 0
523
+ ```
524
+
525
+ ### A hundred rows
526
+
527
+ An answer is capped at a hundred rows, and a statement that would exceed it is
528
+ refused rather than truncated, so a partial answer never arrives looking whole:
529
+
530
+ ```js
531
+ await client.query({ birth, sql: "SELECT name FROM stars" });
532
+ // ValidationError: MansionSQL returned 100 rows of 953; add LIMIT or narrow
533
+ // the query
534
+ ```
535
+
536
+ Add `LIMIT`, or narrow with `WHERE`. `COUNT(*)` is one row, so counting a
537
+ large table is always available.
538
+
539
+ ### What the dialect supports
540
+
541
+ `WHERE`, `GROUP BY`, `HAVING`, `ORDER BY`, `LIMIT`, `OFFSET`, `DISTINCT`,
542
+ `JOIN`, `AS`, `IN`, `NOT IN`, `LIKE`, `BETWEEN`, `IS NULL`, `EXISTS`,
543
+ `CASE WHEN`, and comparison and arithmetic on any column.
544
+
545
+ Clauses apply in the SQL order, which is worth stating because it decides what
546
+ `HAVING` sees and what the hundred-row cap counts:
547
+
548
+ ```
549
+ FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT
550
+ ```
551
+
552
+ ```js
553
+ // The tightest aspects first.
554
+ "SELECT a, b, aspect, orb FROM aspects WHERE orb < 1 ORDER BY orb LIMIT 20";
555
+
556
+ // How the chart is distributed.
557
+ "SELECT sign, COUNT(*) AS n FROM planets GROUP BY sign ORDER BY n DESC";
558
+
559
+ // Angles only.
560
+ "SELECT number, sign, dms FROM houses WHERE number IN (1, 10)";
561
+
562
+ // Each planet with the sign on the cusp of the house it occupies.
563
+ "SELECT p.name, h.sign FROM planets p JOIN houses h ON p.house = h.number";
564
+
565
+ // The brightest fixed stars.
566
+ "SELECT name, sign, dms, magnitude FROM stars ORDER BY magnitude LIMIT 10";
567
+ ```
568
+
569
+ #### Aggregates
570
+
571
+ | Function | Argument | On an empty set | Notes |
572
+ | ------------ | -------------- | --------------- | ---------------------------------------------- |
573
+ | `COUNT(*)` | none | `0` | counts rows |
574
+ | `COUNT(col)` | any | `0` | counts non-`NULL` values, so it can be smaller |
575
+ | `MIN(col)` | number or text | `NULL` | text compares lexically |
576
+ | `MAX(col)` | number or text | `NULL` | text compares lexically |
577
+ | `AVG(col)` | number | `NULL` | refuses a text column |
578
+ | `SUM(col)` | number | `NULL` | refuses a text column |
579
+
580
+ `AVG` and `SUM` refuse a column that is not numeric rather than skipping the
581
+ rows they cannot read. Skipping is the dangerous answer. Over a column that is
582
+ numeric for some rows and text for others it returns the average of part of
583
+ the column with nothing to say the rest was dropped.
584
+
585
+ ```js
586
+ await client.query({ birth, sql: "SELECT AVG(sign) AS v FROM planets" });
587
+ // ValidationError: AVG requires a numeric column; sign is text
588
+ ```
589
+
590
+ `HAVING` filters groups after grouping, and its operands may be aggregates. It
591
+ requires a `GROUP BY`. Some engines allow it without one and read the whole
592
+ result as a single group, but in practice a bare `HAVING` is a `WHERE` written
593
+ in the wrong place, and saying so is more use than answering it.
594
+
595
+ ```js
596
+ // Stellium: three or more bodies in one sign.
597
+ "SELECT sign, COUNT(*) AS n FROM planets GROUP BY sign HAVING COUNT(*) >= 3";
598
+
599
+ // Signs the chart moves slowly through.
600
+ "SELECT sign, AVG(speed) AS v FROM planets GROUP BY sign HAVING AVG(speed) < 0";
601
+ ```
602
+
603
+ An aggregate collapses rows, so `SELECT COUNT(*) FROM stars` is one row and
604
+ never meets the hundred-row cap. The cap counts the final result, after
605
+ `HAVING`.
606
+
607
+ #### Astrological functions
608
+
609
+ Scalar functions, usable anywhere a column is: in `SELECT`, `WHERE`,
610
+ `GROUP BY`, `ORDER BY`, and inside an aggregate. All are lookups or integer
611
+ arithmetic, and none of them calculates anything further.
612
+
613
+ | Function | Argument | Returns |
614
+ | --------------------------------------- | -------------------------- | ---------------------------------------------------------- |
615
+ | `ELEMENT(sign)` | sign name | `fire`, `earth`, `air`, `water` |
616
+ | `MODALITY(sign)` | sign name | `cardinal`, `fixed`, `mutable` |
617
+ | `RULER(sign)` | sign name | the traditional ruler's name |
618
+ | `DIGNITY(body, sign)` | body and sign names | `domicile`, `exaltation`, `detriment`, `fall`, `peregrine` |
619
+ | `DECAN(longitude)` | degrees | `1`, `2` or `3` |
620
+ | `ANGULAR(house)` | 1 to 12 | `angular`, `succedent`, `cadent` |
621
+ | `ORB(a, b)` | two longitudes | their separation, never over 180 |
622
+ | `SEPARATION(a, b)` | two longitudes | the same |
623
+ | `ABS`, `ROUND`, `FLOOR`, `CEIL`, `SIGN` | a number | the usual arithmetic |
624
+ | `COALESCE(a, b, …)` | up to 16 values | the first that is not `NULL` |
625
+ | `LENGTH(text)` | text | its length in characters |
626
+ | `SUBSTR(text, from[, count])` | text and 1-based positions | the slice |
627
+
628
+ `RULER` is the traditional rulership and only that: Mars for Scorpio, Saturn
629
+ for Aquarius, Jupiter for Pisces. A modern variant would be a second answer to
630
+ the same question decided by a setting the statement cannot show, so one query
631
+ would mean two things. If it is wanted it will be a second function under its
632
+ own name.
633
+
634
+ `DIGNITY` is the classical seven-planet table. Anything outside the seven is
635
+ `peregrine`, including Uranus, Neptune, Pluto and the asteroids. Inventing a
636
+ domicile for them would be inventing astrology rather than reading it.
637
+ Triplicity, term and face are real dignities and are deliberately not reported,
638
+ because they need a degree and a day-night distinction and this function is
639
+ given a sign. Mercury in Virgo holds both domicile and exaltation and is
640
+ reported as `domicile`.
641
+
642
+ `LENGTH` and `SUBSTR` count characters, not bytes. A degree reads
643
+ `11°1′36″`, which is eight characters written in thirteen bytes, so `LENGTH`
644
+ answers 8 and `SUBSTR(dms, 3, 1)` answers `°` rather than the first half of it.
645
+
646
+ `COALESCE` earns its place on aggregates. No column of a chart is ever `NULL`,
647
+ but an aggregate over a group that matched nothing is, so
648
+ `COALESCE(AVG(orb), 0)` is the way to ask for a floor instead of an unknown.
649
+
650
+ `NULL` in, `NULL` out. A body with no house returns `NULL` from `ANGULAR`
651
+ rather than a default. A name no sign or body carries is refused, and the
652
+ message quotes the value it was given:
653
+
654
+ ```js
655
+ await client.query({ birth, sql: "SELECT ELEMENT('Lion') AS e FROM planets" });
656
+ // ValidationError: ELEMENT does not know the sign 'Lion'
657
+ ```
658
+
659
+ ```js
660
+ // Elemental balance.
661
+ "SELECT ELEMENT(sign) AS element, COUNT(*) AS n FROM planets GROUP BY ELEMENT(sign) ORDER BY n DESC";
662
+
663
+ // Planets in their own sign.
664
+ "SELECT name, sign FROM planets WHERE DIGNITY(name, sign) = 'domicile'";
665
+
666
+ // The single tightest aspect in the chart.
667
+ "SELECT MIN(orb) AS tightest FROM aspects";
668
+
669
+ // Angular houses only, with the decan.
670
+ "SELECT name, sign, DECAN(longitude) AS decan FROM planets WHERE ANGULAR(house) = 'angular'";
671
+ ```
672
+
673
+ #### Subqueries
674
+
675
+ A subquery may stand after `IN` or `NOT IN`, after `EXISTS`, or as a single
676
+ value in the `SELECT` list. The inner statement may name a different table
677
+ than the outer one. Both charts are already calculated, so this filters data
678
+ in hand rather than calculating a second time.
679
+
680
+ ```js
681
+ // Everything aspecting a retrograde planet.
682
+ "SELECT a, b, aspect, orb FROM aspects WHERE a IN (SELECT name FROM planets WHERE retrograde = 1)";
683
+ ```
684
+
685
+ The inner statement must select exactly one column, and is told so by count:
686
+
687
+ ```js
688
+ await client.query({
689
+ birth,
690
+ sql: "SELECT a FROM aspects WHERE a IN (SELECT name, sign FROM planets)",
691
+ });
692
+ // ValidationError: subquery must select one column, got 2
693
+ ```
694
+
695
+ The hundred-row cap applies to the final answer only. An inner query may
696
+ legitimately produce all 953 stars while the outer answer is three rows.
697
+
698
+ `NOT IN` follows standard SQL where the inner set contains a `NULL`, which
699
+ surprises people and is worth stating plainly. **If any inner value is `NULL`,
700
+ `NOT IN` returns no rows at all.** The comparison is unknown rather than false,
701
+ and unknown is not true, so nothing passes. `IN` is unaffected, and it still
702
+ matches the values that are there. Add `WHERE col IS NOT NULL` to the inner
703
+ statement when the column has gaps. An empty inner set behaves the way the
704
+ logic implies. `IN` matches nothing, and `NOT IN` matches everything.
705
+
706
+ Two charts in one statement, which is synastry written as a join:
707
+
708
+ ```js
709
+ const rows = await client.query({
710
+ birth: {
711
+ date: "2000-01-01",
712
+ time: "12:00",
713
+ lat: 51.4779,
714
+ lon: 0,
715
+ timezone: 0,
716
+ },
717
+ partner: {
718
+ date: "1995-03-14",
719
+ time: "08:20",
720
+ lat: 48.8566,
721
+ lon: 2.3522,
722
+ timezone: "Europe/Paris",
723
+ },
724
+ sql: "SELECT a.name, a.sign, b.name AS partner FROM natal_a a JOIN natal_b b ON a.sign = b.sign LIMIT 50",
725
+ });
726
+ ```
727
+
728
+ And transits against the natal chart:
729
+
730
+ ```js
731
+ const rows = await client.query({
732
+ birth: {
733
+ date: "2000-01-01",
734
+ time: "12:00",
735
+ lat: 51.4779,
736
+ lon: 0,
737
+ timezone: 0,
738
+ },
739
+ moment: {
740
+ date: "2026-08-17",
741
+ time: "12:00",
742
+ lat: 51.4779,
743
+ lon: 0,
744
+ timezone: 0,
745
+ },
746
+ sql: "SELECT t.name, t.sign, n.name AS natal FROM transits t JOIN chart n ON t.sign = n.sign LIMIT 50",
747
+ });
748
+ ```
749
+
750
+ A join multiplies rows, so it reaches the hundred sooner than a plain select.
751
+ Both of these overrun it without the `LIMIT`.
752
+
753
+ ### Rendered output
754
+
755
+ Without `format` the answer is rows. `box` and `csv` render it as text, meant
756
+ for a terminal rather than for parsing, and arrive as a string:
757
+
758
+ ```js
759
+ console.log(
760
+ await client.query({
761
+ birth,
762
+ sql: "SELECT name, sign FROM planets LIMIT 3",
763
+ format: "box",
764
+ }),
765
+ );
766
+ // ┌─────────┬───────────┐
767
+ // │ name │ sign │
768
+ // ├─────────┼───────────┤
769
+ // │ Sun │ Capricorn │
770
+ // └─────────┴───────────┘
771
+ ```
772
+
773
+ `border` picks the box style from `sharp`, `round`, `ascii`, `rules` and
774
+ `markdown`.
775
+
776
+ `json` renders too, and the client parses it back, so it reads like any other
777
+ response rather than like a string you have to decode yourself.
778
+
779
+ `scalar` returns the single value a one-row, one-column answer holds, and
780
+ `object` returns a one-row answer as an object, which saves indexing into a
781
+ list of one:
782
+
783
+ ```js
784
+ (
785
+ await client.query({
786
+ birth,
787
+ sql: "SELECT COUNT(*) AS n FROM stars",
788
+ format: "scalar",
789
+ })
790
+ ).data;
791
+ // 953
792
+
793
+ (
794
+ await client.query({
795
+ birth,
796
+ sql: "SELECT name, sign FROM planets LIMIT 1",
797
+ format: "object",
798
+ })
799
+ ).data.sign;
800
+ // "Capricorn"
801
+ ```
802
+
803
+ ## Every endpoint
804
+
805
+ Every published operation, 67 of them, has a method on the client and a
806
+ module-level shortcut, all generated from the schema. They are the Python
807
+ SDK's methods under the same names, written in camelCase: `natal`,
808
+ `transits`, `synastry`, `composite`, `solarReturn`, `progression`,
809
+ `harmonics`, `astrocartography`, `vedicChart`, `zodiacalReleasing`,
810
+ `firdaria`, `horary`, `electional` and the rest. Python's `render_png` is
811
+ `renderPng` here, and `search_places` is `searchPlaces`.
812
+
813
+ Anything new is reachable before this client names it:
814
+
815
+ ```js
816
+ const result = await client.request("POST", "/v1/harmonics", {
817
+ json: { birth },
818
+ });
819
+ ```
820
+
821
+ Authentication, timeouts, retries and error handling behave identically there.
822
+
823
+ ## Errors
824
+
825
+ ```js
826
+ import { QuotaExceededError, RateLimitError } from "astromansion";
827
+
828
+ try {
829
+ const chart = await client.natal({
830
+ date: "2000-01-01",
831
+ lat: 51.4779,
832
+ lon: 0,
833
+ });
834
+ } catch (error) {
835
+ if (error instanceof RateLimitError) {
836
+ console.log("wait", error.retryAfter, "seconds");
837
+ } else if (error instanceof QuotaExceededError) {
838
+ console.log("this period's allowance is spent");
839
+ }
840
+ }
841
+ ```
842
+
843
+ | Error | Meaning |
844
+ | -------------------------------- | ---------------------------------------------------------- |
845
+ | `AuthenticationError` | Key missing, malformed or unknown |
846
+ | `PermissionDeniedError` | Valid key, feature not in the plan |
847
+ | `QuotaExceededError` | Allowance for the period is spent |
848
+ | `RateLimitError` | Too many requests just now, and `retryAfter` says how long |
849
+ | `ValidationError` | Request rejected, and `details` names the field |
850
+ | `NotFoundError`, `ConflictError` | Missing resource, conflicting state |
851
+ | `ServerError` | The API failed to answer |
852
+ | `AstroMansionConnectionError` | The request never completed |
853
+
854
+ All descend from `AstroMansionError`. Each carries `statusCode`, `errorCode`,
855
+ `details`, `requestId` and `retryAfter` when the API supplies them.
856
+
857
+ ## Rate limits and quota
858
+
859
+ A rate limit clears on its own after `retryAfter`. A spent quota does not, and
860
+ it needs a new period or a larger plan. They are separate errors for that
861
+ reason.
862
+
863
+ The client retries only failures that carry no result. These are connection
864
+ errors, 429 and 5xx. It retries them twice by default and honours
865
+ `Retry-After`. A refusal you must fix is never retried.
866
+
867
+ ```js
868
+ const client = new AstroMansion({ timeout: 60, maxRetries: 0 });
869
+ ```
870
+
871
+ `timeout` is in seconds, as in the Python SDK. `fetch` cannot time the
872
+ connection apart from the answer, so the timeout covers each whole attempt.
873
+
874
+ ## Documents
875
+
876
+ ```js
877
+ import { writeFile } from "node:fs/promises";
878
+
879
+ const pdf = await client.exportPdf({
880
+ date: "2000-01-01",
881
+ lat: 51.4779,
882
+ lon: 0,
883
+ });
884
+
885
+ await writeFile("chart.pdf", pdf);
886
+ ```
887
+
888
+ Or name a path and let the client write it:
889
+
890
+ ```js
891
+ await client.exportPdf({
892
+ date: "2000-01-01",
893
+ lat: 51.4779,
894
+ lon: 0,
895
+ output: "chart.pdf",
896
+ });
897
+ ```
898
+
899
+ Every endpoint that answers with a document takes `output` the same way:
900
+ `exportPdf`, `exportCsv`, `exportReport`, `renderSvg`, `renderPng`,
901
+ `renderBiwheel`, `renderAstrocartography` and `renderSharecard`, and their
902
+ module-level shortcuts.
903
+
904
+ ```js
905
+ await client.renderSvg({
906
+ date: "2000-01-01",
907
+ lat: 51.4779,
908
+ lon: 0,
909
+ output: "wheel.svg",
910
+ });
911
+ ```
912
+
913
+ Nothing is written to disk unless you name a path, so a call cannot overwrite
914
+ a file you did not choose. Without one you get the bytes and decide yourself.
915
+
916
+ Writing needs a file system, which Node.js, Bun and Deno have. An edge
917
+ runtime and React Native have none. There a call with `output` is refused
918
+ before the request is sent, so no quota is spent. The refusal is a
919
+ `ValidationError` that says "output needs a file system, and this runtime has
920
+ none. Leave output out to get the bytes."
921
+
922
+ ## Security
923
+
924
+ The key travels in the `X-API-Key` header, never in a URL. It is masked in
925
+ `String(client)` and appears in no error or log line the package writes.
926
+ Keep it in the environment or a secret store, not in source control. Rotate it
927
+ from your account page if it leaks.
928
+
929
+ A browser page and a React Native app ship their code to every user, so a key
930
+ inside one is everyone's key. A client built there with a key is refused.
931
+ Call the API from your own server, build a visitor client with
932
+ `requireKey: false` and no key, or pass `dangerouslyAllowBrowser: true` to
933
+ accept that risk. The Python SDK never runs in either place, so it has no
934
+ such guard.
935
+
936
+ ## Staging
937
+
938
+ ```js
939
+ const client = new AstroMansion({ baseUrl: "http://localhost:8000" });
39
940
  ```
40
941
 
41
- A client built with `requireKey: false` and no key reaches the endpoints the
42
- API serves to visitors without an account.
942
+ Also readable from `ASTROMANSION_BASE_URL`.
43
943
 
44
- ## License
944
+ ## Links
45
945
 
46
- MIT
946
+ - [Examples cookbook](https://github.com/mustafayavuzak/astromansion-js/blob/main/EXAMPLES.md)
947
+ - [API reference](https://api.astromansion.com/docs)
948
+ - [Documentation](https://astromansion.com/en/docs)
949
+ - [Python SDK](https://github.com/mustafayavuzak/astromansion-python)