@mailwoman/core 9.3.0 → 9.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.
Files changed (95) hide show
  1. package/lib/decoder/tree-shape.ts +3 -7
  2. package/lib/fs/readers.ts +12 -0
  3. package/lib/git.ts +26 -0
  4. package/lib/layers/coverage.ts +3 -2
  5. package/lib/layers/manifest.ts +2 -4
  6. package/lib/layers/schema.ts +0 -1
  7. package/lib/license/docs-site.ts +1 -15
  8. package/lib/license/obligations.ts +3 -0
  9. package/lib/license/status.ts +1 -1
  10. package/lib/module/resolve-from.ts +16 -4
  11. package/lib/objects.ts +9 -1
  12. package/lib/pipeline/client-result.ts +82 -0
  13. package/lib/pipeline/index.ts +1 -1
  14. package/lib/pipeline/runtime-pipeline.ts +1 -2
  15. package/lib/pipeline/types.ts +26 -16
  16. package/lib/resolver/index.ts +1 -0
  17. package/lib/resolver/lookup-types.ts +8 -0
  18. package/lib/resolver/placetype-map.ts +27 -0
  19. package/lib/resolver/types.ts +1 -0
  20. package/lib/strings/format.ts +15 -0
  21. package/lib/workspaces.ts +97 -0
  22. package/out/decoder/tree-shape.d.ts +3 -7
  23. package/out/decoder/tree-shape.d.ts.map +1 -1
  24. package/out/decoder/tree-shape.js +3 -7
  25. package/out/decoder/tree-shape.js.map +1 -1
  26. package/out/fs/readers.d.ts +6 -0
  27. package/out/fs/readers.d.ts.map +1 -1
  28. package/out/fs/readers.js +0 -8
  29. package/out/fs/readers.js.map +1 -1
  30. package/out/git.d.ts +15 -0
  31. package/out/git.d.ts.map +1 -1
  32. package/out/git.js +22 -0
  33. package/out/git.js.map +1 -1
  34. package/out/layers/coverage.d.ts +1 -1
  35. package/out/layers/coverage.d.ts.map +1 -1
  36. package/out/layers/coverage.js +1 -2
  37. package/out/layers/coverage.js.map +1 -1
  38. package/out/layers/manifest.d.ts +2 -2
  39. package/out/layers/manifest.d.ts.map +1 -1
  40. package/out/layers/manifest.js +2 -3
  41. package/out/layers/manifest.js.map +1 -1
  42. package/out/layers/schema.d.ts +0 -1
  43. package/out/layers/schema.d.ts.map +1 -1
  44. package/out/layers/schema.js +0 -3
  45. package/out/layers/schema.js.map +1 -1
  46. package/out/license/docs-site.d.ts +0 -6
  47. package/out/license/docs-site.d.ts.map +1 -1
  48. package/out/license/docs-site.js +1 -12
  49. package/out/license/docs-site.js.map +1 -1
  50. package/out/license/obligations.d.ts.map +1 -1
  51. package/out/license/obligations.js +3 -0
  52. package/out/license/obligations.js.map +1 -1
  53. package/out/license/status.js +1 -1
  54. package/out/license/status.js.map +1 -1
  55. package/out/module/resolve-from.d.ts +12 -3
  56. package/out/module/resolve-from.d.ts.map +1 -1
  57. package/out/module/resolve-from.js.map +1 -1
  58. package/out/objects.d.ts +6 -0
  59. package/out/objects.d.ts.map +1 -1
  60. package/out/objects.js +8 -1
  61. package/out/objects.js.map +1 -1
  62. package/out/pipeline/client-result.d.ts +84 -0
  63. package/out/pipeline/client-result.d.ts.map +1 -0
  64. package/out/pipeline/client-result.js +12 -0
  65. package/out/pipeline/client-result.js.map +1 -0
  66. package/out/pipeline/index.d.ts +1 -1
  67. package/out/pipeline/index.d.ts.map +1 -1
  68. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  69. package/out/pipeline/runtime-pipeline.js.map +1 -1
  70. package/out/pipeline/types.d.ts +21 -15
  71. package/out/pipeline/types.d.ts.map +1 -1
  72. package/out/pipeline/types.js.map +1 -1
  73. package/out/resolver/index.d.ts +1 -1
  74. package/out/resolver/index.d.ts.map +1 -1
  75. package/out/resolver/index.js +1 -1
  76. package/out/resolver/index.js.map +1 -1
  77. package/out/resolver/lookup-types.d.ts +8 -0
  78. package/out/resolver/lookup-types.d.ts.map +1 -1
  79. package/out/resolver/placetype-map.d.ts +7 -0
  80. package/out/resolver/placetype-map.d.ts.map +1 -1
  81. package/out/resolver/placetype-map.js +24 -0
  82. package/out/resolver/placetype-map.js.map +1 -1
  83. package/out/resolver/types.d.ts +1 -1
  84. package/out/resolver/types.d.ts.map +1 -1
  85. package/out/resolver/types.js +1 -1
  86. package/out/resolver/types.js.map +1 -1
  87. package/out/strings/format.d.ts +6 -0
  88. package/out/strings/format.d.ts.map +1 -1
  89. package/out/strings/format.js +12 -0
  90. package/out/strings/format.js.map +1 -1
  91. package/out/workspaces.d.ts +31 -0
  92. package/out/workspaces.d.ts.map +1 -0
  93. package/out/workspaces.js +67 -0
  94. package/out/workspaces.js.map +1 -0
  95. package/package.json +26 -7
@@ -93,10 +93,9 @@ export interface FlatTreeNode {
93
93
  /**
94
94
  * Flatten a tree to its nodes in SOURCE order — sorted by `start`, the same order `decodeAsTuples` means by it.
95
95
  *
96
- * The two copies this replaces (the demo's `demo-helpers.ts` and the `demo-cascade-smoke` mirror of it) relied on
97
- * TRAVERSAL order instead: depth-first onto a stack, then reversed. That coincides with source order only while every
98
- * parent's span precedes its children's, and the decoder does not promise it — measured, the two orders disagree on **7
99
- * of 10** ordinary addresses, always with a child ahead of its parent:
96
+ * A traversal-order walk (depth-first onto a stack, then reversed) is the obvious implementation and is wrong here: it
97
+ * coincides with source order only while every parent's span precedes its children's, and the decoder does not promise
98
+ * it — measured, the two orders disagree on **7 of 10** ordinary addresses, always with a child ahead of its parent:
100
99
  *
101
100
  * Queen Street, Bristol street_suffix@6 before street@0
102
101
  * Via Roma, 5, 50123 Firenze, … house_number@10 before street@0
@@ -104,9 +103,6 @@ export interface FlatTreeNode {
104
103
  *
105
104
  * Sorting is what the tuple projection already does, so this makes a rendered span list and `decodeAsTuples` agree by
106
105
  * construction rather than by luck.
107
- *
108
- * The smoke test could not import the demo's copy (that would be a `mailwoman` → `docs` project reference, and `docs`
109
- * already depends on `mailwoman`), which is why a third home was the only way to collapse them.
110
106
  */
111
107
  export function flattenTreeNodes(tree?: AddressTree | null): FlatTreeNode[] {
112
108
  if (!tree) return []
package/lib/fs/readers.ts CHANGED
@@ -306,6 +306,11 @@ export function readLocalTextFile<S extends Array<PathBuilderLike | URL>>(...pat
306
306
  return readFile(readTarget(pathSegments), "utf8")
307
307
  }
308
308
 
309
+ /**
310
+ * @deprecated Use `readLocalJSONFile` instead
311
+ */
312
+ export function readLocalJSONFile<_T = Record<string, unknown>>(path: `${string}/package.json`): Promise<never>
313
+
309
314
  /**
310
315
  * Read a local JSON file.
311
316
  *
@@ -313,7 +318,14 @@ export function readLocalTextFile<S extends Array<PathBuilderLike | URL>>(...pat
313
318
  *
314
319
  * @category Node
315
320
  * @category Files
321
+ * @see `readPackageJSON` in `#module/resolve-from` for a `package.json`, which answers the manifest shape and takes a
322
+ * package name as readily as a path.
316
323
  */
324
+ export function readLocalJSONFile<
325
+ T = Record<string, unknown>,
326
+ S extends Array<PathBuilderLike | URL> = Array<PathBuilderLike | URL>,
327
+ >(...pathSegments: S): Promise<T>
328
+
317
329
  export function readLocalJSONFile<
318
330
  T = Record<string, unknown>,
319
331
  S extends Array<PathBuilderLike | URL> = Array<PathBuilderLike | URL>,
package/lib/git.ts CHANGED
@@ -48,6 +48,32 @@ export async function dirtyTrackedFiles(repoRoot: PathBuilderLike, pathspecs: st
48
48
  return [...TextSpliterator.from(output)].map((line) => line.trimEnd()).filter((line) => line.length > 0)
49
49
  }
50
50
 
51
+ /**
52
+ * Every `git status --porcelain` line, staged and unstaged and untracked alike.
53
+ *
54
+ * The sibling {@linkcode dirtyTrackedFiles} answers a publish path's question — which committed files have moved — and
55
+ * excludes what a build creates. This answers a CACHE's question: has anything at all changed since a derived artifact
56
+ * was built. A key built from the narrower reading goes stale over a staged edit and over a new file, and a stale index
57
+ * reports that a helper written an hour ago does not exist.
58
+ */
59
+ export async function workingTreeStatus(repoRoot: PathBuilderLike, pathspecs: string[] = []): Promise<string[]> {
60
+ const scope = pathspecs.length ? ["--", ...pathspecs] : []
61
+ const output = await git(repoRoot, ["status", "--porcelain", ...scope])
62
+
63
+ return [...TextSpliterator.from(output)].map((line) => line.trimEnd()).filter((line) => line.length > 0)
64
+ }
65
+
66
+ /**
67
+ * The repo-relative paths that differ between two commits, added, modified, renamed or deleted alike, read
68
+ * NUL-delimited so an unusual path survives. Both commits must be present in the checkout: a shallow clone that lacks
69
+ * `base` fails here with git's own message rather than answering an empty list.
70
+ */
71
+ export async function changedFiles(repoRoot: PathBuilderLike, base: string, head: string): Promise<string[]> {
72
+ const output = await git(repoRoot, ["diff", "--name-only", "-z", base, head], 64 * 1024 * 1024)
73
+
74
+ return output.split("\0").filter((path) => path.length > 0)
75
+ }
76
+
51
77
  /**
52
78
  * Every tracked path, repo-relative, optionally narrowed by git pathspecs. Read NUL-delimited so a path with a newline
53
79
  * or a non-ASCII byte survives; the 64 MiB buffer covers this repository's listing several times over.
@@ -5,8 +5,9 @@
5
5
  * @file Coverage rows and the area check shared by the polygon-layer builders.
6
6
  */
7
7
 
8
- import { supportsExclusion, type CoverageCell } from "#layers/manifest"
9
- import { CoverageBasis } from "#layers/schema"
8
+ import { supportsExclusion, CoverageBasis } from "@mailwoman/evidence"
9
+
10
+ import type { CoverageCell } from "#layers/manifest"
10
11
 
11
12
  /**
12
13
  * The coverage rows for a layer whose coverage is `source_present`: one per cell the authority's own polygons reach,
@@ -8,10 +8,10 @@
8
8
  * corrupted layer fails loudly at open time rather than misbehaving downstream.
9
9
  */
10
10
 
11
- import { supportsExclusion } from "@mailwoman/evidence"
11
+ import { supportsExclusion, CoverageBasis } from "@mailwoman/evidence"
12
12
 
13
13
  import { parseJSONStrict } from "#json"
14
- import { CoverageBasis, LayerFreshnessPolicy, LayerTier, type LayerContractHandle } from "#layers/schema"
14
+ import { LayerFreshnessPolicy, LayerTier, type LayerContractHandle } from "#layers/schema"
15
15
  import { assertAdmissibleLicenseExpression } from "#license/obligations"
16
16
 
17
17
  /**
@@ -70,8 +70,6 @@ export interface CoverageCell {
70
70
  observedRows: number
71
71
  }
72
72
 
73
- export { requireExclusionBasis, supportsExclusion } from "@mailwoman/evidence"
74
-
75
73
  const BASES = new Set<string>(Object.values(CoverageBasis))
76
74
 
77
75
  /**
@@ -85,7 +85,6 @@ export interface LayerManifestTable {
85
85
 
86
86
  // Owned by @mailwoman/evidence so bdc, resolver and filer can check on the SAME FUNCTION rather than on matching copies
87
87
  // of the same three strings. The layer_coverage schema and its IO stay here.
88
- export { CoverageBasis } from "@mailwoman/evidence"
89
88
 
90
89
  export interface LayerCoverageTable {
91
90
  /**
@@ -8,27 +8,13 @@
8
8
  */
9
9
 
10
10
  import { $public } from "#env"
11
+ import { withoutTrailingSlashes } from "#strings/format"
11
12
 
12
13
  /**
13
14
  * The docs site when `MAILWOMAN_DOCS_URL` is unset.
14
15
  */
15
16
  export const DEFAULT_DOCS_URL = "https://mailwoman.ai"
16
17
 
17
- /**
18
- * An origin with its trailing slashes removed, so a path can be appended by concatenation. A loop rather than
19
- * `/\/+$/u`: the input is configuration, and a regex anchored after a repeated class backtracks in time quadratic in
20
- * the run of slashes it is handed.
21
- */
22
- export function withoutTrailingSlashes(url: string): string {
23
- let end = url.length
24
-
25
- while (end > 0 && url[end - 1] === "/") {
26
- end -= 1
27
- }
28
-
29
- return url.slice(0, end)
30
- }
31
-
32
18
  /**
33
19
  * The docs site's base URL with no trailing slash.
34
20
  */
@@ -52,6 +52,9 @@ const KNOWN_OBLIGATIONS: ReadonlyMap<string, readonly LicenseObligation[]> = new
52
52
  ["LicenseRef-USGov-Public-Domain", []],
53
53
  // Licence Ouverte 2.0 (etalab), BAN's elected license.
54
54
  ["etalab-2.0", [LicenseObligation.Attribution]],
55
+ // 政府資料開放授權條款-第1版, the Taiwanese civil-affairs address registers behind Overture-TW. Attribution is the
56
+ // condition of the grant itself: the license voids without the 顯名聲明, so the per-agency list travels with the data.
57
+ ["OGDL-Taiwan-1.0", [LicenseObligation.Attribution]],
55
58
  ["MIT", [LicenseObligation.Attribution]],
56
59
  ["Apache-2.0", [LicenseObligation.Attribution]],
57
60
  ])
@@ -14,8 +14,8 @@ import type { CacheRequestConfig } from "axios-cache-interceptor"
14
14
  import { APIClient, type APIClientConfig } from "#api/APIClient"
15
15
  import { $public } from "#env"
16
16
  import { ResourceError } from "#errors/schema"
17
- import { withoutTrailingSlashes } from "#license/docs-site"
18
17
  import { silentLogger } from "#logging/index"
18
+ import { withoutTrailingSlashes } from "#strings/format"
19
19
 
20
20
  /**
21
21
  * The license worker when `MAILWOMAN_LICENSE_URL` is unset.
@@ -47,22 +47,34 @@ export function resolvePackagePathFrom(base: string, packageName: string, ...seg
47
47
  return resolvePath(dirname(resolvePackageJSON(base, packageName)), ...segments)
48
48
  }
49
49
 
50
- export type PackageJSONLike<D extends object = object> = PackageJson & D
50
+ /**
51
+ * The `mailwoman` block this repository's own manifests may carry. A data-only weights overlay names the base package
52
+ * it shares `model.onnx` and `tokenizer.model` with, which is the field `@mailwoman/neural` follows to find them.
53
+ */
54
+ export interface MailwomanManifestFields {
55
+ mailwoman?: {
56
+ baseWeights?: string
57
+ }
58
+ }
59
+
60
+ export type PackageJSONLike<D extends object = MailwomanManifestFields> = PackageJson & D
51
61
 
52
62
  /**
53
63
  * Read and parse a package's `package.json`, given its path from {@link resolvePackageJSON}.
54
64
  */
55
- export async function readPackageJSON<D extends object = object>(manifestPath: string): Promise<PackageJSONLike<D>>
65
+ export async function readPackageJSON<D extends object = MailwomanManifestFields>(
66
+ manifestPath: string
67
+ ): Promise<PackageJSONLike<D>>
56
68
 
57
69
  /**
58
70
  * Read and parse a package's `package.json`, resolving the package from the caller's `import.meta.url`.
59
71
  */
60
- export async function readPackageJSON<D extends object = object>(
72
+ export async function readPackageJSON<D extends object = MailwomanManifestFields>(
61
73
  base: string,
62
74
  packageName: string
63
75
  ): Promise<PackageJSONLike<D>>
64
76
 
65
- export async function readPackageJSON<D extends object = object>(
77
+ export async function readPackageJSON<D extends object = MailwomanManifestFields>(
66
78
  first: string,
67
79
  packageName?: string
68
80
  ): Promise<PackageJSONLike<D>> {
package/lib/objects.ts CHANGED
@@ -6,9 +6,17 @@
6
6
  * Utility functions for working with objects.
7
7
  */
8
8
 
9
- import { isIterable } from "spliterator"
10
9
  import type { JsonObject } from "type-fest"
11
10
 
11
+ /**
12
+ * True when `value` carries `Symbol.iterator`: arrays, sets, maps, strings, generators. `null` and `undefined` answer
13
+ * false. The same predicate exists in `spliterator`, whose barrel also carries that library's Node fs, worker-thread
14
+ * and XLSX readers; this module is on the browser client's static import path, so it must not reach that barrel.
15
+ */
16
+ export function isIterable(value: unknown): value is Iterable<unknown> {
17
+ return Symbol.iterator in new Object(value)
18
+ }
19
+
12
20
  export function isPlainObject(value: unknown): value is Record<string, unknown> {
13
21
  return typeof value === "object" && value !== null && !Array.isArray(value)
14
22
  }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The parse result as a client renders it: what the browser runtime produces after classify + resolve, and what
7
+ * `@mailwoman/react` takes as input. One definition, because a producer and a renderer that each write the shape
8
+ * agree only by accident. Every field a stage may leave unset is optional here; a renderer that needs a value it
9
+ * cannot see shows absence, never a default.
10
+ */
11
+
12
+ export interface ParsedComponent {
13
+ tag: string
14
+ value?: unknown
15
+ confidence?: number
16
+ start?: number
17
+ end?: number
18
+ }
19
+
20
+ export interface ResolvedPlaceView {
21
+ id: number
22
+ name: string
23
+ placetype: string
24
+ lat: number
25
+ lon: number
26
+ score: number
27
+ bbox?: { minLat: number; maxLat: number; minLon: number; maxLon: number }
28
+ /**
29
+ * How the coordinate was reached when a street-tier lookup answered: a rooftop point, or an interpolation along the
30
+ * segment. Absent for a gazetteer place.
31
+ */
32
+ tier?: "address_point" | "interpolated"
33
+ uncertaintyM?: number
34
+ }
35
+
36
+ export interface DualRoleView {
37
+ id: number
38
+ name: string
39
+ placetype: string
40
+ relationshipType: string
41
+ role: string
42
+ }
43
+
44
+ export interface StageTiming {
45
+ shape: number
46
+ classify: number
47
+ resolve?: number
48
+ }
49
+
50
+ export interface FSTProvenance {
51
+ builtAt: string
52
+ stateCount: number
53
+ placeCount: number
54
+ importanceMatches: number
55
+ }
56
+
57
+ /**
58
+ * The query kind as a client shows it. `kind` is any string here, where the pipeline's own `QueryKindResult` carries
59
+ * the typed union, because a renderer must show a kind it does not know rather than refuse the result.
60
+ */
61
+ export interface KindView {
62
+ kind: string
63
+ confidence: number
64
+ alternatives: ReadonlyArray<{ kind: string; confidence: number }>
65
+ }
66
+
67
+ export interface ParseResult {
68
+ input: string
69
+ /**
70
+ * The decoder's `AddressTree`, opaque here so this module stays free of the decoder's types; a renderer that walks it
71
+ * imports `@mailwoman/core/decoder/types`.
72
+ */
73
+ tree: unknown
74
+ nodes: ParsedComponent[]
75
+ kindResult?: KindView
76
+ timing?: StageTiming
77
+ resolved: ResolvedPlaceView | null
78
+ candidates: ResolvedPlaceView[]
79
+ fstActive: boolean
80
+ fstProvenance?: FSTProvenance | null
81
+ dualRoles?: DualRoleView[]
82
+ }
@@ -27,8 +27,8 @@ export type {
27
27
  ClassifierOpts,
28
28
  FSTMatcherLike,
29
29
  InputMode,
30
+ LocaleDetector,
30
31
  LocaleHint,
31
- LocaleTag,
32
32
  MachinePreferences,
33
33
  NormalizedInputLite,
34
34
  PhraseGrouper,
@@ -21,7 +21,6 @@ import type {
21
21
  FSTMatcherLike,
22
22
  InputMode,
23
23
  LocaleHint,
24
- LocaleTag,
25
24
  NormalizedInputLite,
26
25
  PhraseProposal,
27
26
  PipelineFault,
@@ -193,7 +192,7 @@ function emptyQueryShape(): QueryShapeLite {
193
192
  async function defaultDetectLocale(
194
193
  _input: NormalizedInputLite,
195
194
  _shape: QueryShapeLite,
196
- opts?: { hint?: LocaleTag }
195
+ opts?: { hint?: Intl.UnicodeBCP47LocaleIdentifier }
197
196
  ): Promise<LocaleHint> {
198
197
  const locale = opts?.hint ?? "und"
199
198
 
@@ -17,13 +17,11 @@ import type { AddressTree } from "#decoder/types"
17
17
  import type { ResolveOpts, Resolver, ResolverBackend } from "#resolver/types"
18
18
  import type { Section } from "#types/classifier"
19
19
 
20
- export type LocaleTag = string
21
-
22
20
  /**
23
21
  * Independent host/browser preferences. A timezone is evidence, never a locale conversion.
24
22
  */
25
23
  export interface MachinePreferences {
26
- locale?: LocaleTag
24
+ locale?: Intl.UnicodeBCP47LocaleIdentifier
27
25
  timeZone?: string
28
26
  }
29
27
 
@@ -37,7 +35,8 @@ export type UserLocation = { lat: number; lon: number } | { country: string } |
37
35
  * so this is a PURE PASSTHROUGH: core never constructs or inspects it — it threads the value verbatim from
38
36
  * {@link PipelineOpts.placetypePair} into {@link ClassifierOpts.placetypePair}, and on into the neural classifier's
39
37
  * `parse` opts, where it is typed concretely (`PlacetypePairPriorOpts | false`). The browser demo produces it via
40
- * `neural-web`'s `LoadResult.selectPairIndexForText`. `undefined` (the default) is the byte-stable no-prior decode.
38
+ * `@mailwoman/neural/web-loader`'s `LoadResult.selectPairIndexForText`. `undefined` (the default) is the byte-stable
39
+ * no-prior decode.
41
40
  */
42
41
  export type PlacetypePairPassthrough = object | false
43
42
 
@@ -45,7 +44,7 @@ export type PlacetypePairPassthrough = object | false
45
44
  * Common opts threaded through every stage.
46
45
  */
47
46
  export interface PipelineOpts {
48
- locale?: LocaleTag
47
+ locale?: Intl.UnicodeBCP47LocaleIdentifier
49
48
  userLocation?: UserLocation
50
49
  /**
51
50
  * Explicit input register (operator Decision A / GTM B10 — see {@link InputMode}). When unset the pipeline derives it
@@ -74,9 +73,9 @@ export interface PipelineOpts {
74
73
  /**
75
74
  * Placetype-pair prior (placetype-pair-prior arc, #1278) — an opaque, per-parse decode-channel handle threaded
76
75
  * verbatim to `ClassifierOpts.placetypePair` (and on to the neural classifier's `parse`). The browser demo derives it
77
- * per input via `neural-web`'s `LoadResult.selectPairIndexForText` (locale-hint over the text shape) so a GB/NZ input
78
- * gets its dependent_locality-resurrecting prior while a US/FR input stays byte-stable. `undefined` (default) = no
79
- * prior. See {@link PlacetypePairPassthrough}.
76
+ * per input via `@mailwoman/neural/web-loader`'s `LoadResult.selectPairIndexForText` (locale-hint over the text
77
+ * shape) so a GB/NZ input gets its dependent_locality-resurrecting prior while a US/FR input stays byte-stable.
78
+ * `undefined` (default) = no prior. See {@link PlacetypePairPassthrough}.
80
79
  */
81
80
  placetypePair?: PlacetypePairPassthrough
82
81
  /**
@@ -128,9 +127,9 @@ export interface QueryShapeLite {
128
127
  * Detected (or asserted) locale + alternatives.
129
128
  */
130
129
  export interface LocaleHint {
131
- locale: LocaleTag
130
+ locale: Intl.UnicodeBCP47LocaleIdentifier
132
131
  confidence: number
133
- alternatives: ReadonlyArray<{ locale: LocaleTag; confidence: number }>
132
+ alternatives: ReadonlyArray<{ locale: Intl.UnicodeBCP47LocaleIdentifier; confidence: number }>
134
133
  source: "caller" | "environment" | "machine" | "detected" | "ensemble"
135
134
  /**
136
135
  * Diagnostic provenance for inferred preferences. Locale and timezone remain independent signals.
@@ -138,7 +137,7 @@ export interface LocaleHint {
138
137
  evidence?: {
139
138
  intlLocale?: string
140
139
  timeZone?: string
141
- environmentLocale?: string
140
+ environmentLocale?: Intl.UnicodeBCP47LocaleIdentifier
142
141
  }
143
142
  }
144
143
 
@@ -522,6 +521,21 @@ export interface AddressClassifier {
522
521
  parse(text: string, opts?: ClassifierOpts): Promise<AddressTree>
523
522
  }
524
523
 
524
+ /**
525
+ * The Stage-2 locale detector the coordinator calls: the normalized input and its shape in, a {@link LocaleHint} out.
526
+ * The caller's hint wins outright; an environment locale sits below it and above inferred machine preferences.
527
+ * `@mailwoman/locale-hint` implements it over the query shape alone.
528
+ */
529
+ export type LocaleDetector = (
530
+ input: NormalizedInputLite,
531
+ shape: QueryShapeLite,
532
+ opts?: {
533
+ hint?: Intl.UnicodeBCP47LocaleIdentifier
534
+ machinePreferences?: MachinePreferences
535
+ environmentLocale?: Intl.UnicodeBCP47LocaleIdentifier
536
+ }
537
+ ) => Promise<LocaleHint>
538
+
525
539
  /**
526
540
  * Injectable stage implementations. All optional — when a stage is absent, the coordinator either skips it (resolver)
527
541
  * or substitutes a no-op stub (normalize / queryShape / `@mailwoman/locale-check` stage / kind classifier). The
@@ -531,11 +545,7 @@ export interface AddressClassifier {
531
545
  export interface RuntimePipelineStages {
532
546
  normalize?: (raw: string, opts?: { locale?: string }) => NormalizedInputLite
533
547
  computeQueryShape?: (input: NormalizedInputLite | string, opts?: { locale?: string }) => QueryShapeLite
534
- detectLocale?: (
535
- input: NormalizedInputLite,
536
- shape: QueryShapeLite,
537
- opts?: { hint?: LocaleTag; machinePreferences?: MachinePreferences; environmentLocale?: LocaleTag }
538
- ) => Promise<LocaleHint>
548
+ detectLocale?: LocaleDetector
539
549
  classifyKind?: (input: NormalizedInputLite, shape: QueryShapeLite, locale: LocaleHint) => Promise<QueryKindResult>
540
550
  /**
541
551
  * Coarse country router (#244). A `(normalizedText) → { country, confidence, posterior? }` predictor (a
@@ -50,6 +50,7 @@ export {
50
50
  expandPlacetypeFilter,
51
51
  hardCountrySafelistFromCoverage,
52
52
  isPlacetypeFallback,
53
+ placetypeMapForCountry,
53
54
  } from "#resolver/types"
54
55
 
55
56
  export type {
@@ -44,6 +44,14 @@ export interface AddressPointLookup {
44
44
  number: string
45
45
  postcode?: string
46
46
  locality?: string
47
+ /**
48
+ * The parse's `region` and `subregion` spans, for a register whose rows carry neither postcode nor locality. The
49
+ * Taiwanese register scopes a point by 縣市 and 鄉鎮市區 (`臺北市` / `中正區`), which the parse tags `region` and `subregion`;
50
+ * a reader built on that register composes its locality key from the pair. Every other reader ignores both, so the
51
+ * Latin path is byte-stable.
52
+ */
53
+ region?: string
54
+ subregion?: string
47
55
  /**
48
56
  * Optional bbox scope (`minLat`/`maxLat`/`minLon`/`maxLon`), tried AFTER postcode/locality. For extracts whose
49
57
  * points carry no postcode/locality of their own (OSM addr nodes often don't) but DO carry a coordinate — the
@@ -44,6 +44,33 @@ export const DEFAULT_PLACETYPE_MAP: PlacetypeMap = {
44
44
  postcode: "postalcode",
45
45
  }
46
46
 
47
+ /**
48
+ * Where a country's WOF typing of a tier departs from {@link DEFAULT_PLACETYPE_MAP}, the entries that differ. The map
49
+ * names the tier by tag; WOF names it by placetype, and the two agree for most countries and not for all.
50
+ *
51
+ * - **TW** — 鄉鎮市區, the tier below the 縣市 that the parse tags `subregion`, is `locality` or `localadmin` in WOF for 164 of
52
+ * the 178 held-out districts the candidate table carries and `county` for 14 (the census in
53
+ * `docs/records/evals/2026-09-08-v8-cjk-regs.md` §5). Under the default `county` band `臺北市中正區` reached nothing and
54
+ * the admin tier fell to the 縣市. The `locality` group admits `localadmin` too, the rule the JP `municipality` tag
55
+ * already relies on, and the exact-type preference in ranking keeps a `locality` row ahead of a same-name
56
+ * `localadmin` row.
57
+ */
58
+ const COUNTRY_PLACETYPE_OVERRIDES: Readonly<Record<string, PlacetypeMap>> = {
59
+ tw: { subregion: "locality" },
60
+ }
61
+
62
+ /**
63
+ * The placetype map for a resolve scoped to `countryCode` (ISO alpha-2, any case): the default map with the country's
64
+ * overrides applied, or the default map itself when the country has none or is unknown. The identity of the default
65
+ * object is preserved in that case, so a caller comparing maps to decide whether a second resolve is needed reads
66
+ * "unchanged" correctly.
67
+ */
68
+ export function placetypeMapForCountry(countryCode: string | null | undefined): PlacetypeMap {
69
+ const overrides = countryCode ? COUNTRY_PLACETYPE_OVERRIDES[countryCode.toLowerCase()] : undefined
70
+
71
+ return overrides ? { ...DEFAULT_PLACETYPE_MAP, ...overrides } : DEFAULT_PLACETYPE_MAP
72
+ }
73
+
47
74
  /**
48
75
  * Placetype-equivalence groups for lookup FILTERING. WOF splits a single addressing tier across several placetypes, but
49
76
  * an address's span can name ANY of them. A backend that filters to the one "obvious" placetype makes the equivalents
@@ -46,6 +46,7 @@ export {
46
46
  expandPlacetypeFilter,
47
47
  isPlacetypeFallback,
48
48
  PLACETYPE_FILTER_GROUPS,
49
+ placetypeMapForCountry,
49
50
  type PlacetypeMap,
50
51
  } from "#resolver/placetype-map"
51
52
 
@@ -12,3 +12,18 @@
12
12
  export function normalizeWhitespace(text: string): string {
13
13
  return text.replaceAll(/\s+/gu, " ").trim()
14
14
  }
15
+
16
+ /**
17
+ * The text with its trailing slashes removed: an origin a path can be appended to by concatenation, or a pathname with
18
+ * a trailing slash forgiven. A loop rather than `/\/+$/u`: a regex anchored after a repeated class backtracks in time
19
+ * quadratic in the run of slashes it is handed, and the input is configuration or a URL the browser was given.
20
+ */
21
+ export function withoutTrailingSlashes(text: string): string {
22
+ let end = text.length
23
+
24
+ while (end > 0 && text[end - 1] === "/") {
25
+ end -= 1
26
+ }
27
+
28
+ return text.slice(0, end)
29
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The root manifest's `workspaces` field, expanded to the directories it names. Yarn accepts globs in that field and
7
+ * the repository writes `packages/*` beside the literal `docs`; every reader that walks the workspaces goes through
8
+ * here so a glob is expanded once, the same way, and a literal entry that names no manifest is an error rather than
9
+ * an empty result. Only a single trailing `*` segment is supported: the repository never writes another shape, and
10
+ * a pattern this reader cannot expand must refuse, because "matched nothing" would read as "no workspaces".
11
+ */
12
+
13
+ import { type PathBuilderLike, resolvePath } from "path-ts"
14
+
15
+ import { readDirectoryEntries, tryStat } from "#fs/readers"
16
+ import { readPackageJSON } from "#module/resolve-from"
17
+
18
+ const TRAILING_STAR = /^(?<parent>[^*]+)\/\*$/u
19
+
20
+ async function isWorkspaceDirectory(repoRoot: PathBuilderLike, directory: string): Promise<boolean> {
21
+ return (await tryStat(resolvePath(repoRoot, directory, "package.json"))) !== null
22
+ }
23
+
24
+ export interface ReadWorkspaceDirectoriesOptions {
25
+ /**
26
+ * Skip a literal entry whose directory carries no manifest instead of failing. A checkout at an older ref may predate
27
+ * a workspace the field names; a reader that resolves that ref's own tree wants absence, not an error.
28
+ *
29
+ * @default false
30
+ */
31
+ tolerateMissing?: boolean
32
+ }
33
+
34
+ /**
35
+ * Repo-relative workspace directories, in the field's order: a literal entry stays where it is, and a `parent/*` entry
36
+ * expands to every child of `parent` that carries a `package.json`, sorted by name.
37
+ */
38
+ export async function readWorkspaceDirectories(
39
+ repoRoot: PathBuilderLike,
40
+ options: ReadWorkspaceDirectoriesOptions = {}
41
+ ): Promise<string[]> {
42
+ const manifest = await readPackageJSON(resolvePath(repoRoot, "package.json"))
43
+ // The field is either the pattern array or yarn's object form, which nests the same patterns under `packages`.
44
+ const entries = Array.isArray(manifest.workspaces) ? manifest.workspaces : (manifest.workspaces?.packages ?? [])
45
+
46
+ if (!entries.length) throw new Error(`${resolvePath(repoRoot, "package.json")} declares no workspaces`)
47
+
48
+ const directories: string[] = []
49
+
50
+ for (const entry of entries) {
51
+ if (!entry.includes("*")) {
52
+ if (!(await isWorkspaceDirectory(repoRoot, entry))) {
53
+ if (options.tolerateMissing) continue
54
+
55
+ throw new Error(`workspace ${entry} has no package.json under ${String(repoRoot)}`)
56
+ }
57
+
58
+ directories.push(entry)
59
+
60
+ continue
61
+ }
62
+
63
+ const parent = TRAILING_STAR.exec(entry)?.groups?.["parent"]
64
+
65
+ if (!parent) throw new Error(`workspace pattern ${JSON.stringify(entry)} is not a single trailing "*" segment`)
66
+
67
+ // Only a directory can be a workspace; a file beside them (a README) is skipped before anything is stat-ed under it.
68
+ const children = (await readDirectoryEntries(resolvePath(repoRoot, parent)))
69
+ .filter((dirent) => dirent.isDirectory())
70
+ .map((dirent) => dirent.name)
71
+ .toSorted()
72
+
73
+ const matched: string[] = []
74
+
75
+ for (const child of children) {
76
+ const directory = `${parent}/${child}`
77
+
78
+ if (await isWorkspaceDirectory(repoRoot, directory)) {
79
+ matched.push(directory)
80
+ }
81
+ }
82
+
83
+ if (!matched.length)
84
+ throw new Error(`workspace pattern ${JSON.stringify(entry)} matched no directory with a package.json`)
85
+
86
+ directories.push(...matched)
87
+ }
88
+
89
+ return [...new Set(directories)]
90
+ }
91
+
92
+ /**
93
+ * True when `directory` is one of the workspaces the field names, expanded.
94
+ */
95
+ export async function isRegisteredWorkspace(repoRoot: PathBuilderLike, directory: string): Promise<boolean> {
96
+ return (await readWorkspaceDirectories(repoRoot)).includes(directory)
97
+ }