@mailwoman/core 8.6.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/README.md +2 -2
  2. package/api/clock.ts +1 -1
  3. package/api/disk-storage.ts +7 -4
  4. package/api/test-clocks.ts +57 -9
  5. package/api/test-transport.ts +182 -0
  6. package/coarse-placer/coarse-placer.ts +2 -1
  7. package/coarse-placer/tools/build-dataset.ts +2 -2
  8. package/coarse-placer/tools/build-outlier-exposure.ts +2 -2
  9. package/coarse-placer/tools/build-outlier-latin.ts +3 -2
  10. package/coarse-placer/tools/build-outlier-oa.ts +3 -2
  11. package/coarse-placer/tools/eval-latin-offmap.ts +8 -8
  12. package/coarse-placer/tools/eval-openset.ts +20 -12
  13. package/coarse-placer/tools/eval-quant-compare.ts +8 -9
  14. package/coarse-placer/tools/eval.ts +30 -23
  15. package/coarse-placer/tools/probe-frontier.ts +9 -7
  16. package/coarse-placer/tools/quantize.ts +4 -2
  17. package/coarse-placer/tools/train.ts +10 -10
  18. package/collections.ts +2 -128
  19. package/crypto/node.ts +68 -0
  20. package/decoder/build-tree.ts +19 -0
  21. package/env/schema.ts +58 -2
  22. package/fs/zip.ts +297 -0
  23. package/identifiers.ts +48 -0
  24. package/layers/manifest.ts +2 -1
  25. package/locale/profiles/en-us.ts +2 -3
  26. package/locale/profiles/fr-fr.ts +1 -1
  27. package/locale/profiles/ja-jp.ts +7 -7
  28. package/objects.ts +40 -8
  29. package/out/api/clock.d.ts +1 -1
  30. package/out/api/clock.js +1 -1
  31. package/out/api/disk-storage.d.ts +1 -1
  32. package/out/api/disk-storage.d.ts.map +1 -1
  33. package/out/api/disk-storage.js +5 -5
  34. package/out/api/disk-storage.js.map +1 -1
  35. package/out/api/test-clocks.d.ts +2 -2
  36. package/out/api/test-clocks.d.ts.map +1 -1
  37. package/out/api/test-clocks.js +51 -9
  38. package/out/api/test-clocks.js.map +1 -1
  39. package/out/api/test-transport.d.ts +112 -0
  40. package/out/api/test-transport.d.ts.map +1 -0
  41. package/out/api/test-transport.js +84 -0
  42. package/out/api/test-transport.js.map +1 -0
  43. package/out/coarse-placer/coarse-placer.d.ts.map +1 -1
  44. package/out/coarse-placer/coarse-placer.js +2 -1
  45. package/out/coarse-placer/coarse-placer.js.map +1 -1
  46. package/out/coarse-placer/tools/build-dataset.js +1 -2
  47. package/out/coarse-placer/tools/build-dataset.js.map +1 -1
  48. package/out/coarse-placer/tools/build-outlier-exposure.js +1 -2
  49. package/out/coarse-placer/tools/build-outlier-exposure.js.map +1 -1
  50. package/out/coarse-placer/tools/build-outlier-latin.d.ts.map +1 -1
  51. package/out/coarse-placer/tools/build-outlier-latin.js +2 -2
  52. package/out/coarse-placer/tools/build-outlier-latin.js.map +1 -1
  53. package/out/coarse-placer/tools/build-outlier-oa.d.ts.map +1 -1
  54. package/out/coarse-placer/tools/build-outlier-oa.js +2 -2
  55. package/out/coarse-placer/tools/build-outlier-oa.js.map +1 -1
  56. package/out/coarse-placer/tools/eval-latin-offmap.d.ts.map +1 -1
  57. package/out/coarse-placer/tools/eval-latin-offmap.js +5 -8
  58. package/out/coarse-placer/tools/eval-latin-offmap.js.map +1 -1
  59. package/out/coarse-placer/tools/eval-openset.d.ts.map +1 -1
  60. package/out/coarse-placer/tools/eval-openset.js +12 -11
  61. package/out/coarse-placer/tools/eval-openset.js.map +1 -1
  62. package/out/coarse-placer/tools/eval-quant-compare.d.ts.map +1 -1
  63. package/out/coarse-placer/tools/eval-quant-compare.js +7 -9
  64. package/out/coarse-placer/tools/eval-quant-compare.js.map +1 -1
  65. package/out/coarse-placer/tools/eval.d.ts.map +1 -1
  66. package/out/coarse-placer/tools/eval.js +20 -21
  67. package/out/coarse-placer/tools/eval.js.map +1 -1
  68. package/out/coarse-placer/tools/probe-frontier.d.ts.map +1 -1
  69. package/out/coarse-placer/tools/probe-frontier.js +8 -8
  70. package/out/coarse-placer/tools/probe-frontier.js.map +1 -1
  71. package/out/coarse-placer/tools/quantize.d.ts.map +1 -1
  72. package/out/coarse-placer/tools/quantize.js +3 -2
  73. package/out/coarse-placer/tools/quantize.js.map +1 -1
  74. package/out/coarse-placer/tools/train.d.ts.map +1 -1
  75. package/out/coarse-placer/tools/train.js +7 -10
  76. package/out/coarse-placer/tools/train.js.map +1 -1
  77. package/out/collections.d.ts +1 -59
  78. package/out/collections.d.ts.map +1 -1
  79. package/out/collections.js +2 -90
  80. package/out/collections.js.map +1 -1
  81. package/out/crypto/node.d.ts +43 -0
  82. package/out/crypto/node.d.ts.map +1 -0
  83. package/out/crypto/node.js +43 -0
  84. package/out/crypto/node.js.map +1 -0
  85. package/out/decoder/build-tree.d.ts.map +1 -1
  86. package/out/decoder/build-tree.js +17 -0
  87. package/out/decoder/build-tree.js.map +1 -1
  88. package/out/env/index.d.ts +8 -0
  89. package/out/env/index.d.ts.map +1 -1
  90. package/out/env/schema.d.ts +9 -1
  91. package/out/env/schema.d.ts.map +1 -1
  92. package/out/env/schema.js +54 -2
  93. package/out/env/schema.js.map +1 -1
  94. package/out/fs/zip.d.ts +116 -0
  95. package/out/fs/zip.d.ts.map +1 -0
  96. package/out/fs/zip.js +216 -0
  97. package/out/fs/zip.js.map +1 -0
  98. package/out/identifiers.d.ts +23 -0
  99. package/out/identifiers.d.ts.map +1 -1
  100. package/out/identifiers.js +39 -0
  101. package/out/identifiers.js.map +1 -1
  102. package/out/layers/manifest.d.ts.map +1 -1
  103. package/out/layers/manifest.js +2 -1
  104. package/out/layers/manifest.js.map +1 -1
  105. package/out/locale/profiles/en-us.d.ts +2 -3
  106. package/out/locale/profiles/en-us.d.ts.map +1 -1
  107. package/out/locale/profiles/en-us.js +2 -3
  108. package/out/locale/profiles/en-us.js.map +1 -1
  109. package/out/locale/profiles/fr-fr.d.ts +1 -1
  110. package/out/locale/profiles/fr-fr.js +1 -1
  111. package/out/locale/profiles/ja-jp.d.ts +7 -7
  112. package/out/locale/profiles/ja-jp.js +7 -7
  113. package/out/objects.d.ts +18 -2
  114. package/out/objects.d.ts.map +1 -1
  115. package/out/objects.js +29 -3
  116. package/out/objects.js.map +1 -1
  117. package/out/pipeline/index.d.ts +2 -2
  118. package/out/pipeline/index.d.ts.map +1 -1
  119. package/out/pipeline/index.js +1 -1
  120. package/out/pipeline/index.js.map +1 -1
  121. package/out/pipeline/runtime-pipeline.d.ts +1 -1
  122. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  123. package/out/pipeline/runtime-pipeline.js +74 -18
  124. package/out/pipeline/runtime-pipeline.js.map +1 -1
  125. package/out/pipeline/span-proposer.d.ts +24 -0
  126. package/out/pipeline/span-proposer.d.ts.map +1 -1
  127. package/out/pipeline/span-proposer.js +36 -1
  128. package/out/pipeline/span-proposer.js.map +1 -1
  129. package/out/pipeline/types.d.ts +155 -3
  130. package/out/pipeline/types.d.ts.map +1 -1
  131. package/out/pipeline/types.js +41 -1
  132. package/out/pipeline/types.js.map +1 -1
  133. package/out/resolver/index.d.ts +3 -1
  134. package/out/resolver/index.d.ts.map +1 -1
  135. package/out/resolver/index.js +1 -0
  136. package/out/resolver/index.js.map +1 -1
  137. package/out/resolver/referential.d.ts +73 -0
  138. package/out/resolver/referential.d.ts.map +1 -0
  139. package/out/resolver/referential.js +71 -0
  140. package/out/resolver/referential.js.map +1 -0
  141. package/out/resolver/types.d.ts +204 -0
  142. package/out/resolver/types.d.ts.map +1 -1
  143. package/out/resolver/types.js.map +1 -1
  144. package/out/resources/index.d.ts +0 -1
  145. package/out/resources/index.d.ts.map +1 -1
  146. package/out/resources/index.js +0 -1
  147. package/out/resources/index.js.map +1 -1
  148. package/out/resources/libpostal.d.ts.map +1 -1
  149. package/out/resources/libpostal.js +3 -4
  150. package/out/resources/libpostal.js.map +1 -1
  151. package/out/resources/whosonfirst/index.d.ts +1 -0
  152. package/out/resources/whosonfirst/index.d.ts.map +1 -1
  153. package/out/resources/whosonfirst/index.js +1 -0
  154. package/out/resources/whosonfirst/index.js.map +1 -1
  155. package/out/resources/whosonfirst/placetypes/Placetype.d.ts.map +1 -1
  156. package/out/resources/whosonfirst/placetypes/Placetype.js +6 -5
  157. package/out/resources/whosonfirst/placetypes/Placetype.js.map +1 -1
  158. package/out/resources/whosonfirst/placetypes/admin.d.ts +12 -3
  159. package/out/resources/whosonfirst/placetypes/admin.d.ts.map +1 -1
  160. package/out/resources/whosonfirst/placetypes/admin.js +1 -1
  161. package/out/resources/whosonfirst/placetypes/admin.js.map +1 -1
  162. package/out/resources/whosonfirst/sharded-repo.d.ts +28 -0
  163. package/out/resources/whosonfirst/sharded-repo.d.ts.map +1 -0
  164. package/out/resources/whosonfirst/sharded-repo.js +58 -0
  165. package/out/resources/whosonfirst/sharded-repo.js.map +1 -0
  166. package/out/scripting/utils/index.d.ts.map +1 -1
  167. package/out/scripting/utils/index.js +2 -2
  168. package/out/scripting/utils/index.js.map +1 -1
  169. package/out/tools/download-libpostal-resources.d.ts.map +1 -1
  170. package/out/tools/download-libpostal-resources.js +1 -0
  171. package/out/tools/download-libpostal-resources.js.map +1 -1
  172. package/out/tools/generate-language-types.d.ts.map +1 -1
  173. package/out/tools/generate-language-types.js +5 -11
  174. package/out/tools/generate-language-types.js.map +1 -1
  175. package/out/utils/data-root.d.ts +20 -6
  176. package/out/utils/data-root.d.ts.map +1 -1
  177. package/out/utils/data-root.js +24 -5
  178. package/out/utils/data-root.js.map +1 -1
  179. package/out/utils/hash.d.ts +6 -0
  180. package/out/utils/hash.d.ts.map +1 -1
  181. package/out/utils/hash.js +8 -0
  182. package/out/utils/hash.js.map +1 -1
  183. package/out/utils/index.d.ts +1 -0
  184. package/out/utils/index.d.ts.map +1 -1
  185. package/out/utils/index.js +1 -0
  186. package/out/utils/index.js.map +1 -1
  187. package/out/utils/jsonl.d.ts +17 -3
  188. package/out/utils/jsonl.d.ts.map +1 -1
  189. package/out/utils/jsonl.js +23 -6
  190. package/out/utils/jsonl.js.map +1 -1
  191. package/out/utils/python-json.d.ts +3 -3
  192. package/out/utils/python-json.js +9 -9
  193. package/out/utils/python-numeric.d.ts +33 -0
  194. package/out/utils/python-numeric.d.ts.map +1 -0
  195. package/out/utils/python-numeric.js +149 -0
  196. package/out/utils/python-numeric.js.map +1 -0
  197. package/out/utils/python-random.d.ts +26 -1
  198. package/out/utils/python-random.d.ts.map +1 -1
  199. package/out/utils/python-random.js +43 -7
  200. package/out/utils/python-random.js.map +1 -1
  201. package/out/utils/repo.d.ts.map +1 -1
  202. package/out/utils/repo.js +18 -0
  203. package/out/utils/repo.js.map +1 -1
  204. package/out/utils/sealed-db.d.ts +12 -0
  205. package/out/utils/sealed-db.d.ts.map +1 -1
  206. package/out/utils/sealed-db.js +32 -1
  207. package/out/utils/sealed-db.js.map +1 -1
  208. package/package.json +34 -7
  209. package/pipeline/index.ts +3 -1
  210. package/pipeline/runtime-pipeline.ts +88 -27
  211. package/pipeline/span-proposer.ts +64 -1
  212. package/pipeline/types.ts +160 -2
  213. package/resolver/index.ts +13 -0
  214. package/resolver/referential.ts +84 -0
  215. package/resolver/types.ts +207 -0
  216. package/resources/index.ts +0 -1
  217. package/resources/libpostal.ts +8 -7
  218. package/resources/whosonfirst/index.ts +1 -0
  219. package/resources/whosonfirst/placetypes/Placetype.ts +13 -8
  220. package/resources/whosonfirst/placetypes/admin.ts +12 -2
  221. package/resources/whosonfirst/sharded-repo.ts +69 -0
  222. package/scripting/utils/index.ts +2 -3
  223. package/tools/download-libpostal-resources.ts +1 -0
  224. package/tools/generate-language-types.ts +5 -14
  225. package/utils/data-root.ts +27 -6
  226. package/utils/hash.ts +9 -0
  227. package/utils/index.ts +1 -0
  228. package/utils/jsonl.ts +26 -7
  229. package/utils/python-json.ts +10 -10
  230. package/utils/python-numeric.ts +168 -0
  231. package/utils/python-random.ts +49 -8
  232. package/utils/repo.ts +18 -0
  233. package/utils/sealed-db.ts +38 -1
  234. package/out/resources/collections.d.ts +0 -22
  235. package/out/resources/collections.d.ts.map +0 -1
  236. package/out/resources/collections.js +0 -69
  237. package/out/resources/collections.js.map +0 -1
  238. package/resources/collections.ts +0 -96
@@ -13,11 +13,11 @@
13
13
  * `JSON.stringify` is compact (`","` / `":"`). The committed files are spaced, so we match.
14
14
  * 2. **`ensure_ascii`.** Python defaults to escaping every non-ASCII codepoint as `\uXXXX` (surrogate
15
15
  * pairs for astral chars). `JSON.stringify` emits raw UTF-8. We replicate Python's default
16
- * (`ensureAscii: true`) and allow `ensure_ascii=False` (`ensureAscii: false`).
16
+ * (`ensureASCII: true`) and allow `ensure_ascii=False` (`ensureASCII: false`).
17
17
  *
18
18
  * String escaping of ASCII (quote, backslash, `\n`/`\t`/`\r`/`\b`/`\f`, other control -> `\u00xx`)
19
19
  * is identical between `JSON.stringify` and Python's json, so we delegate per-string base
20
- * escaping to `JSON.stringify` and only post-escape the non-ASCII range when `ensureAscii` is
20
+ * escaping to `JSON.stringify` and only post-escape the non-ASCII range when `ensureASCII` is
21
21
  * on.
22
22
  *
23
23
  * Caveat: JS has a single number type, so a whole-valued float (e.g. an exact `5.0` coordinate)
@@ -29,17 +29,17 @@ export interface PyJSONOptions {
29
29
  /**
30
30
  * Escape non-ASCII as `\uXXXX` (Python `ensure_ascii`). Defaults to `true`, matching Python.
31
31
  */
32
- ensureAscii?: boolean
32
+ ensureASCII?: boolean
33
33
  }
34
34
 
35
35
  /**
36
36
  * Serialize one string the way Python's json does (then optionally `ensure_ascii`-escape it).
37
37
  */
38
- function serializeString(value: string, ensureAscii: boolean): string {
38
+ function serializeString(value: string, ensureASCII: boolean): string {
39
39
  // JSON.stringify handles the quote/backslash/control escaping identically to Python's json.
40
40
  const out = JSON.stringify(value)
41
41
 
42
- if (!ensureAscii) return out
42
+ if (!ensureASCII) return out
43
43
  // ensure_ascii: escape every code unit >= 0x80 as \uXXXX (surrogate halves handled per-unit,
44
44
  // exactly as CPython emits astral codepoints as a \u-pair).
45
45
  let escaped = ""
@@ -64,7 +64,7 @@ function serializeNumber(value: number): string {
64
64
  return value > 0 ? "Infinity" : "-Infinity"
65
65
  }
66
66
 
67
- function serialize(value: unknown, ensureAscii: boolean): string {
67
+ function serialize(value: unknown, ensureASCII: boolean): string {
68
68
  if (value === null || value === undefined) return "null"
69
69
  const t = typeof value
70
70
 
@@ -72,10 +72,10 @@ function serialize(value: unknown, ensureAscii: boolean): string {
72
72
 
73
73
  if (t === "number") return serializeNumber(value as number)
74
74
 
75
- if (t === "string") return serializeString(value as string, ensureAscii)
75
+ if (t === "string") return serializeString(value as string, ensureASCII)
76
76
 
77
77
  if (Array.isArray(value)) {
78
- return "[" + value.map((v) => serialize(v, ensureAscii)).join(", ") + "]"
78
+ return "[" + value.map((v) => serialize(v, ensureASCII)).join(", ") + "]"
79
79
  }
80
80
 
81
81
  if (t === "object") {
@@ -83,7 +83,7 @@ function serialize(value: unknown, ensureAscii: boolean): string {
83
83
 
84
84
  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
85
85
  if (v === undefined) continue // a key Python would never have produced
86
- parts.push(serializeString(k, ensureAscii) + ": " + serialize(v, ensureAscii))
86
+ parts.push(serializeString(k, ensureASCII) + ": " + serialize(v, ensureASCII))
87
87
  }
88
88
 
89
89
  return "{" + parts.join(", ") + "}"
@@ -96,7 +96,7 @@ function serialize(value: unknown, ensureAscii: boolean): string {
96
96
  * `json.dumps(value)` — single line, `(", ", ": ")` separators, `ensure_ascii` per options.
97
97
  */
98
98
  export function pyJSONDumps(value: unknown, options: PyJSONOptions = {}): string {
99
- return serialize(value, options.ensureAscii ?? true)
99
+ return serialize(value, options.ensureASCII ?? true)
100
100
  }
101
101
 
102
102
  /**
@@ -0,0 +1,168 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Python-parity numeric helpers — the third member of the `python-*` family in this directory,
7
+ * beside `python-json.ts` (CPython `json.dumps` spacing) and `python-random.ts` (`random.Random`).
8
+ *
9
+ * These exist because the gazetteer pipeline was ported from Python and its outputs have to match
10
+ * the originals bit for bit: a postcode centroid that rounds differently is a different centroid,
11
+ * and the shard it lands in is a different shard. Divergence here never throws — it surfaces as a
12
+ * shard that quietly disagrees with the reference.
13
+ */
14
+
15
+ /**
16
+ * Digit at which a fractional remainder is exactly half. Above it the value rounds up; at it the tie is broken toward
17
+ * even, which is what keeps repeated centroid rounding unbiased.
18
+ */
19
+ const ROUND_HALF_DIGIT = 5
20
+
21
+ /**
22
+ * Increment a non-negative decimal-digit string, propagating the carry (e.g. "999" → "1000").
23
+ */
24
+ export function incDecimalString(s: string): string {
25
+ const a = s.split("")
26
+ let i = a.length - 1
27
+
28
+ for (; i >= 0; i--) {
29
+ if (a[i] === "9") {
30
+ a[i] = "0"
31
+ } else {
32
+ a[i] = String(Number(a[i]) + 1)
33
+
34
+ break
35
+ }
36
+ }
37
+
38
+ if (i < 0) {
39
+ a.unshift("1")
40
+ }
41
+
42
+ return a.join("")
43
+ }
44
+
45
+ /**
46
+ * Python `round()` — correctly-rounded, round-half-to-EVEN. Works off the double's EXACT (terminating) decimal
47
+ * expansion via `toFixed(80)`, so it matches Python both on ordinary values (where a naïve `x * 10**nd` would diverge
48
+ * by a ULP) and on exact half-way ties like `40.890625` → `40.89062` (where `toFixed(nd)` rounds half-UP and would
49
+ * diverge). `nd === 0` keeps a fast half-even path on the double.
50
+ */
51
+ export function pyRound(x: number, nd = 0): number {
52
+ if (!Number.isFinite(x)) return x
53
+
54
+ if (nd === 0) {
55
+ const floor = Math.floor(x)
56
+ const diff = x - floor
57
+
58
+ if (diff < 0.5) return floor
59
+
60
+ if (diff > 0.5) return floor + 1
61
+
62
+ return floor % 2 === 0 ? floor : floor + 1
63
+ }
64
+
65
+ const neg = x < 0
66
+ const digits = Math.abs(x).toFixed(20) // exact expansion for any coord/distance-range double
67
+ const dot = digits.indexOf(".")
68
+ const intPart = digits.slice(0, dot)
69
+ const frac = digits.slice(dot + 1)
70
+ const keep = frac.slice(0, nd)
71
+ const rest = frac.slice(nd)
72
+ let roundUp = false
73
+ const first = rest.charCodeAt(0) - 48
74
+
75
+ if (first > ROUND_HALF_DIGIT) {
76
+ roundUp = true
77
+ } else if (first === ROUND_HALF_DIGIT) {
78
+ if (/[1-9]/.test(rest.slice(1))) {
79
+ roundUp = true
80
+ } else {
81
+ // exact half → round to even
82
+ const lastKept = keep.length ? keep.charCodeAt(keep.length - 1) - 48 : Number(intPart) % 10
83
+ roundUp = lastKept % 2 === 1
84
+ }
85
+ }
86
+
87
+ let combined = intPart + keep
88
+
89
+ if (roundUp) {
90
+ combined = incDecimalString(combined)
91
+ }
92
+
93
+ const num = Number(combined) / 10 ** nd
94
+
95
+ return neg ? -num : num
96
+ }
97
+
98
+ /**
99
+ * Python `float()`: trimmed-empty / non-numeric → null (the build's try/except skip).
100
+ */
101
+ export function pyFloat(s: string | undefined): number | null {
102
+ if (s === undefined) return null
103
+ const t = s.trim()
104
+
105
+ if (t === "") return null
106
+ const n = Number(t)
107
+
108
+ return Number.isNaN(n) ? null : n
109
+ }
110
+
111
+ /**
112
+ * Python `format(x, ".{d}f")` — round-half-to-even (banker's), unlike JS `toFixed` (half-away).
113
+ */
114
+ export function pyFixed(x: number, d: number): string {
115
+ if (!Number.isFinite(x)) return Number.isNaN(x) ? "nan" : x > 0 ? "inf" : "-inf"
116
+ const neg = x < 0 || Object.is(x, -0)
117
+ const [intPart, fracRaw = ""] = Math.abs(x).toFixed(20).split(".")
118
+ const frac = fracRaw
119
+
120
+ if (frac.length <= d) {
121
+ const body = d > 0 ? `${intPart}.${frac.padEnd(d, "0")}` : intPart!
122
+
123
+ return (neg ? "-" : "") + body
124
+ }
125
+
126
+ const keep = frac.slice(0, d)
127
+ const rest = frac.slice(d)
128
+ let roundUp: boolean
129
+
130
+ if (rest[0]! > "5") {
131
+ roundUp = true
132
+ } else if (rest[0]! < "5") {
133
+ roundUp = false
134
+ } else if (rest.slice(1).replace(/0+$/, "").length) {
135
+ roundUp = true
136
+ } else {
137
+ const lastKept = d > 0 ? (keep[d - 1] ?? "0") : (intPart![intPart!.length - 1] ?? "0")
138
+ roundUp = Number.parseInt(lastKept, 10) % 2 === 1
139
+ }
140
+
141
+ let digits = intPart! + keep
142
+
143
+ if (roundUp) {
144
+ const arr = digits.split("")
145
+ let i = arr.length - 1
146
+
147
+ for (; i >= 0; i--) {
148
+ if (arr[i] === "9") {
149
+ arr[i] = "0"
150
+ } else {
151
+ arr[i] = String(Number.parseInt(arr[i]!, 10) + 1)
152
+
153
+ break
154
+ }
155
+ }
156
+
157
+ if (i < 0) {
158
+ arr.unshift("1")
159
+ }
160
+
161
+ digits = arr.join("")
162
+ }
163
+
164
+ const di = digits.length - d
165
+ const body = d > 0 ? `${digits.slice(0, di) || "0"}.${digits.slice(di)}` : digits.slice(0, di) || "0"
166
+
167
+ return (neg ? "-" : "") + body
168
+ }
@@ -13,28 +13,69 @@
13
13
  * byte-identical random stream buys nothing observable. What is preserved is what matters: a
14
14
  * seeded, deterministic-per-input stream and Python's helper semantics — inclusive `randint`,
15
15
  * uniform `choice`, with-replacement `choices`.
16
+ *
17
+ * TWO generators live here, and that is deliberate: their streams differ, and both streams are
18
+ * baked into shipped artifacts. mulberry32 decides which typos get injected into the training
19
+ * corpus; the LCG decides the train/test splits the scorer evals report. Collapsing them onto one
20
+ * would silently rewrite synthesized corpus rows and published eval numbers. New code should reach
21
+ * for `mulberry32` (better distribution) unless it must reproduce an existing stream.
16
22
  */
17
23
 
18
24
  /**
19
- * Seeded `random.Random`-equivalent. Backed by mulberry32 (a 32-bit stateful generator).
25
+ * Mulberry32 as a thunk — `seed` in, `() => number` in `[0, 1)` out.
26
+ *
27
+ * The thunk exists because callers inject a `random` option and want a bare function; `SeededRandom` below is the same
28
+ * generator behind the Python-shaped class surface. Reach for whichever matches the call site — for one seed they
29
+ * produce identical streams.
30
+ */
31
+ export function mulberry32(seed: number): () => number {
32
+ let a = seed >>> 0
33
+
34
+ return () => {
35
+ a = (a + 0x6d_2b_79_f5) | 0
36
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
37
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
38
+
39
+ return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296
40
+ }
41
+ }
42
+
43
+ /**
44
+ * The Numerical-Recipes linear congruential generator — `s = s * 1664525 + 1013904223 mod 2³²`.
45
+ *
46
+ * Weaker than {@link mulberry32}, and kept only because its exact stream is baked into shipped artifacts: the synthetic
47
+ * PO-box adapter's rows and the registry scorers' train/test splits both reproduce from it. Prefer `mulberry32` for
48
+ * anything new.
49
+ *
50
+ * Seed 0 is a valid state here (unlike mulberry32, which needs a non-zero one); callers that used to guard with `seed
51
+ * || 1` keep doing so at the call site, since dropping the guard would shift their stream for that one seed.
52
+ */
53
+ export function makeLcg(seed: number): () => number {
54
+ let s = seed >>> 0
55
+
56
+ return () => {
57
+ s = (s * 1_664_525 + 1_013_904_223) % 4_294_967_296
58
+
59
+ return s / 4_294_967_296
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Seeded `random.Random`-equivalent. Backed by {@link mulberry32}.
20
65
  */
21
66
  export class SeededRandom {
22
- #state: number
67
+ readonly #next: () => number
23
68
 
24
69
  constructor(seed: number) {
25
70
  // mulberry32 wants a non-zero 32-bit state.
26
- this.#state = seed >>> 0 || 1
71
+ this.#next = mulberry32(seed >>> 0 || 1)
27
72
  }
28
73
 
29
74
  /**
30
75
  * Float in `[0, 1)`. Mirrors Python `random.random()`.
31
76
  */
32
77
  random(): number {
33
- let t = (this.#state += 0x6d_2b_79_f5)
34
- t = Math.imul(t ^ (t >>> 15), t | 1)
35
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
36
-
37
- return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296
78
+ return this.#next()
38
79
  }
39
80
 
40
81
  /**
package/utils/repo.ts CHANGED
@@ -46,6 +46,24 @@ const __dirname = dirname(fileURLToPath(import.meta.url)) as Join<[RepoRootAlias
46
46
  * (Earlier this checked `resolve("..", "..")`, which overshoots `out/` to `core/` and so was always false — the
47
47
  * compiled tree then resolved `CorePackageAbsolutePath` to `core/out` instead of `core/`, landing dictionary reads at
48
48
  * the nonexistent `core/out/data` and requiring an external symlink bridge to find `core/data`. #481.)
49
+ *
50
+ * WHY NOT NATIVE RESOLUTION (2026-08-05 triage). `node:module`'s `findPackageJSON` looks like it retires this
51
+ * arithmetic, and for HALF of it, it would: measured, `dirname(findPackageJSON(import.meta.url))` yields `core/` from
52
+ * BOTH `core/utils/repo.ts` and `core/out/utils/repo.js` (tsc emits no `core/out/package.json`, so the upward walk
53
+ * lands in the same place from either depth) — i.e. it computes {@link CorePackageAbsolutePath} with no
54
+ * `__isCompiledTree` at all. Two things stop it.
55
+ *
56
+ * First, it only covers that half. {@link RepoRootAbsolutePath} is the MONOREPO root, which is not a package on any
57
+ * resolution path from here — no native resolver can name it — so the flag survives for `__upCount` regardless. The
58
+ * arithmetic does not go away; it stops being shared by two consumers, which is worse, not better.
59
+ *
60
+ * Second, this module is reachable from a BUNDLED graph — `core/resources/libpostal.ts` imports it and
61
+ * `@mailwoman/core/resources` is a webpack alias in the demo — and that build resolves every `node:` specifier to an
62
+ * empty shim (`docs/plugins/demo-assets/plugin.ts`: a `NormalModuleReplacementPlugin(/^node:/)` plus a `fallback` map
63
+ * that lists `node:module` right beside `node:path` and `node:url`). A shimmed builtin fails SILENTLY — the import
64
+ * succeeds and the binding is `undefined` — so anything new taken from `node:` here would be an undefined call at
65
+ * module top level rather than a resolution error someone sees. The current code takes only what already survives that
66
+ * treatment. Keep the string arithmetic.
49
67
  */
50
68
  const __isCompiledTree = basename(resolve(__dirname, "..")) === OutDirectoryName
51
69
  const __upCount = __isCompiledTree ? PathReflection.length : PathReflection.length - 1
@@ -8,8 +8,14 @@
8
8
  * is how anything opens a data artifact; a write-mode open of a sealed file throws a NAMED error
9
9
  * pointing at the rebuild command instead of a cryptic SQLITE_READONLY. Unsealing is deliberate and
10
10
  * manual (`chmod u+w`), never programmatic — rebuild, don't mutate.
11
+ *
12
+ * `swapDatabaseIntoPlace` is the other half of that invariant — the atomic publish step AGENTS.md
13
+ * specifies in prose ("build it successfully, then move the previous version to a temp directory,
14
+ * and then move the new version into place"). It lives here because this module already owns the
15
+ * built-artifact lifecycle, and because a rule the project states in prose and implements more than
16
+ * once in code should be a function.
11
17
  */
12
- import { chmodSync, existsSync, statSync, unlinkSync } from "node:fs"
18
+ import { chmodSync, existsSync, renameSync, rmSync, statSync, unlinkSync } from "node:fs"
13
19
  import { basename } from "node:path"
14
20
  import type { DatabaseSync } from "node:sqlite"
15
21
 
@@ -91,3 +97,34 @@ export function openBuiltDatabase(path: string, opts: { write?: boolean } = {}):
91
97
 
92
98
  return new (sqlite().DatabaseSync)(path, { readOnly: true })
93
99
  }
100
+
101
+ /**
102
+ * Atomically move a freshly-built database into its published location.
103
+ *
104
+ * The build writes to a temp path, so a mid-build crash never leaves a half-written DB at `finalPath`. This moves any
105
+ * prior version aside, slots the new one in, then drops the old — the previous file stays intact until the replacement
106
+ * is committed, and the `-wal`/`-shm` siblings of BOTH paths are cleared so a stale journal can never be paired with a
107
+ * new main file.
108
+ *
109
+ * Sealing (`sealDatabase`) happens on the temp file BEFORE the swap: a sealed artifact is what gets published, and 0444
110
+ * does not prevent a rename.
111
+ */
112
+ export function swapDatabaseIntoPlace(tmpPath: string, finalPath: string): void {
113
+ const aside = `${finalPath}.old-${process.pid}`
114
+
115
+ if (existsSync(finalPath)) {
116
+ renameSync(finalPath, aside)
117
+ }
118
+
119
+ for (const sfx of ["-wal", "-shm"]) {
120
+ rmSync(finalPath + sfx, { force: true })
121
+ }
122
+
123
+ renameSync(tmpPath, finalPath)
124
+
125
+ for (const sfx of ["-wal", "-shm"]) {
126
+ rmSync(tmpPath + sfx, { force: true })
127
+ }
128
+
129
+ rmSync(aside, { force: true })
130
+ }
@@ -1,22 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
6
- /**
7
- * Given an iterable collection, returns an async iterable, executing the callback on each batch.
8
- *
9
- * This is useful for batching asynchronous operations.
10
- *
11
- * @param collection The collection to batch.
12
- * @param batchSize The size of each batch.
13
- * @param callback The async callback to execute on each batch.
14
- */
15
- export declare function takeInParallel<T, C extends (entry: T) => Promise<unknown>>(collection: Iterable<T> | AsyncIterable<T>, batchSize: number, callback: C, abortSignal?: AbortSignal): AsyncIterable<Awaited<ReturnType<C>>>;
16
- /**
17
- * Given an async iterable collection, returns an async iterable, yielding batches of items.
18
- *
19
- * This is useful for emitting asynchronous items in batches, such as when processing a stream of data.
20
- */
21
- export declare function takeAsync<T>(collection: AsyncIterable<T>, batchSize: number): AsyncIterable<T[]>;
22
- //# sourceMappingURL=collections.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"collections.d.ts","sourceRoot":"","sources":["../../resources/collections.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;;;;GAQG;AACH,wBAAuB,cAAc,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,EAChF,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,EAC1C,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,CAAC,EACX,WAAW,CAAC,EAAE,WAAW,GACvB,aAAa,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAoDvC;AAED;;;;GAIG;AACH,wBAAuB,SAAS,CAAC,CAAC,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,GAAG,aAAa,CAAC,CAAC,EAAE,CAAC,CAgBvG"}
@@ -1,69 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
6
- /**
7
- * Given an iterable collection, returns an async iterable, executing the callback on each batch.
8
- *
9
- * This is useful for batching asynchronous operations.
10
- *
11
- * @param collection The collection to batch.
12
- * @param batchSize The size of each batch.
13
- * @param callback The async callback to execute on each batch.
14
- */
15
- export async function* takeInParallel(collection, batchSize, callback, abortSignal) {
16
- const iterator = Symbol.asyncIterator in collection ? collection[Symbol.asyncIterator]() : collection[Symbol.iterator]();
17
- const runningTasks = new Map();
18
- const results = new Map();
19
- let iterationResult = await iterator.next();
20
- // oxlint-disable-next-line eslint/no-unmodified-loop-condition -- `abortSignal.aborted` is flipped by the controller, not by this loop
21
- while ((!iterationResult.done || results.size) && !abortSignal?.aborted) {
22
- for (const [key, result] of results) {
23
- yield result;
24
- results.delete(key);
25
- }
26
- if (runningTasks.size >= batchSize) {
27
- await Promise.race(runningTasks.values());
28
- continue;
29
- }
30
- if (iterationResult.done) {
31
- await Promise.all(runningTasks.values());
32
- break;
33
- }
34
- const entry = iterationResult.value;
35
- // oxlint-disable-next-line promise/always-return -- the handle tracks completion, not a value
36
- const futureResult = callback(entry).then((result) => {
37
- runningTasks.delete(entry);
38
- results.set(entry, result);
39
- });
40
- runningTasks.set(entry, futureResult);
41
- iterationResult = await iterator.next();
42
- }
43
- if (!abortSignal || !abortSignal.aborted) {
44
- await Promise.all(runningTasks.values());
45
- for (const [key, result] of results) {
46
- yield result;
47
- results.delete(key);
48
- }
49
- }
50
- }
51
- /**
52
- * Given an async iterable collection, returns an async iterable, yielding batches of items.
53
- *
54
- * This is useful for emitting asynchronous items in batches, such as when processing a stream of data.
55
- */
56
- export async function* takeAsync(collection, batchSize) {
57
- let buffer = [];
58
- for await (const item of collection) {
59
- buffer.push(item);
60
- if (buffer.length === batchSize) {
61
- yield buffer;
62
- buffer = [];
63
- }
64
- }
65
- if (buffer.length) {
66
- yield buffer;
67
- }
68
- }
69
- //# sourceMappingURL=collections.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"collections.js","sourceRoot":"","sources":["../../resources/collections.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,cAAc,CACpC,UAA0C,EAC1C,SAAiB,EACjB,QAAW,EACX,WAAyB;IAEzB,MAAM,QAAQ,GACb,MAAM,CAAC,aAAa,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAA;IAExG,MAAM,YAAY,GAAG,IAAI,GAAG,EAAuB,CAAA;IACnD,MAAM,OAAO,GAAG,IAAI,GAAG,EAAoB,CAAA;IAE3C,IAAI,eAAe,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;IAE3C,uIAAuI;IACvI,OAAO,CAAC,CAAC,eAAe,CAAC,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,CAAC;QACzE,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;YACrC,MAAM,MAAM,CAAA;YAEZ,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QACpB,CAAC;QAED,IAAI,YAAY,CAAC,IAAI,IAAI,SAAS,EAAE,CAAC;YACpC,MAAM,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,CAAC,CAAA;YAEzC,SAAQ;QACT,CAAC;QAED,IAAI,eAAe,CAAC,IAAI,EAAE,CAAC;YAC1B,MAAM,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,EAAE,CAAC,CAAA;YAExC,MAAK;QACN,CAAC;QAED,MAAM,KAAK,GAAG,eAAe,CAAC,KAAK,CAAA;QAEnC,8FAA8F;QAC9F,MAAM,YAAY,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;YACpD,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YAE1B,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAuB,CAAC,CAAA;QAC5C,CAAC,CAAC,CAAA;QAEF,YAAY,CAAC,GAAG,CAAC,KAAK,EAAE,YAAY,CAAC,CAAA;QAErC,eAAe,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;IACxC,CAAC;IAED,IAAI,CAAC,WAAW,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC;QAC1C,MAAM,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,EAAE,CAAC,CAAA;QAExC,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;YACrC,MAAM,MAAM,CAAA;YAEZ,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QACpB,CAAC;IACF,CAAC;AACF,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,SAAS,CAAI,UAA4B,EAAE,SAAiB;IAClF,IAAI,MAAM,GAAQ,EAAE,CAAA;IAEpB,IAAI,KAAK,EAAE,MAAM,IAAI,IAAI,UAAU,EAAE,CAAC;QACrC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAEjB,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YACjC,MAAM,MAAM,CAAA;YAEZ,MAAM,GAAG,EAAE,CAAA;QACZ,CAAC;IACF,CAAC;IAED,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QACnB,MAAM,MAAM,CAAA;IACb,CAAC;AACF,CAAC"}
@@ -1,96 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
6
-
7
- /**
8
- * Given an iterable collection, returns an async iterable, executing the callback on each batch.
9
- *
10
- * This is useful for batching asynchronous operations.
11
- *
12
- * @param collection The collection to batch.
13
- * @param batchSize The size of each batch.
14
- * @param callback The async callback to execute on each batch.
15
- */
16
- export async function* takeInParallel<T, C extends (entry: T) => Promise<unknown>>(
17
- collection: Iterable<T> | AsyncIterable<T>,
18
- batchSize: number,
19
- callback: C,
20
- abortSignal?: AbortSignal
21
- ): AsyncIterable<Awaited<ReturnType<C>>> {
22
- const iterator =
23
- Symbol.asyncIterator in collection ? collection[Symbol.asyncIterator]() : collection[Symbol.iterator]()
24
-
25
- const runningTasks = new Map<T, Promise<unknown>>()
26
- const results = new Map<T, ReturnType<C>>()
27
-
28
- let iterationResult = await iterator.next()
29
-
30
- // oxlint-disable-next-line eslint/no-unmodified-loop-condition -- `abortSignal.aborted` is flipped by the controller, not by this loop
31
- while ((!iterationResult.done || results.size) && !abortSignal?.aborted) {
32
- for (const [key, result] of results) {
33
- yield result
34
-
35
- results.delete(key)
36
- }
37
-
38
- if (runningTasks.size >= batchSize) {
39
- await Promise.race(runningTasks.values())
40
-
41
- continue
42
- }
43
-
44
- if (iterationResult.done) {
45
- await Promise.all(runningTasks.values())
46
-
47
- break
48
- }
49
-
50
- const entry = iterationResult.value
51
-
52
- // oxlint-disable-next-line promise/always-return -- the handle tracks completion, not a value
53
- const futureResult = callback(entry).then((result) => {
54
- runningTasks.delete(entry)
55
-
56
- results.set(entry, result as ReturnType<C>)
57
- })
58
-
59
- runningTasks.set(entry, futureResult)
60
-
61
- iterationResult = await iterator.next()
62
- }
63
-
64
- if (!abortSignal || !abortSignal.aborted) {
65
- await Promise.all(runningTasks.values())
66
-
67
- for (const [key, result] of results) {
68
- yield result
69
-
70
- results.delete(key)
71
- }
72
- }
73
- }
74
-
75
- /**
76
- * Given an async iterable collection, returns an async iterable, yielding batches of items.
77
- *
78
- * This is useful for emitting asynchronous items in batches, such as when processing a stream of data.
79
- */
80
- export async function* takeAsync<T>(collection: AsyncIterable<T>, batchSize: number): AsyncIterable<T[]> {
81
- let buffer: T[] = []
82
-
83
- for await (const item of collection) {
84
- buffer.push(item)
85
-
86
- if (buffer.length === batchSize) {
87
- yield buffer
88
-
89
- buffer = []
90
- }
91
- }
92
-
93
- if (buffer.length) {
94
- yield buffer
95
- }
96
- }