@mailwoman/core 7.1.0 → 7.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/api/APIClient.ts +175 -0
  2. package/api/headless.ts +23 -0
  3. package/api/index.ts +11 -0
  4. package/api/responses.ts +135 -0
  5. package/coarse-placer/coarse-placer.ts +300 -0
  6. package/coarse-placer/featurize.ts +171 -0
  7. package/coarse-placer/tools/build-dataset.ts +223 -0
  8. package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
  9. package/coarse-placer/tools/build-outlier-latin.ts +200 -0
  10. package/coarse-placer/tools/build-outlier-oa.ts +231 -0
  11. package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
  12. package/coarse-placer/tools/eval-openset.ts +519 -0
  13. package/coarse-placer/tools/eval-quant-compare.ts +151 -0
  14. package/coarse-placer/tools/eval.ts +187 -0
  15. package/coarse-placer/tools/fnv-hash.ts +24 -0
  16. package/coarse-placer/tools/index.ts +23 -0
  17. package/coarse-placer/tools/probe-frontier.ts +216 -0
  18. package/coarse-placer/tools/quantize.ts +116 -0
  19. package/coarse-placer/tools/train.ts +244 -0
  20. package/collections.ts +134 -0
  21. package/db/schema.ts +21 -0
  22. package/decoder/build-tree.ts +228 -0
  23. package/decoder/calibration.ts +101 -0
  24. package/decoder/containment.ts +87 -0
  25. package/decoder/index.ts +17 -0
  26. package/decoder/proposals-to-tree.ts +83 -0
  27. package/decoder/resolve-proposal-overlaps.ts +79 -0
  28. package/decoder/serialize-json.ts +70 -0
  29. package/decoder/serialize-tuples.ts +61 -0
  30. package/decoder/serialize-xml.ts +209 -0
  31. package/decoder/types.ts +159 -0
  32. package/decoder/unknown-spans.ts +103 -0
  33. package/decoder/validate-tree.ts +100 -0
  34. package/env/index.ts +42 -0
  35. package/env/load.ts +14 -0
  36. package/env/paths.ts +40 -0
  37. package/env/schema.ts +125 -0
  38. package/errors/index.ts +9 -0
  39. package/errors/schema.ts +155 -0
  40. package/fs/node.ts +38 -0
  41. package/identifiers.ts +58 -0
  42. package/index.ts +13 -0
  43. package/kysley/adapter.ts +29 -0
  44. package/kysley/client.ts +30 -0
  45. package/kysley/dialect-config.ts +30 -0
  46. package/kysley/dialect.ts +67 -0
  47. package/kysley/driver.ts +175 -0
  48. package/layers/index.ts +12 -0
  49. package/layers/manifest.ts +154 -0
  50. package/layers/schema.ts +105 -0
  51. package/lifecycle/ServiceSymbol.ts +95 -0
  52. package/lifecycle/index.ts +11 -0
  53. package/lifecycle/lru-cache.ts +44 -0
  54. package/lifecycle/services.ts +322 -0
  55. package/locale/index.ts +9 -0
  56. package/locale/locale.ts +49 -0
  57. package/locale/profiles/en-us.ts +69 -0
  58. package/locale/profiles/fr-fr.ts +75 -0
  59. package/locale/profiles/index.ts +9 -0
  60. package/locale/profiles/ja-jp.ts +33 -0
  61. package/locale/registry.ts +68 -0
  62. package/logging/index.ts +8 -0
  63. package/logging/shared.ts +145 -0
  64. package/logging/utils.ts +46 -0
  65. package/objects.ts +211 -0
  66. package/out/layers/index.d.ts +12 -0
  67. package/out/layers/index.d.ts.map +1 -0
  68. package/out/layers/index.js +12 -0
  69. package/out/layers/index.js.map +1 -0
  70. package/out/layers/manifest.d.ts +64 -0
  71. package/out/layers/manifest.d.ts.map +1 -0
  72. package/out/layers/manifest.js +102 -0
  73. package/out/layers/manifest.js.map +1 -0
  74. package/out/layers/schema.d.ts +72 -0
  75. package/out/layers/schema.d.ts.map +1 -0
  76. package/out/layers/schema.js +61 -0
  77. package/out/layers/schema.js.map +1 -0
  78. package/out/pipeline/index.d.ts +1 -1
  79. package/out/pipeline/index.d.ts.map +1 -1
  80. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  81. package/out/pipeline/runtime-pipeline.js +27 -0
  82. package/out/pipeline/runtime-pipeline.js.map +1 -1
  83. package/out/pipeline/types.d.ts +74 -4
  84. package/out/pipeline/types.d.ts.map +1 -1
  85. package/out/pipeline/types.js.map +1 -1
  86. package/package.json +21 -21
  87. package/pipeline/index.ts +46 -0
  88. package/pipeline/reconcile-lookups.ts +108 -0
  89. package/pipeline/reconcile.ts +542 -0
  90. package/pipeline/runtime-pipeline.ts +732 -0
  91. package/pipeline/span-logit-aggregation.ts +151 -0
  92. package/pipeline/span-proposer.ts +587 -0
  93. package/pipeline/types.ts +348 -0
  94. package/policy/defaults.ts +35 -0
  95. package/policy/index.ts +10 -0
  96. package/policy/policy.ts +60 -0
  97. package/policy/proposal-collection.ts +64 -0
  98. package/policy/registry.ts +149 -0
  99. package/resolver/index.ts +29 -0
  100. package/resolver/types.ts +584 -0
  101. package/resources/LocaleIndex.ts +124 -0
  102. package/resources/ResourceMapCache.ts +126 -0
  103. package/resources/collections.ts +93 -0
  104. package/resources/debugging.ts +19 -0
  105. package/resources/git.ts +54 -0
  106. package/resources/index.ts +17 -0
  107. package/resources/languages/index.ts +49 -0
  108. package/resources/languages/types.gen.ts +1368 -0
  109. package/resources/libaddressinput.ts +105 -0
  110. package/resources/libpostal.ts +182 -0
  111. package/resources/locale.ts +23 -0
  112. package/resources/set.ts +179 -0
  113. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  114. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  115. package/resources/whosonfirst/index.ts +10 -0
  116. package/resources/whosonfirst/loader.ts +157 -0
  117. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  118. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  119. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  120. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  121. package/resources/whosonfirst/placetypes/index.ts +12 -0
  122. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  123. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  124. package/routing/index.ts +208 -0
  125. package/scripting/index.ts +40 -0
  126. package/scripting/utils/index.ts +106 -0
  127. package/tokenization/Graph.ts +50 -0
  128. package/tokenization/Span.ts +297 -0
  129. package/tokenization/index.ts +9 -0
  130. package/tokenization/normalizer.ts +123 -0
  131. package/tools/download-libpostal-resources.ts +98 -0
  132. package/tools/download-ssl-address.ts +99 -0
  133. package/tools/generate-language-types.ts +194 -0
  134. package/tools/index.ts +13 -0
  135. package/types/Classification.ts +211 -0
  136. package/types/classifier.ts +133 -0
  137. package/types/component.ts +75 -0
  138. package/types/index.ts +10 -0
  139. package/types/mapping.ts +81 -0
  140. package/utils/data-root.ts +56 -0
  141. package/utils/hash.ts +27 -0
  142. package/utils/index.ts +14 -0
  143. package/utils/jsonl.ts +43 -0
  144. package/utils/python-json.ts +105 -0
  145. package/utils/python-random.ts +90 -0
  146. package/utils/repo.ts +118 -0
  147. package/utils/sealed-db.ts +85 -0
  148. package/utils/stats.ts +32 -0
  149. package/vitest.config.ts +53 -0
@@ -0,0 +1,106 @@
1
+ import { ResourceError } from "../../errors/index.ts"
2
+ import { ServiceRepository } from "../../lifecycle/index.ts"
3
+ import { ConsoleLogger } from "../../logging/index.ts"
4
+
5
+ /**
6
+ * Logs an error that occurred while running a script.
7
+ */
8
+ export function logScriptError(error: unknown): void {
9
+ ConsoleLogger.error("An error occurred while running the script.")
10
+
11
+ const normalizedError = error instanceof ResourceError ? error : ResourceError.wrap(error)
12
+
13
+ ConsoleLogger.error(normalizedError)
14
+
15
+ if (normalizedError.cause instanceof Error && normalizedError.cause.stack) {
16
+ ConsoleLogger.error("Stack via cause:\n" + normalizedError.cause.stack)
17
+ } else if (normalizedError.stack) {
18
+ ConsoleLogger.error("Stack via cause:\n" + normalizedError.stack)
19
+ }
20
+ }
21
+
22
+ /**
23
+ * A script callback function to invoke.
24
+ *
25
+ * @internal
26
+ */
27
+ export type ScriptCallback = (...args: unknown[]) => unknown | Promise<unknown>
28
+
29
+ /**
30
+ * Cleans up services and exits the script cleanly.
31
+ *
32
+ * @param exitCode - Explicit exit code; when omitted, whatever `process.exitCode` the script set (default 0) stands.
33
+ * @internal
34
+ */
35
+ export function postScriptCleanup(signal: NodeJS.Signals = "SIGTERM", exitCode?: number): Promise<void> {
36
+ ConsoleLogger.debug(`\n[${signal}] Shutting down...`)
37
+
38
+ const timeout = setTimeout(() => {
39
+ ConsoleLogger.error("Script did not exit in a timely manner.")
40
+
41
+ ServiceRepository.abortController.abort(signal)
42
+
43
+ const services = ServiceRepository.inspect()
44
+ ConsoleLogger.warn(services, `${services.length} did not dispose.`)
45
+
46
+ process.exit(1)
47
+ }, 15_000)
48
+
49
+ return ServiceRepository.dispose()
50
+ .catch(logScriptError)
51
+ .finally(() => {
52
+ clearTimeout(timeout)
53
+ process.exit(exitCode ?? process.exitCode ?? 0)
54
+ })
55
+ }
56
+
57
+ /**
58
+ * Runs a script callback and handles cleanup. A callback that throws exits 1; a clean return exits with
59
+ * `process.exitCode` (default 0).
60
+ *
61
+ * @internal
62
+ */
63
+ export function runScript(scriptCallback: ScriptCallback): Promise<void> {
64
+ process.on("SIGINT", postScriptCleanup)
65
+ process.on("SIGTERM", postScriptCleanup)
66
+
67
+ return Promise.resolve()
68
+ .then(() => scriptCallback())
69
+ .then(
70
+ () => postScriptCleanup(),
71
+ (error) => {
72
+ logScriptError(error)
73
+
74
+ return postScriptCleanup("SIGTERM", 1)
75
+ }
76
+ )
77
+ .catch(() => postScriptCleanup("SIGTERM", 1))
78
+ }
79
+
80
+ /**
81
+ * The ONE blessed accessor for CLI arguments. Everything outside `core/env` + this module is forbidden from touching
82
+ * `process.argv` directly (enforced by the `sister-software/no-process-globals` oxlint rule) — prefer `node:util`
83
+ * `parseArgs` (which reads this same slice by default) and reach for this only where `parseArgs` cannot express the
84
+ * grammar (e.g. verbatim passthrough of undeclared flags to a child process — see
85
+ * `corpus-python/scripts/train_with_resume.ts`).
86
+ */
87
+ export function cliArguments(): string[] {
88
+ // oxlint-disable-next-line sister-software/no-process-globals
89
+ return process.argv.slice(2)
90
+ }
91
+
92
+ /**
93
+ * The ONE blessed way to build a child-process environment: the current environment with explicit overrides. Everything
94
+ * outside `core/env` + this module is forbidden from touching `process.env` directly (enforced by
95
+ * `scripts/lint-raw-env-argv.ts`) — read config through `$public`/`$private`.
96
+ */
97
+ export function childEnv(overrides: Record<string, string | undefined> = {}): NodeJS.ProcessEnv {
98
+ // oxlint-disable-next-line sister-software/no-process-globals
99
+ return { ...process.env, ...overrides }
100
+ }
101
+
102
+ /** The path of the executing script (`argv[1]`) — for commands that re-spawn or reference their own CLI entry. */
103
+ export function scriptEntryPath(): string {
104
+ // oxlint-disable-next-line sister-software/no-process-globals
105
+ return process.argv[1]!
106
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ // Import `Sequence` from its leaf module, NOT the `@mailwoman/core/resources` barrel: the barrel
8
+ // re-exports the libpostal/WOF dictionaries (top-level `readdir` + fast-glob, Node-only), which would
9
+ // drag the entire resource-loading layer into any browser bundle that touches tokenization — and
10
+ // `@mailwoman/phrase-grouper` touches it via `Span`. `Sequence` itself is a pure `extends Set`.
11
+ import { Sequence } from "../resources/set.ts"
12
+
13
+ export type GraphNodeCallback<G> = (node: G) => boolean
14
+
15
+ /**
16
+ * A graph structure for storing relationships between nodes.
17
+ */
18
+ export class Graph<GraphNode extends WeakKey> {
19
+ /**
20
+ * Parents of the graph, i.e. upward connections to the graph.
21
+ */
22
+ public parents: Sequence<GraphNode> = new Sequence()
23
+
24
+ /**
25
+ * Children of the graph, i.e. downward connections to the graph.
26
+ */
27
+ public children: Sequence<GraphNode> = new Sequence()
28
+
29
+ /**
30
+ * Previous siblings of the graph, i.e. leftward connections to the graph.
31
+ */
32
+ public readonly previousSiblings = new Sequence<GraphNode>()
33
+ /**
34
+ * Next siblings of the graph, i.e. rightward connections to the graph.
35
+ */
36
+ public readonly nextSiblings = new Sequence<GraphNode>()
37
+
38
+ /**
39
+ * Phrases identified in the graph, i.e. a sequence of nodes composing a classification.
40
+ */
41
+ public readonly phrases: Sequence<GraphNode> = new Sequence<GraphNode>()
42
+
43
+ public get nextSibling(): GraphNode | null {
44
+ return this.nextSiblings.first
45
+ }
46
+
47
+ public get previousSibling(): GraphNode | null {
48
+ return this.previousSiblings.first
49
+ }
50
+ }
@@ -0,0 +1,297 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import type { Displayable } from "../resources/debugging.ts"
8
+ import type { Alpha3bLanguageCode } from "../resources/languages/index.ts"
9
+ import type { LibPostalLanguageCode } from "../resources/libpostal.ts"
10
+ // Imported via deep relative path (not @mailwoman/core/classification) to avoid a runtime cycle:
11
+ // classification/index.ts re-exports SectionClassifier / WordClassifier which themselves import
12
+ // Span from @mailwoman/core/tokenization, creating a TDZ that surfaces as "Class extends value
13
+ // undefined" when the source-mode test runner loads tokenization first.
14
+ import { type Classification, type ClassificationMatch, ClassificationsMatchMap } from "../types/Classification.ts"
15
+ import { Graph } from "./Graph.ts"
16
+
17
+ const MAX_SPAN_LENGTH = 140
18
+
19
+ export interface SpanCreationOptions {
20
+ start?: number
21
+ classifications?: Iterable<Classification>
22
+ children?: Iterable<Span>
23
+ }
24
+
25
+ const kSpanID: unique symbol = Symbol("SpanID")
26
+
27
+ export interface SerializedSpan {
28
+ // [kSpanID]: number
29
+ body: string
30
+ start: number
31
+ end: number
32
+ normalized: string
33
+ classifications: ClassificationMatch[]
34
+ children: SerializedSpan[]
35
+ phrases: SerializedSpan[]
36
+ }
37
+
38
+ /**
39
+ * A span of text, i.e. a token or a phrase.
40
+ */
41
+ export class Span extends Graph<Span> {
42
+ #body: string = ""
43
+ /**
44
+ * The start index of the span.
45
+ */
46
+ public start: number
47
+
48
+ /**
49
+ * The end index of the span.
50
+ */
51
+ public end!: number
52
+
53
+ /**
54
+ * The unique identifier for this span.
55
+ */
56
+ protected static IDCounter = 0
57
+
58
+ /**
59
+ * The unique identifier for this span.
60
+ */
61
+ readonly [kSpanID]!: number
62
+
63
+ public get id(): number {
64
+ return this[kSpanID]
65
+ }
66
+
67
+ /**
68
+ * The normalized body of the span.
69
+ */
70
+ public normalized = ""
71
+
72
+ /**
73
+ * Classifications for this span.
74
+ */
75
+ public readonly classifications: ClassificationsMatchMap = new ClassificationsMatchMap()
76
+
77
+ readonly #flags = new Set<SpanFlag>()
78
+
79
+ /**
80
+ * Boolean-like indications that hint at the nature of the span.
81
+ *
82
+ * Unlike classifications, these are not exposed in the final output.
83
+ */
84
+ public get flags(): ReadonlySet<SpanFlag> {
85
+ return this.#flags
86
+ }
87
+
88
+ public is(classification: Classification): boolean {
89
+ return this.classifications.has(classification)
90
+ }
91
+
92
+ static from(input?: string, options?: SpanCreationOptions): Span
93
+ static from(input: Span, options?: Omit<SpanCreationOptions, "start">): Span
94
+ static from(input: Span | string, options?: SpanCreationOptions): Span
95
+ static from(input: Span | string = "", options: SpanCreationOptions = {}): Span {
96
+ const span = input instanceof Span ? input : new Span(input, options.start)
97
+
98
+ for (const classification of options.classifications ?? []) {
99
+ span.classifications.add(classification)
100
+ }
101
+
102
+ span.children.add(...(options.children ?? []))
103
+
104
+ return span
105
+ }
106
+
107
+ constructor(body = "", start = 0) {
108
+ super()
109
+
110
+ // this[kSpanID] = Span.IDCounter++
111
+ Object.defineProperty(this, kSpanID, {
112
+ value: Span.IDCounter++,
113
+ writable: false,
114
+ enumerable: false,
115
+ configurable: false,
116
+ })
117
+
118
+ // Note that `start` should be set first to ensure that `end` is calculated correctly.
119
+ this.start = start
120
+ this.body = body
121
+ }
122
+
123
+ get body(): string {
124
+ return this.#body
125
+ }
126
+
127
+ /**
128
+ * Set the body of the Span
129
+ */
130
+ set body(nextBody: string) {
131
+ this.#flags.clear()
132
+ this.#body = nextBody.slice(0, MAX_SPAN_LENGTH)
133
+
134
+ this.normalized = this.#body.toLowerCase()
135
+ this.end = this.start + this.#body.length
136
+
137
+ for (const [pattern, flag] of PatternMatchers) {
138
+ if (pattern.test(this.normalized)) {
139
+ this.#flags.add(flag)
140
+
141
+ break
142
+ }
143
+ }
144
+
145
+ if (this.flags.has("numeric") || this.flags.has("alphanumeric")) {
146
+ this.#flags.add("numeral")
147
+ }
148
+
149
+ if (this.#body.slice(-1) === ".") {
150
+ this.#flags.add("ends_with_period")
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Predicate to determine if this Span intersects another Span
156
+ */
157
+ public intersects(that: Pick<Span, "start" | "end">): boolean {
158
+ return this.start < that.end && this.end > that.start
159
+ }
160
+
161
+ /**
162
+ * Predicate to determine if this Span covers another Span
163
+ */
164
+ public covers(that: Pick<Span, "start" | "end">): boolean {
165
+ return this.start <= that.start && this.end >= that.end
166
+ }
167
+
168
+ /**
169
+ * Returns the distance between two Spans
170
+ *
171
+ * @todo Use graph to find prev and next spans for a more accurate result
172
+ * @todo Or base 'distance' on word distance (slop) rather than characters
173
+ */
174
+ public distance(that: Pick<Span, "start" | "end">): number {
175
+ if (this.intersects(that)) return 0
176
+
177
+ if (this.end < that.start) {
178
+ return that.start - this.end
179
+ }
180
+
181
+ return this.start - that.end
182
+ }
183
+
184
+ /**
185
+ * Returns the coverage of the span, i.e. the number of characters covered by the span and its children.
186
+ */
187
+ public get coverage(): number {
188
+ if (this.children.size) {
189
+ return (
190
+ Iterator
191
+ // ---
192
+ .from(this.children)
193
+ .reduce((sum, child) => sum + (child.end - child.start), 0)
194
+ )
195
+ }
196
+
197
+ return this.end - this.start
198
+ }
199
+
200
+ /**
201
+ * The combined languages of the span's children.
202
+ */
203
+ public get languages(): Displayable<ReadonlySet<LibPostalLanguageCode | Alpha3bLanguageCode>> {
204
+ // Spread children langs to the parent...
205
+ const languages: Displayable<Set<LibPostalLanguageCode | Alpha3bLanguageCode>> = new Set()
206
+ const displayNames = new Set<string>()
207
+
208
+ for (const child of this.children) {
209
+ for (const classification of child.classifications.values()) {
210
+ const childLanguages = classification.languages
211
+
212
+ if (!childLanguages) continue
213
+
214
+ if (childLanguages.displayName) {
215
+ displayNames.add(childLanguages.displayName)
216
+ }
217
+
218
+ for (const language of childLanguages) {
219
+ languages.add(language)
220
+ }
221
+ }
222
+ }
223
+
224
+ languages.displayName = displayNames.size ? Array.from(displayNames).join(", ") : undefined
225
+
226
+ return languages
227
+ }
228
+
229
+ /**
230
+ * Serialize the span to JSON.
231
+ */
232
+ public toJSON(): SerializedSpan {
233
+ return {
234
+ // [kSpanID]: this.id,
235
+ body: this.body,
236
+ start: this.start,
237
+ end: this.end,
238
+ normalized: this.normalized,
239
+ classifications: this.classifications.toJSON(),
240
+ children: Iterator.from(this.children)
241
+ .map((c) => c.toJSON())
242
+ .toArray(),
243
+ phrases: Iterator.from(this.phrases)
244
+ .map((p) => p.toJSON())
245
+ .toArray(),
246
+ } satisfies SerializedSpan
247
+ }
248
+
249
+ public override toString() {
250
+ const classifications = Array.from(this.classifications.keys()).join(", ")
251
+ const flags = Array.from(this.#flags).join(", ")
252
+
253
+ return `Span(${this.children.size}) "${this.body}" [${classifications}][${flags}]`
254
+ }
255
+
256
+ public [Symbol.for("nodejs.util.inspect.custom")]() {
257
+ return this.toString()
258
+ }
259
+
260
+ /**
261
+ * Connect siblings in the graph.
262
+ */
263
+ static connectSiblings(...spans: Span[]) {
264
+ for (const [i, span] of spans.entries()) {
265
+ if (spans[i - 1]) {
266
+ span.previousSiblings.add(spans[i - 1]!)
267
+ }
268
+
269
+ if (spans[i + 1]) {
270
+ span.nextSiblings.add(spans[i + 1]!)
271
+ }
272
+ }
273
+
274
+ return spans
275
+ }
276
+ }
277
+
278
+ export type SpanFlag = "ends_with_period" | "numeric" | "alpha" | "alphanumeric" | "numeral" | "punctuation"
279
+
280
+ /**
281
+ * Patterns to test and apply classifications to spans.
282
+ *
283
+ * Note that order here is important, as the first pattern that matches will be used.
284
+ */
285
+ export const PatternMatchers: readonly [pattern: RegExp, flag: SpanFlag][] = [
286
+ // Entirely numeric, i.e. contains only digits.
287
+ [/^\d+$/, "numeric"],
288
+
289
+ // Entirely special characters, i.e. contains only punctuation, symbols, or other non-alphanumeric characters.
290
+ [/^[@&/\\#,+()$~%.!^'";:*?[\]<>{}]+$/, "punctuation"],
291
+
292
+ // Entirely alpha, i.e. contains only letters.
293
+ [/^[A-Za-z\W]+$/, "alpha"],
294
+
295
+ // Entirely alphanumeric, i.e. contains only letters and digits.
296
+ [/^[A-Za-z0-9\W]+$/, "alphanumeric"],
297
+ ]
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ export * from "./Graph.ts"
8
+ export * from "./normalizer.ts"
9
+ export * from "./Span.ts"
@@ -0,0 +1,123 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import regenerate from "regenerate"
8
+
9
+ /**
10
+ * A pattern matching combining diacritical marks, variation selectors, and other characters that are often used in text
11
+ * normalization.
12
+ */
13
+ const CombiningDiacriticalPattern = regenerate()
14
+ .add(0x200d) // ZERO WIDTH JOINER (U+200D)
15
+ .addRange(0x0300, 0x036f) // Combining Diacritical Marks
16
+ .addRange(0x1ab0, 0x1aff) // Combining Diacritical Marks Extended
17
+ .addRange(0x1dc0, 0x1dff) // Combining Diacritical Marks Supplement
18
+ .addRange(0x20d0, 0x20ff) // Combining Diacritical Marks for Symbols
19
+ .addRange(0xfe00, 0xfe0f) // Variation Selectors
20
+ .addRange(0xfe20, 0xfe2f) // Combining Half Marks
21
+ .add(0x3099) // Combining Dakuten
22
+ .add(0x309a) // Combining Handakuten
23
+ .toRegExp("g")
24
+
25
+ export interface TextNormalizerReplaceClause {
26
+ from: string | RegExp
27
+ to: string
28
+ }
29
+
30
+ export interface TextNormalizerInit {
31
+ lowercase?: boolean
32
+ removeAccents?: boolean
33
+ removeHyphen?: boolean
34
+ removeSpaces?: boolean
35
+ minLength?: number
36
+ maxLength?: number
37
+ replace?: TextNormalizerReplaceClause[]
38
+ }
39
+
40
+ /**
41
+ * Normalizes text values, i.e. removes superfluous characters such as accents, hyphens, and spaces.
42
+ */
43
+ export class TextNormalizer implements TextNormalizerInit {
44
+ public readonly lowercase: boolean
45
+ public readonly removeAccents: boolean
46
+ public readonly removeHyphen: boolean
47
+ public readonly removeSpaces: boolean
48
+ public readonly replace: TextNormalizerReplaceClause[]
49
+ public readonly minLength?: number
50
+ public readonly maxLength?: number
51
+
52
+ constructor(init: TextNormalizerInit = {}) {
53
+ this.lowercase = init.lowercase ?? false
54
+ this.removeAccents = init.removeAccents ?? false
55
+ this.removeHyphen = init.removeHyphen ?? false
56
+ this.removeSpaces = init.removeSpaces ?? false
57
+ this.replace = init.replace ?? []
58
+ this.minLength = init.minLength
59
+ this.maxLength = init.maxLength
60
+ }
61
+
62
+ /**
63
+ * Perform text normalization on a given input.
64
+ */
65
+ public normalize(input: string): string {
66
+ input = input.trim()
67
+
68
+ for (const { from, to } of this.replace) {
69
+ input = input.replace(from, to)
70
+ }
71
+
72
+ if (this.lowercase) {
73
+ input = input.toLowerCase()
74
+ }
75
+
76
+ if (this.removeAccents) {
77
+ input = input
78
+ // We first normalize to NFKD to decompose any accented characters...
79
+ .normalize("NFKD")
80
+ // Then we remove the accented characters...
81
+ .replace(CombiningDiacriticalPattern, "")
82
+ // And finally we normalize to NFKC to recompose the string.
83
+ .normalize("NFKC")
84
+ }
85
+
86
+ if (this.removeHyphen) {
87
+ input = input.replace(/-/g, " ")
88
+ }
89
+
90
+ if (this.removeSpaces) {
91
+ input = input.replace(/ /g, "")
92
+ }
93
+
94
+ return input
95
+ }
96
+
97
+ /**
98
+ * Validate a given input against the defined validations.
99
+ */
100
+ public validate(input: string): boolean {
101
+ if (this.minLength && input.length < this.minLength) {
102
+ return false
103
+ }
104
+
105
+ if (this.maxLength && input.length > this.maxLength) {
106
+ return false
107
+ }
108
+
109
+ return true
110
+ }
111
+
112
+ public toJSON(): TextNormalizerInit {
113
+ return {
114
+ lowercase: this.lowercase,
115
+ removeAccents: this.removeAccents,
116
+ removeHyphen: this.removeHyphen,
117
+ removeSpaces: this.removeSpaces,
118
+ replace: this.replace,
119
+ minLength: this.minLength,
120
+ maxLength: this.maxLength,
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Download + alphabetize libpostal's `resources/dictionaries` — the per-language abbreviation,
7
+ * street-type, and synonym tables the normalizer expands against. Shallow-clones
8
+ * {@link https://github.com/openvenues/libpostal openvenues/libpostal}, sorts each dictionary file
9
+ * in place, and copies the `dictionaries/` tree next to this script.
10
+ *
11
+ * Replaces the bash `resources-download.sh`. `git clone` runs through zx's `$` (no clean native
12
+ * equivalent); everything else is `node:fs` / `node:os`. Sorting is done in-process with a plain
13
+ * code-point `Array.sort()`, which matches `LC_ALL=C sort` byte order — deterministic and free of
14
+ * the shell `sort`'s locale dependency (the original relied on the ambient locale).
15
+ *
16
+ * ## Usage
17
+ *
18
+ * ```sh
19
+ * mailwoman dev download libpostal-resources [--force]
20
+ * ```
21
+ *
22
+ * ## Flags
23
+ *
24
+ * - `--force` — delete an existing `./dictionaries` directory instead of erroring out
25
+ */
26
+
27
+ import { cp, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"
28
+ import { tmpdir } from "node:os"
29
+ import { join } from "node:path"
30
+
31
+ import { isDirectory } from "@mailwoman/core/fs"
32
+ import { resourceDictionaryPath } from "@mailwoman/core/utils"
33
+
34
+ const REPO_URL = "https://github.com/openvenues/libpostal.git"
35
+ const DICTIONARIES_DIR = resourceDictionaryPath("libpostal")
36
+
37
+ /**
38
+ * Sort a single dictionary file in place by code point (matching `LC_ALL=C sort`). Blank lines sort to the top, exactly
39
+ * as `sort` orders empty strings; a trailing newline is preserved.
40
+ */
41
+ async function sortFileInPlace(path: string): Promise<void> {
42
+ const text = await readFile(path, "utf8")
43
+ const hadTrailingNewline = text.endsWith("\n")
44
+ const lines = text.split("\n")
45
+
46
+ // Drop the empty element produced by a trailing newline so it isn't re-sorted as a blank line.
47
+ if (hadTrailingNewline) {
48
+ lines.pop()
49
+ }
50
+ lines.sort()
51
+ await writeFile(path, lines.join("\n") + (hadTrailingNewline ? "\n" : ""))
52
+ }
53
+
54
+ /**
55
+ * Shallow-clone libpostal, alphabetize each dictionary file, and install the tree at the checked-in
56
+ * `core/data/libpostal/dictionaries`. Refuses to clobber an existing tree unless `force`. zx is lazy-imported
57
+ * (dev-grade dependency — the pipeline convention).
58
+ */
59
+ export async function downloadLibpostalResources(
60
+ options: { force?: boolean } = {},
61
+ report?: (line: string) => void
62
+ ): Promise<void> {
63
+ // Guard the destination exactly as the bash version did: refuse to clobber unless --force.
64
+ if (await isDirectory(DICTIONARIES_DIR)) {
65
+ if (options.force) {
66
+ report?.("Warning: The dictionaries directory already exists. Deleting it due to --force flag.")
67
+ await rm(DICTIONARIES_DIR, { recursive: true, force: true })
68
+ } else {
69
+ // Guidance-grade refusal: suppress the stack so the CLI renders just the message
70
+ // (core can't import mailwoman/cli-kit's commandError — wrong dependency direction).
71
+ const error = new Error("The dictionaries directory already exists. Remove it first or pass --force.")
72
+ error.stack = error.message
73
+ throw error
74
+ }
75
+ }
76
+
77
+ const { $ } = await import("zx")
78
+ const tempDir = await mkdtemp(join(tmpdir(), "libpostal-"))
79
+
80
+ try {
81
+ const cloneDir = join(tempDir, "libpostal")
82
+ await $`git clone --depth 1 ${REPO_URL} ${cloneDir}`
83
+
84
+ const sourceDicts = join(cloneDir, "resources", "dictionaries")
85
+
86
+ // Alphabetize the contents of each dictionary file in place.
87
+ for (const entry of await readdir(sourceDicts, { withFileTypes: true })) {
88
+ if (entry.isFile()) {
89
+ await sortFileInPlace(join(sourceDicts, entry.name))
90
+ }
91
+ }
92
+
93
+ // Copy the (now-sorted) dictionaries tree into the checked-in data home.
94
+ await cp(sourceDicts, DICTIONARIES_DIR, { recursive: true })
95
+ } finally {
96
+ await rm(tempDir, { recursive: true, force: true })
97
+ }
98
+ }