kaabalah 5.2.0 → 5.4.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.
@@ -0,0 +1,1675 @@
1
+ import { __require } from './chunk-WY6NIR2V.mjs';
2
+
3
+ // wasm/build/swisseph.node.wasm?url
4
+ var swisseph_node_default = "./swisseph.node-2K5IHMKE.wasm?url";
5
+
6
+ // wasm/build/swisseph.web.wasm?url
7
+ var swisseph_web_default = "./swisseph.web-2K5IHMKE.wasm?url";
8
+
9
+ // wasm/src/swisseph.ts
10
+ var Planet = /* @__PURE__ */ ((Planet2) => {
11
+ Planet2[Planet2["SUN"] = 0] = "SUN";
12
+ Planet2[Planet2["MOON"] = 1] = "MOON";
13
+ Planet2[Planet2["MERCURY"] = 2] = "MERCURY";
14
+ Planet2[Planet2["VENUS"] = 3] = "VENUS";
15
+ Planet2[Planet2["MARS"] = 4] = "MARS";
16
+ Planet2[Planet2["JUPITER"] = 5] = "JUPITER";
17
+ Planet2[Planet2["SATURN"] = 6] = "SATURN";
18
+ Planet2[Planet2["URANUS"] = 7] = "URANUS";
19
+ Planet2[Planet2["NEPTUNE"] = 8] = "NEPTUNE";
20
+ Planet2[Planet2["PLUTO"] = 9] = "PLUTO";
21
+ Planet2[Planet2["MEAN_NODE"] = 10] = "MEAN_NODE";
22
+ Planet2[Planet2["TRUE_NODE"] = 11] = "TRUE_NODE";
23
+ Planet2[Planet2["LILITH_MEAN"] = 12] = "LILITH_MEAN";
24
+ Planet2[Planet2["LILITH_TRUE"] = 13] = "LILITH_TRUE";
25
+ Planet2[Planet2["CHIRON"] = 15] = "CHIRON";
26
+ return Planet2;
27
+ })(Planet || {});
28
+ var VirtualNodes = /* @__PURE__ */ ((VirtualNodes2) => {
29
+ VirtualNodes2["PARS_FORTUNAE"] = "parsFortunae";
30
+ return VirtualNodes2;
31
+ })(VirtualNodes || {});
32
+ var PLANET_AND_NODE_NAMES = {
33
+ [0 /* SUN */]: "Sun",
34
+ [1 /* MOON */]: "Moon",
35
+ [2 /* MERCURY */]: "Mercury",
36
+ [3 /* VENUS */]: "Venus",
37
+ [4 /* MARS */]: "Mars",
38
+ [5 /* JUPITER */]: "Jupiter",
39
+ [6 /* SATURN */]: "Saturn",
40
+ [7 /* URANUS */]: "Uranus",
41
+ [8 /* NEPTUNE */]: "Neptune",
42
+ [9 /* PLUTO */]: "Pluto",
43
+ [10 /* MEAN_NODE */]: "Mean Node",
44
+ [11 /* TRUE_NODE */]: "True Node",
45
+ [12 /* LILITH_MEAN */]: "Lilith Mean",
46
+ [13 /* LILITH_TRUE */]: "Lilith True",
47
+ [15 /* CHIRON */]: "Chiron",
48
+ ["parsFortunae" /* PARS_FORTUNAE */]: "Wheel of Fortune"
49
+ };
50
+ var HouseSystem = /* @__PURE__ */ ((HouseSystem2) => {
51
+ HouseSystem2["PLACIDUS"] = "P";
52
+ HouseSystem2["KOCH"] = "K";
53
+ HouseSystem2["PORPHYRIUS"] = "O";
54
+ HouseSystem2["REGIOMONTANUS"] = "R";
55
+ HouseSystem2["CAMPANUS"] = "C";
56
+ HouseSystem2["EQUAL"] = "E";
57
+ HouseSystem2["WHOLE_SIGN"] = "W";
58
+ HouseSystem2["MERIDIAN"] = "X";
59
+ HouseSystem2["MORINUS"] = "M";
60
+ HouseSystem2["KRUSINSKI"] = "U";
61
+ HouseSystem2["ALCABITIUS"] = "B";
62
+ return HouseSystem2;
63
+ })(HouseSystem || {});
64
+ var CalcFlag = /* @__PURE__ */ ((CalcFlag2) => {
65
+ CalcFlag2[CalcFlag2["JPL_EPH"] = 1] = "JPL_EPH";
66
+ CalcFlag2[CalcFlag2["SWISS_EPH"] = 2] = "SWISS_EPH";
67
+ CalcFlag2[CalcFlag2["MOSHIER"] = 4] = "MOSHIER";
68
+ CalcFlag2[CalcFlag2["HELIOCENTRIC"] = 8] = "HELIOCENTRIC";
69
+ CalcFlag2[CalcFlag2["TRUE_POS"] = 16] = "TRUE_POS";
70
+ CalcFlag2[CalcFlag2["J2000"] = 32] = "J2000";
71
+ CalcFlag2[CalcFlag2["NONUT"] = 64] = "NONUT";
72
+ CalcFlag2[CalcFlag2["SPEED3"] = 128] = "SPEED3";
73
+ CalcFlag2[CalcFlag2["SPEED"] = 256] = "SPEED";
74
+ CalcFlag2[CalcFlag2["EQUATORIAL"] = 2048] = "EQUATORIAL";
75
+ CalcFlag2[CalcFlag2["TOPOCTR"] = 32768] = "TOPOCTR";
76
+ CalcFlag2[CalcFlag2["SIDEREAL"] = 65536] = "SIDEREAL";
77
+ return CalcFlag2;
78
+ })(CalcFlag || {});
79
+ var SE_AST_OFFSET = 1e4;
80
+ var BODY = {
81
+ MEAN_APOGEE: 12,
82
+ // Lilith mean
83
+ OSC_APOGEE: 13};
84
+ var normalizeAngle = (deg) => (deg % 360 + 360) % 360;
85
+ var SwissEph = class {
86
+ /**
87
+ * Constructor that accepts a pre-initialized Swiss Ephemeris module
88
+ */
89
+ constructor(module) {
90
+ this.swe_julday = null;
91
+ this.swe_calc_ut = null;
92
+ this.swe_houses = null;
93
+ this.swe_house_pos = null;
94
+ this.swe_set_ephe_path = null;
95
+ this.swe_close = null;
96
+ this.swe_set_topo = null;
97
+ this.swe_set_sid_mode = null;
98
+ this.module = module;
99
+ this.swe_julday = this.module.cwrap("swe_julday", "number", [
100
+ "number",
101
+ "number",
102
+ "number",
103
+ "number",
104
+ "number"
105
+ ]);
106
+ this.swe_calc_ut = this.module.cwrap("swe_calc_ut", "number", [
107
+ "number",
108
+ "number",
109
+ "number",
110
+ "number",
111
+ "number"
112
+ ]);
113
+ this.swe_houses = this.module.cwrap("swe_houses", "number", [
114
+ "number",
115
+ "number",
116
+ "number",
117
+ "number",
118
+ "number",
119
+ "number"
120
+ ]);
121
+ this.swe_house_pos = this.module.cwrap(
122
+ "swe_house_pos",
123
+ "number",
124
+ ["number", "number", "number", "string", "number", "number"]
125
+ );
126
+ this.swe_set_ephe_path = this.module.cwrap(
127
+ "swe_set_ephe_path",
128
+ null,
129
+ ["number"]
130
+ );
131
+ this.swe_close = this.module.cwrap("swe_close", null, []);
132
+ this.swe_set_topo = this.module.cwrap("swe_set_topo", null, [
133
+ "number",
134
+ "number",
135
+ "number"
136
+ ]);
137
+ this.swe_set_sid_mode = this.module.cwrap(
138
+ "swe_set_sid_mode",
139
+ null,
140
+ ["number", "number", "number"]
141
+ );
142
+ }
143
+ checkInitialized() {
144
+ if (!this.module) {
145
+ throw new Error("Swiss Ephemeris module not available.");
146
+ }
147
+ }
148
+ /**
149
+ * Sets the path to the ephemeris data files.
150
+ * @param path - The path to the directory containing ephemeris files.
151
+ */
152
+ setEphemerisPath(path) {
153
+ this.checkInitialized();
154
+ if (path && this.swe_set_ephe_path) {
155
+ const pathPtr = this.module._malloc(path.length + 1);
156
+ if (!pathPtr) {
157
+ throw new Error("Failed to allocate memory for ephemeris path");
158
+ }
159
+ this.module.stringToUTF8(path, pathPtr, path.length + 1);
160
+ this.swe_set_ephe_path(pathPtr);
161
+ this.module._free(pathPtr);
162
+ }
163
+ }
164
+ /**
165
+ * Calculate Julian day number for a given date and time
166
+ */
167
+ getJulianDay(date) {
168
+ this.checkInitialized();
169
+ if (!this.swe_julday) {
170
+ throw new Error("Julian day calculation function not available");
171
+ }
172
+ const year = date.getUTCFullYear();
173
+ const month = date.getUTCMonth() + 1;
174
+ const day = date.getUTCDate();
175
+ const hour = date.getUTCHours() + date.getUTCMinutes() / 60 + date.getUTCSeconds() / 3600;
176
+ return this.swe_julday(year, month, day, hour, 1);
177
+ }
178
+ /**
179
+ * Calculate planet position at a given Julian day
180
+ */
181
+ calculatePlanetPosition(julday, planet, flags = 2 /* SWISS_EPH */) {
182
+ this.checkInitialized();
183
+ if (!this.swe_calc_ut || !this.module) {
184
+ throw new Error("Planet calculation function not available");
185
+ }
186
+ const resultPtr = this.module._malloc(6 * 8);
187
+ if (!resultPtr) {
188
+ throw new Error("Failed to allocate memory for planet position");
189
+ }
190
+ const ERR_BYTES = 512;
191
+ const errPtr = this.module._malloc(ERR_BYTES);
192
+ if (!errPtr) {
193
+ this.module._free(resultPtr);
194
+ throw new Error("Failed to allocate memory for error buffer");
195
+ }
196
+ this.module.HEAP8.fill(0, errPtr, errPtr + ERR_BYTES);
197
+ try {
198
+ let ret = this.swe_calc_ut(julday, planet, flags, resultPtr, errPtr);
199
+ if (ret < 0) {
200
+ const msg = this.module.UTF8ToString(errPtr);
201
+ throw new Error(msg && msg.length ? msg : `Swiss Ephemeris calculation failed with error code ${ret}`);
202
+ }
203
+ const position = {
204
+ longitude: this.module.getValue(resultPtr, "double"),
205
+ latitude: this.module.getValue(resultPtr + 8, "double"),
206
+ distance: this.module.getValue(resultPtr + 16, "double")
207
+ };
208
+ if (flags & 256 /* SPEED */) {
209
+ position.longitudeSpeed = this.module.getValue(resultPtr + 24, "double");
210
+ position.latitudeSpeed = this.module.getValue(resultPtr + 32, "double");
211
+ position.distanceSpeed = this.module.getValue(resultPtr + 40, "double");
212
+ }
213
+ return position;
214
+ } finally {
215
+ this.module._free(errPtr);
216
+ this.module._free(resultPtr);
217
+ }
218
+ }
219
+ /**
220
+ * Calculate houses for a given date, location, and house system
221
+ */
222
+ calculateHouses(julday, latitude, longitude, hsys = "P" /* PLACIDUS */) {
223
+ this.checkInitialized();
224
+ if (!this.swe_houses || !this.module) {
225
+ throw new Error("Houses calculation function not available");
226
+ }
227
+ if (latitude < -90 || latitude > 90) {
228
+ throw new Error("Latitude must be between -90 and 90 degrees");
229
+ }
230
+ if (longitude < -180 || longitude > 180) {
231
+ throw new Error("Longitude must be between -180 and 180 degrees");
232
+ }
233
+ const HOUSES_DOUBLES = 13;
234
+ const ASCMC_DOUBLES = 10;
235
+ const BYTES_PER_F64 = 8;
236
+ const totalBytes = (HOUSES_DOUBLES + ASCMC_DOUBLES) * BYTES_PER_F64;
237
+ const memoryPtr = this.module._malloc(totalBytes);
238
+ if (!memoryPtr) throw new Error("Memory allocation failed");
239
+ const housesPtr = memoryPtr;
240
+ const ascmcPtr = memoryPtr + HOUSES_DOUBLES * BYTES_PER_F64;
241
+ try {
242
+ const hsysCode = hsys.charCodeAt(0);
243
+ const ret = this.swe_houses(
244
+ julday,
245
+ latitude,
246
+ longitude,
247
+ hsysCode,
248
+ housesPtr,
249
+ ascmcPtr
250
+ );
251
+ if (ret < 0) {
252
+ throw new Error(`Houses calculation failed with error code ${ret}`);
253
+ }
254
+ const houses = new Array(HOUSES_DOUBLES);
255
+ for (let i = 0; i < HOUSES_DOUBLES; i++) {
256
+ houses[i] = this.module.getValue(
257
+ housesPtr + i * BYTES_PER_F64,
258
+ "double"
259
+ );
260
+ }
261
+ const ascendant = this.module.getValue(
262
+ ascmcPtr + 0 * BYTES_PER_F64,
263
+ "double"
264
+ );
265
+ const mc = this.module.getValue(ascmcPtr + 1 * BYTES_PER_F64, "double");
266
+ const armc = this.module.getValue(ascmcPtr + 2 * BYTES_PER_F64, "double");
267
+ const vertex = this.module.getValue(
268
+ ascmcPtr + 3 * BYTES_PER_F64,
269
+ "double"
270
+ );
271
+ const equasc = this.module.getValue(
272
+ ascmcPtr + 4 * BYTES_PER_F64,
273
+ "double"
274
+ );
275
+ const coasc1 = this.module.getValue(
276
+ ascmcPtr + 5 * BYTES_PER_F64,
277
+ "double"
278
+ );
279
+ const coasc2 = this.module.getValue(
280
+ ascmcPtr + 6 * BYTES_PER_F64,
281
+ "double"
282
+ );
283
+ const polasc = this.module.getValue(
284
+ ascmcPtr + 7 * BYTES_PER_F64,
285
+ "double"
286
+ );
287
+ return {
288
+ ascendant,
289
+ mc,
290
+ houses,
291
+ ascmc: {
292
+ armc,
293
+ vertex,
294
+ equasc,
295
+ coasc1,
296
+ coasc2,
297
+ polasc
298
+ }
299
+ };
300
+ } finally {
301
+ this.module._free(memoryPtr);
302
+ }
303
+ }
304
+ /**
305
+ * Clean up and close the Swiss Ephemeris
306
+ */
307
+ close() {
308
+ this.checkInitialized();
309
+ if (this.swe_close) {
310
+ this.swe_close();
311
+ }
312
+ }
313
+ /**
314
+ * Set topocentric observer
315
+ */
316
+ setTopocentric(longitude, latitude, altitudeMeters = 0) {
317
+ this.checkInitialized();
318
+ if (!this.swe_set_topo) {
319
+ throw new Error("Topocentric calculation function not available");
320
+ }
321
+ this.swe_set_topo(longitude, latitude, altitudeMeters);
322
+ }
323
+ /**
324
+ * Set sidereal mode
325
+ * Ex.: mode=1 (Lahiri). See Swiss Ephemeris mode table.
326
+ */
327
+ setSiderealMode(mode, t0 = 0, ayan_t0 = 0) {
328
+ this.checkInitialized();
329
+ this.swe_set_sid_mode?.(mode, t0, ayan_t0);
330
+ }
331
+ /**
332
+ * Asteroid by MPC number
333
+ */
334
+ calculateAsteroidPosition(julday, mpcNumber, flags = 2 /* SWISS_EPH */) {
335
+ return this.calculatePlanetPosition(
336
+ julday,
337
+ SE_AST_OFFSET + mpcNumber,
338
+ flags
339
+ );
340
+ }
341
+ /**
342
+ * Lilith mean (12) and true (13)
343
+ */
344
+ calculateLilith(julday, kind = "mean", flags = 2 /* SWISS_EPH */) {
345
+ const id = kind === "mean" ? BODY.MEAN_APOGEE : BODY.OSC_APOGEE;
346
+ return this.calculatePlanetPosition(julday, id, flags);
347
+ }
348
+ };
349
+ function parsFortunae(asc, sunLon, moonLon, diurnal) {
350
+ const val = diurnal ? asc + moonLon - sunLon : asc + sunLon - moonLon;
351
+ return normalizeAngle(val);
352
+ }
353
+
354
+ // src/astrology/swisseph.ts
355
+ var swissEph = null;
356
+ var DEFAULT_FLAGS = 2 /* SWISS_EPH */ | 256 /* SPEED */;
357
+ var REQUIRED_EPHE_FILES = ["seas_18.se1", "semo_18.se1", "sepl_18.se1"];
358
+ var NODE_EPHE_MOUNT_POINT = "/ephefs";
359
+ var NODE_EPHE_MEMFS_PATH = "/ephemem";
360
+ function normalizeVirtualPath(path) {
361
+ if (path === "/") {
362
+ return path;
363
+ }
364
+ return path.replace(/\/+$/, "") || "/";
365
+ }
366
+ function joinVirtualPath(rootPath, leaf) {
367
+ const normalizedRoot = normalizeVirtualPath(rootPath);
368
+ return normalizedRoot === "/" ? `/${leaf}` : `${normalizedRoot}/${leaf}`;
369
+ }
370
+ function ensureVirtualDir(fs, path) {
371
+ try {
372
+ fs.mkdir(path);
373
+ } catch {
374
+ }
375
+ }
376
+ function safeAnalyzePath(fs, path) {
377
+ if (!fs.analyzePath) {
378
+ return null;
379
+ }
380
+ try {
381
+ return fs.analyzePath(path).exists === true;
382
+ } catch {
383
+ return false;
384
+ }
385
+ }
386
+ function safeReaddir(fs, path) {
387
+ if (!fs.readdir) {
388
+ return [];
389
+ }
390
+ try {
391
+ return fs.readdir(path).filter((entry) => entry !== "." && entry !== "..");
392
+ } catch {
393
+ return [];
394
+ }
395
+ }
396
+ function inspectVirtualEphemerisPath(fs, rootPath, requiredFiles = REQUIRED_EPHE_FILES) {
397
+ if (!fs) {
398
+ return {
399
+ rootExists: null,
400
+ visibleEntries: [],
401
+ missingFiles: [...requiredFiles]
402
+ };
403
+ }
404
+ const rootExists = safeAnalyzePath(fs, rootPath);
405
+ const visibleEntries = safeReaddir(fs, rootPath);
406
+ const missingFiles = requiredFiles.filter((file) => {
407
+ const filePath = joinVirtualPath(rootPath, file);
408
+ return !visibleEntries.includes(file) && safeAnalyzePath(fs, filePath) !== true;
409
+ });
410
+ return {
411
+ rootExists,
412
+ visibleEntries,
413
+ missingFiles
414
+ };
415
+ }
416
+ function formatVirtualPathCheck(label, path, check) {
417
+ if (!check) {
418
+ return `${label} "${path}" could not be inspected.`;
419
+ }
420
+ const exists = check.rootExists == null ? "unknown" : check.rootExists ? "yes" : "no";
421
+ const visibleEntries = check.visibleEntries.length > 0 ? check.visibleEntries.join(", ") : "(none)";
422
+ const missingFiles = check.missingFiles.length > 0 ? check.missingFiles.join(", ") : "(none)";
423
+ return `${label} "${path}" exists: ${exists}; visible entries: ${visibleEntries}; missing required files: ${missingFiles}.`;
424
+ }
425
+ function normalizeHostFileData(data) {
426
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
427
+ }
428
+ function loadHostEphemerisFiles(ephePath, requiredFiles, nodeFs, pathModule) {
429
+ const files = /* @__PURE__ */ new Map();
430
+ for (const file of requiredFiles) {
431
+ files.set(file, normalizeHostFileData(nodeFs.readFileSync(pathModule.join(ephePath, file))));
432
+ }
433
+ return files;
434
+ }
435
+ function writeEphemerisFilesToMemfs(fs, targetPath, files) {
436
+ ensureVirtualDir(fs, targetPath);
437
+ for (const [fileName, fileData] of files.entries()) {
438
+ fs.writeFile(joinVirtualPath(targetPath, fileName), fileData);
439
+ }
440
+ }
441
+ function toError(err) {
442
+ return err instanceof Error ? err : new Error(String(err));
443
+ }
444
+ function buildEphemerisResolutionError(finalEphePath, requiredFiles, details) {
445
+ const parts = [
446
+ `Unable to resolve Swiss Ephemeris data files. Expected ${requiredFiles.join(", ")} under "${finalEphePath}".`
447
+ ];
448
+ if (details.mountAttempted) {
449
+ parts.push(
450
+ `${formatVirtualPathCheck("Mounted ephemeris path", details.mountPoint, details.mountCheck)} The NODEFS mount may have failed silently.`
451
+ );
452
+ }
453
+ if (details.mountError) {
454
+ parts.push(`Mounting the ephemeris directory failed: ${details.mountError.message}.`);
455
+ }
456
+ parts.push(formatVirtualPathCheck("Direct host ephemeris path", finalEphePath, details.hostCheck));
457
+ if (details.memfsCheck) {
458
+ parts.push(formatVirtualPathCheck("MEMFS ephemeris copy", details.memfsPath, details.memfsCheck));
459
+ }
460
+ if (details.hostReadError) {
461
+ parts.push(`Reading host ephemeris files failed: ${details.hostReadError.message}.`);
462
+ }
463
+ parts.push(
464
+ `Pass an explicit ephePath that contains ${requiredFiles.join(", ")} or ensure the packaged ephemeris directory is readable.`
465
+ );
466
+ return parts.join(" ");
467
+ }
468
+ function resolveNodeEphemerisPath(module, finalEphePath, options = {}) {
469
+ const fs = module.FS;
470
+ const requiredFiles = options.requiredFiles ?? REQUIRED_EPHE_FILES;
471
+ const mountPoint = options.mountPoint ?? NODE_EPHE_MOUNT_POINT;
472
+ const memfsPath = options.memfsPath ?? NODE_EPHE_MEMFS_PATH;
473
+ const nodeFs = options.nodeFs ?? __require("fs");
474
+ const pathModule = options.pathModule ?? __require("path");
475
+ let mountAttempted = false;
476
+ let mountCheck = null;
477
+ let mountError = null;
478
+ let hostCheck = null;
479
+ let memfsCheck = null;
480
+ let hostReadError = null;
481
+ if (fs?.mount && fs.filesystems?.NODEFS) {
482
+ mountAttempted = true;
483
+ ensureVirtualDir(fs, mountPoint);
484
+ try {
485
+ fs.mount(fs.filesystems.NODEFS, { root: finalEphePath }, mountPoint);
486
+ mountCheck = inspectVirtualEphemerisPath(fs, mountPoint, requiredFiles);
487
+ if (mountCheck.missingFiles.length === 0) {
488
+ return { path: mountPoint, strategy: "nodefs-mount" };
489
+ }
490
+ } catch (mountErr) {
491
+ mountError = toError(mountErr);
492
+ }
493
+ }
494
+ hostCheck = inspectVirtualEphemerisPath(fs, finalEphePath, requiredFiles);
495
+ if (fs && hostCheck.missingFiles.length === 0) {
496
+ return { path: finalEphePath, strategy: "host-path" };
497
+ }
498
+ let hostFiles = null;
499
+ try {
500
+ hostFiles = loadHostEphemerisFiles(finalEphePath, requiredFiles, nodeFs, pathModule);
501
+ } catch (err) {
502
+ hostReadError = toError(err);
503
+ }
504
+ if (hostFiles && fs?.writeFile) {
505
+ writeEphemerisFilesToMemfs(fs, memfsPath, hostFiles);
506
+ memfsCheck = inspectVirtualEphemerisPath(fs, memfsPath, requiredFiles);
507
+ if (memfsCheck.missingFiles.length === 0) {
508
+ return { path: memfsPath, strategy: "memfs-copy" };
509
+ }
510
+ }
511
+ if (hostFiles) {
512
+ return { path: finalEphePath, strategy: "host-path" };
513
+ }
514
+ throw new Error(
515
+ buildEphemerisResolutionError(finalEphePath, requiredFiles, {
516
+ mountAttempted,
517
+ mountPoint,
518
+ mountCheck,
519
+ mountError,
520
+ hostCheck,
521
+ memfsPath,
522
+ memfsCheck,
523
+ hostReadError
524
+ })
525
+ );
526
+ }
527
+ async function getSwissEph(options = {}) {
528
+ if (swissEph) {
529
+ return;
530
+ }
531
+ try {
532
+ const isBrowser = typeof window !== "undefined";
533
+ const wasmUrl = isBrowser ? swisseph_web_default : swisseph_node_default;
534
+ const finalWasmPath = options.wasmPath || (isBrowser ? wasmUrl : __require("path").resolve(__dirname, wasmUrl));
535
+ const moduleFactory = isBrowser ? (await import('./swisseph.web-TSFJI7DQ.mjs')).default : (await import('./swisseph.node-6H4ISR7M.mjs')).default;
536
+ const module = await moduleFactory({
537
+ locateFile: () => finalWasmPath
538
+ });
539
+ const instance = new SwissEph(module);
540
+ const defaultEphePath = isBrowser ? "../ephe" : __require("path").resolve(__dirname, "../ephe");
541
+ const finalEphePath = options.ephePath || defaultEphePath;
542
+ if (isBrowser) {
543
+ const epheFsPath = "/ephe";
544
+ try {
545
+ module.FS?.mkdir?.(epheFsPath);
546
+ } catch {
547
+ }
548
+ const files = ["seas_18.se1", "semo_18.se1", "sepl_18.se1"];
549
+ await Promise.all(
550
+ files.map(async (name) => {
551
+ const url = `${finalEphePath}/${name}`;
552
+ const res = await fetch(url);
553
+ if (!res.ok) {
554
+ throw new Error(`Failed to fetch ephemeris file: ${url}`);
555
+ }
556
+ const buf = await res.arrayBuffer();
557
+ module.FS?.writeFile?.(
558
+ `${epheFsPath}/${name}`,
559
+ new Uint8Array(buf)
560
+ );
561
+ })
562
+ );
563
+ const browserCheck = inspectVirtualEphemerisPath(module.FS, epheFsPath, REQUIRED_EPHE_FILES);
564
+ if (browserCheck.missingFiles.length > 0) {
565
+ throw new Error(
566
+ `Failed to materialize browser ephemeris files at "${epheFsPath}". Missing: ${browserCheck.missingFiles.join(", ")}.`
567
+ );
568
+ }
569
+ console.info(`Setting ephemeris path to: ${epheFsPath}`);
570
+ instance.setEphemerisPath(epheFsPath);
571
+ } else {
572
+ const resolution = resolveNodeEphemerisPath(module, finalEphePath);
573
+ if (resolution.strategy === "nodefs-mount") {
574
+ console.info(`Setting ephemeris path to: ${resolution.path} (mounted from ${finalEphePath})`);
575
+ } else if (resolution.strategy === "memfs-copy") {
576
+ console.info(`Setting ephemeris path to: ${resolution.path} (copied from ${finalEphePath})`);
577
+ } else {
578
+ console.info(`Setting ephemeris path to: ${resolution.path}`);
579
+ }
580
+ instance.setEphemerisPath(resolution.path);
581
+ }
582
+ swissEph = instance;
583
+ } catch (error) {
584
+ console.error("Error initializing Swiss Ephemeris:", error);
585
+ throw error;
586
+ }
587
+ }
588
+ function calculateSinglePlanetPosition(date, planet) {
589
+ checkInitialization();
590
+ const julday = swissEph.getJulianDay(date);
591
+ return swissEph.calculatePlanetPosition(julday, planet, DEFAULT_FLAGS);
592
+ }
593
+ async function calculatePlanetaryPositions(date) {
594
+ try {
595
+ checkInitialization();
596
+ const julday = swissEph.getJulianDay(date);
597
+ const flags = DEFAULT_FLAGS;
598
+ const planets = {
599
+ sun: 0 /* SUN */,
600
+ moon: 1 /* MOON */,
601
+ mercury: 2 /* MERCURY */,
602
+ venus: 3 /* VENUS */,
603
+ mars: 4 /* MARS */,
604
+ jupiter: 5 /* JUPITER */,
605
+ saturn: 6 /* SATURN */,
606
+ uranus: 7 /* URANUS */,
607
+ neptune: 8 /* NEPTUNE */,
608
+ pluto: 9 /* PLUTO */,
609
+ meanNode: 10 /* MEAN_NODE */,
610
+ trueNode: 11 /* TRUE_NODE */,
611
+ chiron: 15 /* CHIRON */,
612
+ lilithMean: 12 /* LILITH_MEAN */,
613
+ lilithTrue: 13 /* LILITH_TRUE */
614
+ };
615
+ const positions = {};
616
+ for (const id of Object.values(planets)) {
617
+ try {
618
+ positions[id] = swissEph.calculatePlanetPosition(julday, id, flags);
619
+ } catch (error) {
620
+ throw new Error(
621
+ `Failed to calculate position for ${PLANET_AND_NODE_NAMES[id]}: ${error}`
622
+ );
623
+ }
624
+ }
625
+ return positions;
626
+ } catch (error) {
627
+ console.error("Error calculating planetary positions:", error);
628
+ throw error;
629
+ }
630
+ }
631
+ async function calculateHouses(date, latitude, longitude, houseSystem, options = {}) {
632
+ try {
633
+ checkInitialization();
634
+ const dateForUt = options.treatAsUTC === true ? date instanceof Date ? date : createUtcDateFromParts(buildLocalParts(date)) : await localToUtcDate(date, latitude, longitude, options);
635
+ const julday = swissEph.getJulianDay(dateForUt);
636
+ return swissEph.calculateHouses(
637
+ julday,
638
+ latitude,
639
+ longitude,
640
+ houseSystem
641
+ );
642
+ } catch (error) {
643
+ console.error("Error calculating houses:", error);
644
+ throw error;
645
+ }
646
+ }
647
+ function calcParsFortunae(asc, sunLon, moonLon, isDiurnal) {
648
+ return parsFortunae(asc, sunLon, moonLon, isDiurnal);
649
+ }
650
+ function closeSwissEph() {
651
+ if (swissEph) {
652
+ try {
653
+ swissEph.close();
654
+ swissEph = null;
655
+ } catch (error) {
656
+ console.error("Error closing Swiss Ephemeris:", error);
657
+ throw error;
658
+ }
659
+ }
660
+ }
661
+ function checkInitialization() {
662
+ if (!swissEph) {
663
+ throw new Error(
664
+ "Swiss Ephemeris not initialized. Call getSwissEph() first."
665
+ );
666
+ }
667
+ }
668
+ function buildLocalParts(date) {
669
+ if (date instanceof Date) {
670
+ return {
671
+ year: date.getFullYear(),
672
+ month: date.getMonth() + 1,
673
+ day: date.getDate(),
674
+ hour: date.getHours(),
675
+ minute: date.getMinutes(),
676
+ second: date.getSeconds()
677
+ };
678
+ }
679
+ return date;
680
+ }
681
+ function createUtcDateFromParts(parts) {
682
+ const { year, month, day, hour = 0, minute = 0, second = 0 } = parts;
683
+ return new Date(Date.UTC(year, month - 1, day, hour, minute, second));
684
+ }
685
+ function getTimeZoneOffsetMs(instant, timeZone) {
686
+ const dtf = new Intl.DateTimeFormat("en-US", {
687
+ timeZone,
688
+ year: "numeric",
689
+ month: "2-digit",
690
+ day: "2-digit",
691
+ hour: "2-digit",
692
+ minute: "2-digit",
693
+ second: "2-digit",
694
+ hour12: false
695
+ });
696
+ const parts = dtf.formatToParts(instant);
697
+ const map = {};
698
+ for (const p of parts) {
699
+ map[p.type] = p.value;
700
+ }
701
+ const asUTC = Date.UTC(
702
+ Number(map.year),
703
+ Number(map.month) - 1,
704
+ Number(map.day),
705
+ Number(map.hour),
706
+ Number(map.minute),
707
+ Number(map.second)
708
+ );
709
+ return asUTC - instant.getTime();
710
+ }
711
+ async function localToUtcDate(local, latitude, longitude, opts = {}) {
712
+ if (opts.treatAsUTC === true) {
713
+ return local instanceof Date ? local : createUtcDateFromParts(buildLocalParts(local));
714
+ }
715
+ const parts = buildLocalParts(local);
716
+ const auto = opts.autoTimeZone !== false;
717
+ if (typeof opts.utcOffsetMinutes === "number" && Number.isFinite(opts.utcOffsetMinutes)) {
718
+ const utcMs = Date.UTC(
719
+ parts.year,
720
+ parts.month - 1,
721
+ parts.day,
722
+ parts.hour ?? 0,
723
+ parts.minute ?? 0,
724
+ parts.second ?? 0
725
+ );
726
+ return new Date(utcMs - opts.utcOffsetMinutes * 6e4);
727
+ }
728
+ if (opts.timeZone) {
729
+ const naiveUtc = createUtcDateFromParts(parts);
730
+ const offsetMs = getTimeZoneOffsetMs(naiveUtc, opts.timeZone);
731
+ return new Date(naiveUtc.getTime() - offsetMs);
732
+ }
733
+ if (opts.resolveTimeZone && typeof latitude === "number" && typeof longitude === "number") {
734
+ const tz = opts.resolveTimeZone(latitude, longitude, parts);
735
+ if (tz) {
736
+ const naiveUtc = createUtcDateFromParts(parts);
737
+ const offsetMs = getTimeZoneOffsetMs(naiveUtc, tz);
738
+ return new Date(naiveUtc.getTime() - offsetMs);
739
+ }
740
+ }
741
+ if (auto && typeof latitude === "number" && typeof longitude === "number") {
742
+ const mod = await import('tz-lookup');
743
+ const lookup = mod.default ?? mod;
744
+ const tz = lookup(latitude, longitude);
745
+ if (tz) {
746
+ const naiveUtc = createUtcDateFromParts(parts);
747
+ const offsetMs = getTimeZoneOffsetMs(naiveUtc, tz);
748
+ return new Date(naiveUtc.getTime() - offsetMs);
749
+ }
750
+ }
751
+ throw new Error(
752
+ "Time zone information is required. Provide 'utcOffsetMinutes', 'timeZone', 'resolveTimeZone', or enable autoTimeZone with latitude/longitude."
753
+ );
754
+ }
755
+ async function toUtcDate(local, latitude, longitude, options = {}) {
756
+ return localToUtcDate(local, latitude, longitude, options);
757
+ }
758
+
759
+ // src/astrology/aspects.ts
760
+ var DEFAULT_ASPECT_SPECS = [
761
+ { name: "conjunction", angle: 0, orb: 8 },
762
+ { name: "duodecile", angle: 30, orb: 2 },
763
+ { name: "octile", angle: 45, orb: 3 },
764
+ { name: "sextile", angle: 60, orb: 5 },
765
+ { name: "square", angle: 90, orb: 6 },
766
+ { name: "trine", angle: 120, orb: 7 },
767
+ { name: "trioctile", angle: 135, orb: 3 },
768
+ { name: "quincunx", angle: 150, orb: 3 },
769
+ { name: "opposition", angle: 180, orb: 8 }
770
+ ];
771
+ function getAspectMatch(lonA, lonB, specs = DEFAULT_ASPECT_SPECS) {
772
+ const a = normalizeAngle(lonA);
773
+ const b = normalizeAngle(lonB);
774
+ const delta = Math.min(
775
+ normalizeAngle(b - a),
776
+ normalizeAngle(a - b)
777
+ );
778
+ for (const spec of specs) {
779
+ const orb = Math.abs(delta - spec.angle);
780
+ if (orb <= spec.orb) {
781
+ return { spec, orb, delta };
782
+ }
783
+ }
784
+ return null;
785
+ }
786
+ function computeAspects(planets, specs = DEFAULT_ASPECT_SPECS) {
787
+ const keys = Object.keys(planets);
788
+ const edges = [];
789
+ for (let i = 0; i < keys.length; i++) {
790
+ for (let j = i + 1; j < keys.length; j++) {
791
+ const a = planets[keys[i]];
792
+ const b = planets[keys[j]];
793
+ const match = getAspectMatch(a.longitude, b.longitude, specs);
794
+ if (match) {
795
+ edges.push({
796
+ planetA: keys[i],
797
+ planetB: keys[j],
798
+ longitudeA: a.longitude,
799
+ longitudeB: b.longitude,
800
+ aspect: match.spec.name,
801
+ aspectAngle: match.spec.angle,
802
+ delta: match.delta,
803
+ orb: match.orb
804
+ });
805
+ }
806
+ }
807
+ }
808
+ return edges;
809
+ }
810
+ function computeSynastryAspects(planetsA, planetsB, specs = DEFAULT_ASPECT_SPECS) {
811
+ const keysA = Object.keys(planetsA);
812
+ const keysB = Object.keys(planetsB);
813
+ const edges = [];
814
+ for (const kA of keysA) {
815
+ for (const kB of keysB) {
816
+ const a = planetsA[kA];
817
+ const b = planetsB[kB];
818
+ const match = getAspectMatch(a.longitude, b.longitude, specs);
819
+ if (match) {
820
+ edges.push({
821
+ planetA: kA,
822
+ planetB: kB,
823
+ longitudeA: a.longitude,
824
+ longitudeB: b.longitude,
825
+ aspect: match.spec.name,
826
+ aspectAngle: match.spec.angle,
827
+ delta: match.delta,
828
+ orb: match.orb
829
+ });
830
+ }
831
+ }
832
+ }
833
+ return edges;
834
+ }
835
+ function shorterArcMidpoint(a, b) {
836
+ let diff = b - a;
837
+ if (diff > 180) diff -= 360;
838
+ if (diff < -180) diff += 360;
839
+ return normalizeAngle(a + diff / 2);
840
+ }
841
+ function computeMidpoints(planetsA, planetsB) {
842
+ const result = {};
843
+ for (const key of Object.keys(planetsA)) {
844
+ if (!(key in planetsB)) continue;
845
+ result[key] = shorterArcMidpoint(planetsA[key].longitude, planetsB[key].longitude);
846
+ }
847
+ return result;
848
+ }
849
+ var SLOW_PLANETS = /* @__PURE__ */ new Set([
850
+ "pluto",
851
+ "neptune",
852
+ "uranus",
853
+ "saturn",
854
+ "jupiter",
855
+ "chiron",
856
+ "mean node",
857
+ "true node",
858
+ "lilith true",
859
+ "lilith mean"
860
+ ]);
861
+ function computeTransitAspects(transitPlanets, natalPlanets, specs = DEFAULT_ASPECT_SPECS) {
862
+ const keysT = Object.keys(transitPlanets);
863
+ const keysN = Object.keys(natalPlanets);
864
+ const edges = [];
865
+ for (const kT of keysT) {
866
+ const t = transitPlanets[kT];
867
+ for (const kN of keysN) {
868
+ const n = natalPlanets[kN];
869
+ const match = getAspectMatch(t.longitude, n.longitude, specs);
870
+ if (!match) continue;
871
+ const tSpeed = t.longitudeSpeed ?? 0;
872
+ const nSpeed = n.longitudeSpeed ?? 0;
873
+ const dt = 0.01;
874
+ const tLonFuture = t.longitude + tSpeed * dt;
875
+ const nLonFuture = n.longitude + nSpeed * dt;
876
+ const futureMatch = getAspectMatch(tLonFuture, nLonFuture, [match.spec]);
877
+ const applying = futureMatch != null ? futureMatch.orb < match.orb : false;
878
+ edges.push({
879
+ planetA: kT,
880
+ planetB: kN,
881
+ longitudeA: t.longitude,
882
+ longitudeB: n.longitude,
883
+ aspect: match.spec.name,
884
+ aspectAngle: match.spec.angle,
885
+ delta: match.delta,
886
+ orb: match.orb,
887
+ applying,
888
+ retrograde: tSpeed < 0,
889
+ category: SLOW_PLANETS.has(kT) ? "slow" : "fast"
890
+ });
891
+ }
892
+ }
893
+ return edges;
894
+ }
895
+
896
+ // src/astrology/dignity.ts
897
+ var DOMICILE_RULERS = {
898
+ Aries: "Mars",
899
+ Taurus: "Venus",
900
+ Gemini: "Mercury",
901
+ Cancer: "Moon",
902
+ Leo: "Sun",
903
+ Virgo: "Mercury",
904
+ Libra: "Venus",
905
+ Scorpio: "Mars",
906
+ Sagittarius: "Jupiter",
907
+ Capricorn: "Saturn",
908
+ Aquarius: "Saturn",
909
+ Pisces: "Jupiter"
910
+ };
911
+ var EXALTATIONS = {
912
+ Sun: { sign: "Aries", degree: 19 },
913
+ Moon: { sign: "Taurus", degree: 3 },
914
+ Mercury: { sign: "Virgo", degree: 15 },
915
+ Venus: { sign: "Pisces", degree: 27 },
916
+ Mars: { sign: "Capricorn", degree: 28 },
917
+ Jupiter: { sign: "Cancer", degree: 15 },
918
+ Saturn: { sign: "Libra", degree: 21 }
919
+ };
920
+ function getDomicileRuler(sign) {
921
+ return DOMICILE_RULERS[sign];
922
+ }
923
+ function getExaltation(planet) {
924
+ return EXALTATIONS[planet];
925
+ }
926
+ function getOppositeSign(sign) {
927
+ const idx = SIGNS.indexOf(sign);
928
+ return SIGNS[(idx + 6) % 12];
929
+ }
930
+ function getDetriment(planet) {
931
+ const signs = [];
932
+ for (const [sign, ruler] of Object.entries(DOMICILE_RULERS)) {
933
+ if (ruler === planet) {
934
+ signs.push(getOppositeSign(sign));
935
+ }
936
+ }
937
+ return signs;
938
+ }
939
+ function getFall(planet) {
940
+ return getOppositeSign(EXALTATIONS[planet].sign);
941
+ }
942
+ function getEssentialDignity(planet, sign) {
943
+ const domicile = DOMICILE_RULERS[sign] === planet;
944
+ const exaltation = EXALTATIONS[planet].sign === sign;
945
+ const detrimentSigns = getDetriment(planet);
946
+ const detriment = detrimentSigns.includes(sign);
947
+ const fallSign = getFall(planet);
948
+ const fall = fallSign === sign;
949
+ const domicileRuler = DOMICILE_RULERS[sign];
950
+ const peregrine = !domicile && !exaltation && !detriment && !fall;
951
+ return { domicile, exaltation, detriment, fall, domicileRuler, peregrine };
952
+ }
953
+
954
+ // src/astrology/decans.ts
955
+ var CHALDEAN_RULERS = [
956
+ "Mars",
957
+ "Sun",
958
+ "Venus",
959
+ "Mercury",
960
+ "Moon",
961
+ "Saturn",
962
+ "Jupiter"
963
+ ];
964
+ var SIGN_SUITS = {
965
+ Aries: "Wands",
966
+ Taurus: "Pentacles",
967
+ Gemini: "Swords",
968
+ Cancer: "Cups",
969
+ Leo: "Wands",
970
+ Virgo: "Pentacles",
971
+ Libra: "Swords",
972
+ Scorpio: "Cups",
973
+ Sagittarius: "Wands",
974
+ Capricorn: "Pentacles",
975
+ Aquarius: "Swords",
976
+ Pisces: "Cups"
977
+ };
978
+ var RANK_NAMES = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"];
979
+ function getDecan(longitude) {
980
+ const L = normalizeAngle(longitude);
981
+ const signIndex = Math.floor(L / 30) % 12;
982
+ const degreeWithinSign = L - signIndex * 30;
983
+ const decanIndex = Math.min(Math.floor(degreeWithinSign / 10), 2);
984
+ const globalDecanIndex = signIndex * 3 + decanIndex;
985
+ const sign = SIGNS[signIndex];
986
+ const ruler = CHALDEAN_RULERS[globalDecanIndex % 7];
987
+ const suit = SIGN_SUITS[sign];
988
+ const rank = RANK_NAMES[globalDecanIndex % 9];
989
+ const tarotCard = `${rank} of ${suit}`;
990
+ return {
991
+ sign,
992
+ decanNumber: decanIndex + 1,
993
+ ruler,
994
+ tarotCard,
995
+ startDegree: signIndex * 30 + decanIndex * 10,
996
+ endDegree: signIndex * 30 + (decanIndex + 1) * 10,
997
+ degreeWithinSign
998
+ };
999
+ }
1000
+
1001
+ // src/astrology/dodecatemoria.ts
1002
+ function getDodecatemoria(longitude) {
1003
+ const L = normalizeAngle(longitude);
1004
+ const signIndex = Math.floor(L / 30) % 12;
1005
+ const degreeWithinSign = L - signIndex * 30;
1006
+ const index = Math.min(Math.floor(degreeWithinSign / 2.5), 11);
1007
+ const dodecatemoriaSignIndex = (signIndex + index) % 12;
1008
+ return {
1009
+ originalSign: SIGNS[signIndex],
1010
+ originalDegree: degreeWithinSign,
1011
+ dodecatemoriaSign: SIGNS[dodecatemoriaSignIndex],
1012
+ dodecatemoriaIndex: index
1013
+ };
1014
+ }
1015
+
1016
+ // src/astrology/profections.ts
1017
+ function getAnnualProfection(natalChart, birthDate, targetYear) {
1018
+ const year = targetYear ?? (/* @__PURE__ */ new Date()).getFullYear();
1019
+ const birthYear = birthDate.getFullYear();
1020
+ const age = year - birthYear;
1021
+ if (age < 0) {
1022
+ throw new Error(`Target year (${year}) is before birth year (${birthYear}).`);
1023
+ }
1024
+ const house = age % 12 + 1;
1025
+ const sign = natalChart.houses.houses[house - 1].sign;
1026
+ const ruler = getDomicileRuler(sign);
1027
+ return { age, house, sign, ruler, targetYear: year };
1028
+ }
1029
+ function getMonthlyProfections(natalChart, birthDate, targetYear) {
1030
+ const annualProfection = getAnnualProfection(natalChart, birthDate, targetYear);
1031
+ const annualSignIndex = SIGNS.indexOf(annualProfection.sign);
1032
+ const bdMonth = birthDate.getMonth();
1033
+ const bdDay = birthDate.getDate();
1034
+ const year = annualProfection.targetYear;
1035
+ const months = [];
1036
+ for (let i = 0; i < 12; i++) {
1037
+ const monthDate = new Date(year, bdMonth + i, bdDay);
1038
+ if (monthDate.getDate() !== bdDay) {
1039
+ monthDate.setDate(0);
1040
+ }
1041
+ const signIndex = (annualSignIndex + i) % 12;
1042
+ const sign = SIGNS[signIndex];
1043
+ months.push({
1044
+ month: i + 1,
1045
+ startDate: monthDate,
1046
+ sign,
1047
+ ruler: getDomicileRuler(sign)
1048
+ });
1049
+ }
1050
+ return { annualProfection, months };
1051
+ }
1052
+
1053
+ // src/astrology/firdaria.ts
1054
+ var DAY_SEQUENCE = [
1055
+ { planet: "Sun", years: 10 },
1056
+ { planet: "Venus", years: 8 },
1057
+ { planet: "Mercury", years: 13 },
1058
+ { planet: "Moon", years: 9 },
1059
+ { planet: "Saturn", years: 11 },
1060
+ { planet: "Jupiter", years: 12 },
1061
+ { planet: "Mars", years: 7 },
1062
+ { planet: "NorthNode", years: 3 },
1063
+ { planet: "SouthNode", years: 2 }
1064
+ ];
1065
+ var NIGHT_SEQUENCE = [
1066
+ { planet: "Moon", years: 9 },
1067
+ { planet: "Saturn", years: 11 },
1068
+ { planet: "Jupiter", years: 12 },
1069
+ { planet: "Mars", years: 7 },
1070
+ { planet: "NorthNode", years: 3 },
1071
+ { planet: "SouthNode", years: 2 },
1072
+ { planet: "Sun", years: 10 },
1073
+ { planet: "Venus", years: 8 },
1074
+ { planet: "Mercury", years: 13 }
1075
+ ];
1076
+ var CHALDEAN_ORDER = [
1077
+ "Saturn",
1078
+ "Jupiter",
1079
+ "Mars",
1080
+ "Sun",
1081
+ "Venus",
1082
+ "Mercury",
1083
+ "Moon"
1084
+ ];
1085
+ function addYears(date, years) {
1086
+ const ms = years * 365.25 * 24 * 60 * 60 * 1e3;
1087
+ return new Date(date.getTime() + ms);
1088
+ }
1089
+ function getSubPeriodStart(planet, options) {
1090
+ const mode = options?.nodeSubPeriodStart ?? "jupiter-saturn";
1091
+ if (planet === "NorthNode") {
1092
+ if (mode === "sun-mars") {
1093
+ return CHALDEAN_ORDER.indexOf("Sun");
1094
+ }
1095
+ return CHALDEAN_ORDER.indexOf("Jupiter");
1096
+ }
1097
+ if (planet === "SouthNode") {
1098
+ if (mode === "sun-mars") {
1099
+ return CHALDEAN_ORDER.indexOf("Mars");
1100
+ }
1101
+ return CHALDEAN_ORDER.indexOf("Saturn");
1102
+ }
1103
+ return CHALDEAN_ORDER.indexOf(planet);
1104
+ }
1105
+ function buildSubPeriods(major, majorStart, majorEnd, options) {
1106
+ const startIdx = getSubPeriodStart(major.planet, options);
1107
+ const totalMs = majorEnd.getTime() - majorStart.getTime();
1108
+ const subMs = totalMs / 7;
1109
+ const subs = [];
1110
+ for (let i = 0; i < 7; i++) {
1111
+ const subPlanet = CHALDEAN_ORDER[(startIdx + i) % 7];
1112
+ const subStart = new Date(majorStart.getTime() + i * subMs);
1113
+ const subEnd = new Date(majorStart.getTime() + (i + 1) * subMs);
1114
+ subs.push({ planet: subPlanet, startDate: subStart, endDate: subEnd });
1115
+ }
1116
+ return subs;
1117
+ }
1118
+ function getFirdaria(birthDate, isDiurnal, targetDate, options) {
1119
+ const target = targetDate ?? /* @__PURE__ */ new Date();
1120
+ const sequence = isDiurnal ? DAY_SEQUENCE : NIGHT_SEQUENCE;
1121
+ const sect = isDiurnal ? "diurnal" : "nocturnal";
1122
+ const allPeriods = [];
1123
+ let cursor = new Date(birthDate.getTime());
1124
+ let foundCurrent = false;
1125
+ for (let cycle = 0; cycle < 3 && !foundCurrent; cycle++) {
1126
+ for (const entry of sequence) {
1127
+ const start = new Date(cursor.getTime());
1128
+ const end = addYears(start, entry.years);
1129
+ const subPeriods = buildSubPeriods(entry, start, end, options);
1130
+ allPeriods.push({
1131
+ planet: entry.planet,
1132
+ years: entry.years,
1133
+ startDate: start,
1134
+ endDate: end,
1135
+ subPeriods
1136
+ });
1137
+ cursor = end;
1138
+ if (target.getTime() >= start.getTime() && target.getTime() < end.getTime()) {
1139
+ foundCurrent = true;
1140
+ }
1141
+ }
1142
+ }
1143
+ const currentMajor = allPeriods.find(
1144
+ (p) => target.getTime() >= p.startDate.getTime() && target.getTime() < p.endDate.getTime()
1145
+ ) ?? allPeriods[0];
1146
+ const currentSub = currentMajor.subPeriods.find(
1147
+ (s) => target.getTime() >= s.startDate.getTime() && target.getTime() < s.endDate.getTime()
1148
+ ) ?? currentMajor.subPeriods[0];
1149
+ return { sect, currentMajor, currentSub, allPeriods };
1150
+ }
1151
+
1152
+ // src/astrology/index.ts
1153
+ function validateInputs(options) {
1154
+ if (!(options.date instanceof Date) || isNaN(options.date.getTime())) {
1155
+ throw new Error("Invalid date provided");
1156
+ }
1157
+ if (typeof options.latitude !== "number" || options.latitude < -90 || options.latitude > 90) {
1158
+ throw new Error("Invalid latitude: must be between -90 and 90 degrees");
1159
+ }
1160
+ if (typeof options.longitude !== "number" || options.longitude < -180 || options.longitude > 180) {
1161
+ throw new Error("Invalid longitude: must be between -180 and 180 degrees");
1162
+ }
1163
+ }
1164
+ function hydratePlanet(id, position, houseCusps) {
1165
+ return {
1166
+ ...position,
1167
+ id,
1168
+ name: PLANET_AND_NODE_NAMES[id],
1169
+ zodiacPosition: getZodiacPosition(position.longitude, houseCusps)
1170
+ };
1171
+ }
1172
+ async function getBirthChart(options) {
1173
+ try {
1174
+ validateInputs(options);
1175
+ const tzOptions = options.timeZoneSettings ?? { autoTimeZone: true };
1176
+ const utcDate = await toUtcDate(options.date, options.latitude, options.longitude, tzOptions);
1177
+ const planetPositions = await calculatePlanetaryPositions(utcDate);
1178
+ if (!planetPositions) {
1179
+ throw new Error("Failed to calculate planetary positions");
1180
+ }
1181
+ const housesPositions = await calculateHouses(
1182
+ utcDate,
1183
+ options.latitude,
1184
+ options.longitude,
1185
+ options.houseSystem || "P" /* PLACIDUS */,
1186
+ { treatAsUTC: true }
1187
+ );
1188
+ if (!housesPositions) {
1189
+ throw new Error("Failed to calculate houses");
1190
+ }
1191
+ const houseCusps = housesPositions.houses.slice(1, 13).map(normalizeAngle);
1192
+ const planets = {};
1193
+ for (const [planetId, position] of Object.entries(planetPositions)) {
1194
+ const id = planetId;
1195
+ const hydratedPlanet = hydratePlanet(id, position, houseCusps);
1196
+ planets[hydratedPlanet.name.toLocaleLowerCase()] = hydratedPlanet;
1197
+ }
1198
+ const houseCuspsPositions = houseCusps.map(
1199
+ (lon) => getZodiacPosition(lon, houseCusps)
1200
+ );
1201
+ const descendant = normalizeAngle(housesPositions.ascendant + 180);
1202
+ const imumCoeli = normalizeAngle(housesPositions.mc + 180);
1203
+ const ascendantSign = getZodiacPosition(
1204
+ housesPositions.ascendant,
1205
+ houseCusps
1206
+ );
1207
+ const midheavenSign = getZodiacPosition(housesPositions.mc, houseCusps);
1208
+ const descendantSign = getZodiacPosition(descendant, houseCusps);
1209
+ const imumCoeliSign = getZodiacPosition(imumCoeli, houseCusps);
1210
+ const houses = {
1211
+ ascendant: ascendantSign,
1212
+ mc: midheavenSign,
1213
+ dc: descendantSign,
1214
+ ic: imumCoeliSign,
1215
+ houses: houseCuspsPositions,
1216
+ ascmc: {
1217
+ armc: housesPositions.ascmc ? getZodiacPosition(housesPositions.ascmc.armc, houseCusps) : void 0,
1218
+ vertex: housesPositions.ascmc ? getZodiacPosition(housesPositions.ascmc.vertex, houseCusps) : void 0,
1219
+ equasc: housesPositions.ascmc ? getZodiacPosition(housesPositions.ascmc.equasc, houseCusps) : void 0,
1220
+ coasc1: housesPositions.ascmc ? getZodiacPosition(housesPositions.ascmc.coasc1, houseCusps) : void 0,
1221
+ coasc2: housesPositions.ascmc ? getZodiacPosition(housesPositions.ascmc.coasc2, houseCusps) : void 0,
1222
+ polasc: housesPositions.ascmc ? getZodiacPosition(housesPositions.ascmc.polasc, houseCusps) : void 0
1223
+ }
1224
+ };
1225
+ const isDiurnal = planets.sun.zodiacPosition.house >= 7 && planets.sun.zodiacPosition.house <= 12;
1226
+ const wheelOfFortuneLongitude = calcParsFortunae(
1227
+ houses.ascendant.longitude,
1228
+ planets.sun.longitude,
1229
+ planets.moon.longitude,
1230
+ isDiurnal
1231
+ );
1232
+ const wheelOfFortune = getZodiacPosition(
1233
+ wheelOfFortuneLongitude,
1234
+ houseCusps
1235
+ );
1236
+ const nodes = {
1237
+ ["parsFortunae" /* PARS_FORTUNAE */]: {
1238
+ ...wheelOfFortune,
1239
+ id: "parsFortunae" /* PARS_FORTUNAE */,
1240
+ name: PLANET_AND_NODE_NAMES["parsFortunae" /* PARS_FORTUNAE */]
1241
+ }
1242
+ };
1243
+ const aspects = computeAspects(getAspectPoints(planets, houses.ascendant.longitude, houses.mc.longitude));
1244
+ return {
1245
+ dateUtc: utcDate,
1246
+ planets,
1247
+ houses,
1248
+ nodes,
1249
+ aspects,
1250
+ sect: isDiurnal ? "diurnal" : "nocturnal"
1251
+ };
1252
+ } catch (error) {
1253
+ console.error("Error calculating birth chart:", error);
1254
+ throw error;
1255
+ }
1256
+ }
1257
+ var SIGNS = [
1258
+ "Aries",
1259
+ "Taurus",
1260
+ "Gemini",
1261
+ "Cancer",
1262
+ "Leo",
1263
+ "Virgo",
1264
+ "Libra",
1265
+ "Scorpio",
1266
+ "Sagittarius",
1267
+ "Capricorn",
1268
+ "Aquarius",
1269
+ "Pisces"
1270
+ ];
1271
+ function formatDegreeMinutes(decimalDegrees) {
1272
+ let deg = Math.floor(decimalDegrees);
1273
+ let min = Math.round((decimalDegrees - deg) * 60);
1274
+ if (min === 60) {
1275
+ min = 0;
1276
+ deg += 1;
1277
+ }
1278
+ return `${deg}\xB0${String(min).padStart(2, "0")}'`;
1279
+ }
1280
+ function getZodiacPosition(longitude, houseCusps) {
1281
+ const L = normalizeAngle(longitude);
1282
+ const signIndex = Math.floor(L / 30) % 12;
1283
+ const within = L - signIndex * 30;
1284
+ const house = findHouseOf(L, houseCusps);
1285
+ return {
1286
+ sign: SIGNS[signIndex],
1287
+ decimalDegrees: within,
1288
+ traditionalFormat: formatDegreeMinutes(within),
1289
+ decimal: within.toFixed(2) + "\xB0",
1290
+ longitude: L,
1291
+ house
1292
+ };
1293
+ }
1294
+ function findHouseOf(longitude, housePositions) {
1295
+ const L = normalizeAngle(longitude);
1296
+ if (!housePositions || housePositions.length === 0) {
1297
+ throw new Error("House positions are required");
1298
+ }
1299
+ const H = housePositions.map((c, i) => ({ i: i + 1, L: normalizeAngle(c) })).sort((a, b) => a.L - b.L);
1300
+ for (let k = 0; k < H.length; k++) {
1301
+ const cur = H[k], nxt = H[(k + 1) % H.length];
1302
+ if (nxt.L < cur.L) {
1303
+ if (L >= cur.L || L < nxt.L) return cur.i;
1304
+ } else {
1305
+ if (L >= cur.L && L < nxt.L) return cur.i;
1306
+ }
1307
+ }
1308
+ return 1;
1309
+ }
1310
+ function getAspectPoints(planets, ascLon, mcLon) {
1311
+ return { ...planets, ascendant: { longitude: ascLon }, mc: { longitude: mcLon } };
1312
+ }
1313
+ async function getSynastryChart(options) {
1314
+ const [chartA, chartB] = await Promise.all([
1315
+ getBirthChart(options.chartA),
1316
+ getBirthChart(options.chartB)
1317
+ ]);
1318
+ const aspects = computeSynastryAspects(
1319
+ getAspectPoints(chartA.planets, chartA.houses.ascendant.longitude, chartA.houses.mc.longitude),
1320
+ getAspectPoints(chartB.planets, chartB.houses.ascendant.longitude, chartB.houses.mc.longitude),
1321
+ options.aspectSpecs
1322
+ );
1323
+ return { chartA, chartB, aspects };
1324
+ }
1325
+ async function getCompositeChart(options) {
1326
+ const [chartA, chartB] = await Promise.all([
1327
+ getBirthChart(options.chartA),
1328
+ getBirthChart(options.chartB)
1329
+ ]);
1330
+ const midpointLongitudes = computeMidpoints(chartA.planets, chartB.planets);
1331
+ const cuspsA = chartA.houses.houses.map((h) => h.longitude);
1332
+ const cuspsB = chartB.houses.houses.map((h) => h.longitude);
1333
+ const compositeCusps = cuspsA.map(
1334
+ (a, i) => i < cuspsB.length ? shorterArcMidpoint(a, cuspsB[i]) : a
1335
+ );
1336
+ const compositePlanets = {};
1337
+ for (const [key, lon] of Object.entries(midpointLongitudes)) {
1338
+ compositePlanets[key] = {
1339
+ name: key,
1340
+ longitude: lon,
1341
+ zodiacPosition: getZodiacPosition(lon, compositeCusps)
1342
+ };
1343
+ }
1344
+ const compositeHouses = compositeCusps.map(
1345
+ (lon) => getZodiacPosition(lon, compositeCusps)
1346
+ );
1347
+ const aspects = computeAspects(compositePlanets, options.aspectSpecs);
1348
+ return {
1349
+ chartA,
1350
+ chartB,
1351
+ compositePlanets,
1352
+ compositeHouses,
1353
+ aspects
1354
+ };
1355
+ }
1356
+ function getTransitAspectPoints(planets) {
1357
+ const points = {};
1358
+ for (const [key, p] of Object.entries(planets)) {
1359
+ points[key] = { longitude: p.longitude, longitudeSpeed: p.longitudeSpeed };
1360
+ }
1361
+ return points;
1362
+ }
1363
+ function getNatalAspectPoints(planets, ascLon, mcLon) {
1364
+ const points = {};
1365
+ for (const [key, p] of Object.entries(planets)) {
1366
+ points[key] = { longitude: p.longitude, longitudeSpeed: 0 };
1367
+ }
1368
+ points.ascendant = { longitude: ascLon, longitudeSpeed: 0 };
1369
+ points.mc = { longitude: mcLon, longitudeSpeed: 0 };
1370
+ return points;
1371
+ }
1372
+ function filterByNames(points, names) {
1373
+ if (!names || names.length === 0) return points;
1374
+ const allowed = new Set(names.map((n) => n.toLowerCase()));
1375
+ const result = {};
1376
+ for (const [key, val] of Object.entries(points)) {
1377
+ if (allowed.has(key)) result[key] = val;
1378
+ }
1379
+ return result;
1380
+ }
1381
+ async function getTransitChart(options) {
1382
+ const natalChart = await getBirthChart(options.natal);
1383
+ const transitChart = await getBirthChart({
1384
+ date: options.transitDate,
1385
+ latitude: options.transitLatitude ?? options.natal.latitude,
1386
+ longitude: options.transitLongitude ?? options.natal.longitude,
1387
+ houseSystem: options.natal.houseSystem,
1388
+ timeZoneSettings: options.transitTimeZoneSettings ?? { autoTimeZone: true }
1389
+ });
1390
+ const natalCusps = natalChart.houses.houses.map((h) => h.longitude);
1391
+ const transitPlanets = {};
1392
+ for (const [key, planet] of Object.entries(transitChart.planets)) {
1393
+ const natalZodiac = getZodiacPosition(planet.longitude, natalCusps);
1394
+ transitPlanets[key] = {
1395
+ ...planet,
1396
+ retrograde: (planet.longitudeSpeed ?? 0) < 0,
1397
+ natalHouse: natalZodiac.house,
1398
+ zodiacPosition: {
1399
+ ...planet.zodiacPosition,
1400
+ house: natalZodiac.house
1401
+ }
1402
+ };
1403
+ }
1404
+ let tPoints = getTransitAspectPoints(transitChart.planets);
1405
+ let nPoints = getNatalAspectPoints(
1406
+ natalChart.planets,
1407
+ natalChart.houses.ascendant.longitude,
1408
+ natalChart.houses.mc.longitude
1409
+ );
1410
+ tPoints = filterByNames(tPoints, options.transitPlanets);
1411
+ nPoints = filterByNames(nPoints, options.natalPlanets);
1412
+ let aspects = computeTransitAspects(tPoints, nPoints, options.aspectSpecs);
1413
+ if (options.maxOrb != null) {
1414
+ aspects = aspects.filter((a) => a.orb <= options.maxOrb);
1415
+ }
1416
+ if (options.aspectFilter && options.aspectFilter.length > 0) {
1417
+ const allowed = new Set(options.aspectFilter);
1418
+ aspects = aspects.filter((a) => allowed.has(a.aspect));
1419
+ }
1420
+ return {
1421
+ natalChart,
1422
+ transitDateUtc: transitChart.dateUtc,
1423
+ transitPlanets,
1424
+ aspects
1425
+ };
1426
+ }
1427
+ async function getTransitRange(options) {
1428
+ const natalChart = await getBirthChart(options.natal);
1429
+ natalChart.houses.houses.map((h) => h.longitude);
1430
+ const nPoints = filterByNames(
1431
+ getNatalAspectPoints(
1432
+ natalChart.planets,
1433
+ natalChart.houses.ascendant.longitude,
1434
+ natalChart.houses.mc.longitude
1435
+ ),
1436
+ options.natalPlanets
1437
+ );
1438
+ const natalKeys = Object.keys(nPoints);
1439
+ const rawStep = options.stepDays ?? 1;
1440
+ if (rawStep <= 0) throw new Error("stepDays must be greater than 0");
1441
+ const fromMs = options.from.getTime();
1442
+ const toMs = options.to.getTime();
1443
+ const specs = options.aspectSpecs;
1444
+ const steps = [];
1445
+ const transitLat = options.transitLatitude ?? options.natal.latitude;
1446
+ const transitLon = options.transitLongitude ?? options.natal.longitude;
1447
+ const transitTz = options.transitTimeZoneSettings ?? { autoTimeZone: true };
1448
+ const FAST_PLANET_MAX_STEP = 0.25;
1449
+ let effectiveStepDays = rawStep;
1450
+ const requestedTransitPlanets = options.transitPlanets?.map((n) => n.toLowerCase());
1451
+ const hasFastPlanets = requestedTransitPlanets ? requestedTransitPlanets.some((n) => !SLOW_PLANETS.has(n)) : true;
1452
+ if (hasFastPlanets && effectiveStepDays > FAST_PLANET_MAX_STEP) {
1453
+ effectiveStepDays = FAST_PLANET_MAX_STEP;
1454
+ }
1455
+ const stepMs = effectiveStepDays * 864e5;
1456
+ const scanEndMs = toMs + stepMs;
1457
+ for (let ms = fromMs; ms <= scanEndMs; ms += stepMs) {
1458
+ const date = new Date(ms);
1459
+ const utcDate = await toUtcDate(date, transitLat, transitLon, transitTz ?? { autoTimeZone: true });
1460
+ const positions = await calculatePlanetaryPositions(utcDate);
1461
+ if (!positions) continue;
1462
+ const points = {};
1463
+ for (const [planetId, pos] of Object.entries(positions)) {
1464
+ const id = planetId;
1465
+ const name = PLANET_AND_NODE_NAMES[id].toLowerCase();
1466
+ points[name] = { longitude: pos.longitude, longitudeSpeed: pos.longitudeSpeed };
1467
+ }
1468
+ steps.push({ time: ms, positions: filterByNames(points, options.transitPlanets) });
1469
+ }
1470
+ const perfections = [];
1471
+ const transitKeys = steps.length > 0 ? Object.keys(steps[0].positions) : [];
1472
+ for (const tKey of transitKeys) {
1473
+ for (const nKey of natalKeys) {
1474
+ let prevOrb = null;
1475
+ let prevDecreasing = false;
1476
+ let prevStep = null;
1477
+ for (const step of steps) {
1478
+ const tPos = step.positions[tKey];
1479
+ const nPos = nPoints[nKey];
1480
+ if (!tPos || !nPos) continue;
1481
+ const match = specs ? findClosestAspectOrb(tPos.longitude, nPos.longitude, specs) : findClosestAspectOrb(tPos.longitude, nPos.longitude);
1482
+ if (!match) {
1483
+ prevOrb = null;
1484
+ prevStep = step;
1485
+ continue;
1486
+ }
1487
+ const currentOrb = match.orb;
1488
+ if (prevOrb != null && prevStep) {
1489
+ const wasDecreasing = prevOrb > currentOrb;
1490
+ if (prevDecreasing && !wasDecreasing && currentOrb <= match.spec.orb) {
1491
+ const exactResult = await binarySearchPerfection(
1492
+ tKey,
1493
+ nKey,
1494
+ match.spec,
1495
+ prevStep.time,
1496
+ step.time,
1497
+ nPos,
1498
+ transitLat,
1499
+ transitLon,
1500
+ transitTz
1501
+ );
1502
+ if (exactResult) perfections.push(exactResult);
1503
+ }
1504
+ prevDecreasing = wasDecreasing;
1505
+ } else {
1506
+ prevDecreasing = false;
1507
+ }
1508
+ prevOrb = currentOrb;
1509
+ prevStep = step;
1510
+ }
1511
+ }
1512
+ }
1513
+ let filtered = perfections.filter((p) => {
1514
+ const t = p.exactDate.getTime();
1515
+ return t >= fromMs && t <= toMs;
1516
+ });
1517
+ if (options.maxOrb != null) {
1518
+ filtered = filtered.filter((p) => p.exactOrb <= options.maxOrb);
1519
+ }
1520
+ if (options.aspectFilter && options.aspectFilter.length > 0) {
1521
+ const allowed = new Set(options.aspectFilter);
1522
+ filtered = filtered.filter((p) => allowed.has(p.aspect));
1523
+ }
1524
+ filtered.sort((a, b) => a.exactDate.getTime() - b.exactDate.getTime());
1525
+ return {
1526
+ natalChart,
1527
+ from: options.from,
1528
+ to: options.to,
1529
+ perfections: filtered
1530
+ };
1531
+ }
1532
+ function findClosestAspectOrb(lonA, lonB, specs = DEFAULT_ASPECT_SPECS) {
1533
+ const a = normalizeAngle(lonA);
1534
+ const b = normalizeAngle(lonB);
1535
+ const delta = Math.min(normalizeAngle(b - a), normalizeAngle(a - b));
1536
+ let best = null;
1537
+ for (const spec of specs) {
1538
+ const orb = Math.abs(delta - spec.angle);
1539
+ if (orb <= spec.orb + 2) {
1540
+ if (!best || orb < best.orb) {
1541
+ best = { spec, orb, delta };
1542
+ }
1543
+ }
1544
+ }
1545
+ return best;
1546
+ }
1547
+ function computeOrbForAspect(transitLon, natalLon, aspectAngle) {
1548
+ const delta = Math.min(
1549
+ normalizeAngle(transitLon - natalLon),
1550
+ normalizeAngle(natalLon - transitLon)
1551
+ );
1552
+ return Math.abs(delta - aspectAngle);
1553
+ }
1554
+ var NAME_TO_PLANET = {};
1555
+ for (const [id, name] of Object.entries(PLANET_AND_NODE_NAMES)) {
1556
+ const numId = Number(id);
1557
+ if (!isNaN(numId)) NAME_TO_PLANET[name.toLowerCase()] = numId;
1558
+ }
1559
+ async function getTransitLongitudeAt(ms, transitKey, transitLat, transitLon, transitTz) {
1560
+ const date = new Date(ms);
1561
+ const utc = await toUtcDate(date, transitLat, transitLon, transitTz);
1562
+ const planetId = NAME_TO_PLANET[transitKey];
1563
+ if (planetId != null) {
1564
+ try {
1565
+ return calculateSinglePlanetPosition(utc, planetId);
1566
+ } catch {
1567
+ return null;
1568
+ }
1569
+ }
1570
+ const positions = await calculatePlanetaryPositions(utc);
1571
+ if (!positions) return null;
1572
+ return findPlanetByName(positions, transitKey) ?? null;
1573
+ }
1574
+ async function binarySearchPerfection(transitKey, natalKey, spec, startMs, endMs, natalPoint, transitLat, transitLon, transitTz) {
1575
+ const tz = transitTz ?? { autoTimeZone: true };
1576
+ const maxIterations = 30;
1577
+ let lo = startMs;
1578
+ let hi = endMs;
1579
+ for (let i = 0; i < maxIterations; i++) {
1580
+ if (hi - lo < 6e4) break;
1581
+ const m1 = lo + Math.floor((hi - lo) / 3);
1582
+ const m2 = hi - Math.floor((hi - lo) / 3);
1583
+ const pos1 = await getTransitLongitudeAt(m1, transitKey, transitLat, transitLon, tz);
1584
+ const pos2 = await getTransitLongitudeAt(m2, transitKey, transitLat, transitLon, tz);
1585
+ if (!pos1 || !pos2) break;
1586
+ const orb1 = computeOrbForAspect(pos1.longitude, natalPoint.longitude, spec.angle);
1587
+ const orb2 = computeOrbForAspect(pos2.longitude, natalPoint.longitude, spec.angle);
1588
+ if (orb1 < orb2) {
1589
+ hi = m2;
1590
+ } else {
1591
+ lo = m1;
1592
+ }
1593
+ }
1594
+ const finalMs = Math.floor((lo + hi) / 2);
1595
+ const finalPos = await getTransitLongitudeAt(finalMs, transitKey, transitLat, transitLon, tz);
1596
+ if (!finalPos) return null;
1597
+ const finalOrb = computeOrbForAspect(finalPos.longitude, natalPoint.longitude, spec.angle);
1598
+ if (finalOrb > spec.orb) return null;
1599
+ return {
1600
+ transitPlanet: transitKey,
1601
+ natalPlanet: natalKey,
1602
+ aspect: spec.name,
1603
+ exactDate: new Date(finalMs),
1604
+ exactOrb: finalOrb,
1605
+ retrograde: (finalPos.longitudeSpeed ?? 0) < 0,
1606
+ category: SLOW_PLANETS.has(transitKey) ? "slow" : "fast"
1607
+ };
1608
+ }
1609
+ function findPlanetByName(positions, name) {
1610
+ for (const [planetId, pos] of Object.entries(positions)) {
1611
+ const id = planetId;
1612
+ if (PLANET_AND_NODE_NAMES[id].toLowerCase() === name) return pos;
1613
+ }
1614
+ return void 0;
1615
+ }
1616
+ async function getSunLongitudeAtMs(ms) {
1617
+ const positions = await calculatePlanetaryPositions(new Date(ms));
1618
+ const sun = findPlanetByName(positions, "sun");
1619
+ if (!sun) throw new Error("Failed to compute Sun position");
1620
+ return sun.longitude;
1621
+ }
1622
+ function signedAngularDelta(current, target) {
1623
+ let d = normalizeAngle(current - target);
1624
+ if (d > 180) d -= 360;
1625
+ return d;
1626
+ }
1627
+ async function getSolarReturnChart(options) {
1628
+ const natalChart = await getBirthChart(options.natal);
1629
+ const natalSunLongitude = natalChart.planets.sun.longitude;
1630
+ const natalDate = options.natal.date;
1631
+ const approxReturn = new Date(Date.UTC(
1632
+ options.year,
1633
+ natalDate.getMonth(),
1634
+ natalDate.getDate(),
1635
+ 12,
1636
+ 0,
1637
+ 0
1638
+ ));
1639
+ let lo = approxReturn.getTime() - 2 * 864e5;
1640
+ let hi = approxReturn.getTime() + 2 * 864e5;
1641
+ for (let i = 0; i < 30; i++) {
1642
+ if (hi - lo < 6e4) break;
1643
+ const mid = Math.floor((lo + hi) / 2);
1644
+ const sunLon = await getSunLongitudeAtMs(mid);
1645
+ const delta = signedAngularDelta(sunLon, natalSunLongitude);
1646
+ if (delta < 0) {
1647
+ lo = mid;
1648
+ } else {
1649
+ hi = mid;
1650
+ }
1651
+ }
1652
+ const exactMs = Math.floor((lo + hi) / 2);
1653
+ const exactReturnDate = new Date(exactMs);
1654
+ const solarReturnChart = await getBirthChart({
1655
+ date: exactReturnDate,
1656
+ latitude: options.solarReturnLatitude ?? options.natal.latitude,
1657
+ longitude: options.solarReturnLongitude ?? options.natal.longitude,
1658
+ houseSystem: options.solarReturnHouseSystem ?? options.natal.houseSystem,
1659
+ // Always treatAsUTC: the binary search converged on a UTC millisecond timestamp.
1660
+ // Passing a caller timezone here would re-interpret the already-UTC instant as local,
1661
+ // shifting planetary positions by hours.
1662
+ timeZoneSettings: { treatAsUTC: true }
1663
+ });
1664
+ return {
1665
+ natalChart,
1666
+ solarReturnChart,
1667
+ exactReturnDate,
1668
+ natalSunLongitude,
1669
+ year: options.year
1670
+ };
1671
+ }
1672
+
1673
+ export { CalcFlag, DEFAULT_ASPECT_SPECS, DOMICILE_RULERS, EXALTATIONS, HouseSystem, PLANET_AND_NODE_NAMES, Planet, SIGNS, SLOW_PLANETS, VirtualNodes, closeSwissEph, computeAspects, computeMidpoints, computeSynastryAspects, computeTransitAspects, findHouseOf, formatDegreeMinutes, getAnnualProfection, getAspectMatch, getBirthChart, getCompositeChart, getDecan, getDetriment, getDodecatemoria, getDomicileRuler, getEssentialDignity, getExaltation, getFall, getFirdaria, getMonthlyProfections, getOppositeSign, getSolarReturnChart, getSwissEph, getSynastryChart, getTransitChart, getTransitRange, getZodiacPosition, normalizeAngle, shorterArcMidpoint };
1674
+ //# sourceMappingURL=chunk-EBLM443L.mjs.map
1675
+ //# sourceMappingURL=chunk-EBLM443L.mjs.map