@mailwoman/registry 11.1.0 → 11.2.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 (122) hide show
  1. package/README.md +18 -3
  2. package/data/manifests/artifacts.json +35 -0
  3. package/data/manifests/coverage.json +63 -0
  4. package/data/manifests/sources.lock.json +12 -0
  5. package/data/normalized/language-subtags.json +18518 -0
  6. package/lib/artifacts/bcp47/extlang.fixture.json +260 -0
  7. package/lib/artifacts/bcp47/extlang.ts +32 -0
  8. package/lib/artifacts/bcp47/grandfathered.fixture.json +28 -0
  9. package/lib/artifacts/bcp47/grandfathered.ts +32 -0
  10. package/lib/artifacts/bcp47/language.fixture.json +8278 -0
  11. package/lib/artifacts/bcp47/language.ts +32 -0
  12. package/lib/artifacts/bcp47/redundant.fixture.json +69 -0
  13. package/lib/artifacts/bcp47/redundant.ts +32 -0
  14. package/lib/artifacts/bcp47/region.fixture.json +307 -0
  15. package/lib/artifacts/bcp47/region.ts +32 -0
  16. package/lib/artifacts/bcp47/script.fixture.json +227 -0
  17. package/lib/artifacts/bcp47/script.ts +32 -0
  18. package/lib/artifacts/bcp47/variant.fixture.json +141 -0
  19. package/lib/artifacts/bcp47/variant.ts +32 -0
  20. package/lib/bcp47/subtag-index.ts +65 -0
  21. package/lib/bcp47/tag.ts +301 -0
  22. package/lib/errors.ts +11 -1
  23. package/lib/index.ts +8 -2
  24. package/lib/iso15924/codes.ts +169 -0
  25. package/lib/iso15924/unicode-script.ts +124 -0
  26. package/lib/iso639/languages.ts +88 -0
  27. package/lib/types.ts +58 -0
  28. package/out/artifacts/bcp47/extlang.d.ts +21 -0
  29. package/out/artifacts/bcp47/extlang.d.ts.map +1 -0
  30. package/out/artifacts/bcp47/extlang.fixture.json +260 -0
  31. package/out/artifacts/bcp47/extlang.js +17 -0
  32. package/out/artifacts/bcp47/extlang.js.map +1 -0
  33. package/out/artifacts/bcp47/grandfathered.d.ts +21 -0
  34. package/out/artifacts/bcp47/grandfathered.d.ts.map +1 -0
  35. package/out/artifacts/bcp47/grandfathered.fixture.json +28 -0
  36. package/out/artifacts/bcp47/grandfathered.js +17 -0
  37. package/out/artifacts/bcp47/grandfathered.js.map +1 -0
  38. package/out/artifacts/bcp47/language.d.ts +21 -0
  39. package/out/artifacts/bcp47/language.d.ts.map +1 -0
  40. package/out/artifacts/bcp47/language.fixture.json +8278 -0
  41. package/out/artifacts/bcp47/language.js +17 -0
  42. package/out/artifacts/bcp47/language.js.map +1 -0
  43. package/out/artifacts/bcp47/redundant.d.ts +21 -0
  44. package/out/artifacts/bcp47/redundant.d.ts.map +1 -0
  45. package/out/artifacts/bcp47/redundant.fixture.json +69 -0
  46. package/out/artifacts/bcp47/redundant.js +17 -0
  47. package/out/artifacts/bcp47/redundant.js.map +1 -0
  48. package/out/artifacts/bcp47/region.d.ts +21 -0
  49. package/out/artifacts/bcp47/region.d.ts.map +1 -0
  50. package/out/artifacts/bcp47/region.fixture.json +307 -0
  51. package/out/artifacts/bcp47/region.js +17 -0
  52. package/out/artifacts/bcp47/region.js.map +1 -0
  53. package/out/artifacts/bcp47/script.d.ts +21 -0
  54. package/out/artifacts/bcp47/script.d.ts.map +1 -0
  55. package/out/artifacts/bcp47/script.fixture.json +227 -0
  56. package/out/artifacts/bcp47/script.js +17 -0
  57. package/out/artifacts/bcp47/script.js.map +1 -0
  58. package/out/artifacts/bcp47/variant.d.ts +21 -0
  59. package/out/artifacts/bcp47/variant.d.ts.map +1 -0
  60. package/out/artifacts/bcp47/variant.fixture.json +141 -0
  61. package/out/artifacts/bcp47/variant.js +17 -0
  62. package/out/artifacts/bcp47/variant.js.map +1 -0
  63. package/out/bcp47/subtag-index.d.ts +22 -0
  64. package/out/bcp47/subtag-index.d.ts.map +1 -0
  65. package/out/bcp47/subtag-index.js +43 -0
  66. package/out/bcp47/subtag-index.js.map +1 -0
  67. package/out/bcp47/tag.d.ts +47 -0
  68. package/out/bcp47/tag.d.ts.map +1 -0
  69. package/out/bcp47/tag.js +218 -0
  70. package/out/bcp47/tag.js.map +1 -0
  71. package/out/errors.d.ts +4 -0
  72. package/out/errors.d.ts.map +1 -1
  73. package/out/errors.js.map +1 -1
  74. package/out/index.d.ts +8 -2
  75. package/out/index.d.ts.map +1 -1
  76. package/out/index.js +4 -1
  77. package/out/index.js.map +1 -1
  78. package/out/iso15924/codes.d.ts +57 -0
  79. package/out/iso15924/codes.d.ts.map +1 -0
  80. package/out/iso15924/codes.js +133 -0
  81. package/out/iso15924/codes.js.map +1 -0
  82. package/out/iso15924/unicode-script.d.ts +10 -0
  83. package/out/iso15924/unicode-script.d.ts.map +1 -0
  84. package/out/iso15924/unicode-script.js +103 -0
  85. package/out/iso15924/unicode-script.js.map +1 -0
  86. package/out/iso639/languages.d.ts +40 -0
  87. package/out/iso639/languages.d.ts.map +1 -0
  88. package/out/iso639/languages.js +54 -0
  89. package/out/iso639/languages.js.map +1 -0
  90. package/out/sdk/fetch.d.ts +5 -1
  91. package/out/sdk/fetch.d.ts.map +1 -1
  92. package/out/sdk/fetch.js +18 -4
  93. package/out/sdk/fetch.js.map +1 -1
  94. package/out/sdk/fetch.run.js +17 -3
  95. package/out/sdk/fetch.run.js.map +1 -1
  96. package/out/sdk/sources.d.ts +1 -1
  97. package/out/sdk/sources.d.ts.map +1 -1
  98. package/out/sdk/sources.js +18 -1
  99. package/out/sdk/sources.js.map +1 -1
  100. package/out/tools/generate.run.js +51 -4
  101. package/out/tools/generate.run.js.map +1 -1
  102. package/out/tools/language-subtags.d.ts +59 -0
  103. package/out/tools/language-subtags.d.ts.map +1 -0
  104. package/out/tools/language-subtags.js +145 -0
  105. package/out/tools/language-subtags.js.map +1 -0
  106. package/out/tools/normalize.d.ts +3 -1
  107. package/out/tools/normalize.d.ts.map +1 -1
  108. package/out/tools/normalize.js.map +1 -1
  109. package/out/tools/normalize.run.js +22 -3
  110. package/out/tools/normalize.run.js.map +1 -1
  111. package/out/types.d.ts +57 -0
  112. package/out/types.d.ts.map +1 -1
  113. package/out/types.js +12 -0
  114. package/out/types.js.map +1 -1
  115. package/package.json +6 -3
  116. package/sdk/fetch.run.ts +19 -3
  117. package/sdk/fetch.ts +26 -5
  118. package/sdk/sources.ts +19 -1
  119. package/tools/generate.run.ts +57 -4
  120. package/tools/language-subtags.ts +195 -0
  121. package/tools/normalize.run.ts +25 -3
  122. package/tools/normalize.ts +1 -1
@@ -0,0 +1,301 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * BCP 47 language tags (RFC 5646): parsing, validation against the IANA Language
6
+ * Subtag Registry, and canonicalization.
7
+ *
8
+ * A tag is accepted when it is well-formed (section 2.1) and valid (section 2.2.9):
9
+ * every language, extlang, script, region and variant subtag is registered, an extlang's
10
+ * prefix matches the language, and no variant or extension singleton repeats.
11
+ *
12
+ * The canonical form (section 4.5) replaces a deprecated subtag or tag with its preferred value,
13
+ * replaces a language-extlang pair with the extlang's preferred value (`zh-yue` becomes `yue`),
14
+ * orders extensions by singleton, and applies the case conventions: `ja-Jpan-JP`.
15
+ * It keeps a script the language would suppress, so `ja-Jpan` stays `ja-Jpan`.
16
+ */
17
+
18
+ import { extlangSubtagRows } from "#artifacts/bcp47/extlang"
19
+ import { grandfatheredSubtagRows } from "#artifacts/bcp47/grandfathered"
20
+ import { languageSubtagRows } from "#artifacts/bcp47/language"
21
+ import { redundantSubtagRows } from "#artifacts/bcp47/redundant"
22
+ import { regionSubtagRows } from "#artifacts/bcp47/region"
23
+ import { scriptSubtagRows } from "#artifacts/bcp47/script"
24
+ import { variantSubtagRows } from "#artifacts/bcp47/variant"
25
+ import { lazySubtagIndex } from "#bcp47/subtag-index"
26
+ import { type Parsed, ParseFailure } from "#errors"
27
+ import type { BCP47 } from "#types"
28
+
29
+ const languages = lazySubtagIndex(languageSubtagRows)
30
+ const extlangs = lazySubtagIndex(extlangSubtagRows)
31
+ const scripts = lazySubtagIndex(scriptSubtagRows)
32
+ const regions = lazySubtagIndex(regionSubtagRows)
33
+ const variants = lazySubtagIndex(variantSubtagRows)
34
+ const grandfatheredTags = lazySubtagIndex(grandfatheredSubtagRows)
35
+ const redundantTags = lazySubtagIndex(redundantSubtagRows)
36
+
37
+ /**
38
+ * A parsed tag in canonical form.
39
+ */
40
+ export interface LanguageTag {
41
+ tag: BCP47.LanguageTag
42
+ /**
43
+ * The primary language subtag, such as `ja`.
44
+ *
45
+ * An irregular grandfathered tag without a preferred value, such as `i-default`,
46
+ * holds the whole tag here.
47
+ * A private-use tag such as `x-whatever` holds an empty string.
48
+ */
49
+ language: string
50
+ script: string | null
51
+ region: string | null
52
+ variants: readonly string[]
53
+ /**
54
+ * Each extension with its singleton, such as `u-ca-gregory`, ordered by singleton.
55
+ */
56
+ extensions: readonly string[]
57
+ /**
58
+ * The private-use sequence with its `x-` prefix, or `null`.
59
+ */
60
+ privateUse: string | null
61
+ }
62
+
63
+ // The subtag grammars of RFC 5646, section 2.1, over a lowercased tag.
64
+ const SUBTAG = /^[a-z0-9]{1,8}$/
65
+ const LANGUAGE = /^(?:[a-z]{2,3}|[a-z]{5,8})$/
66
+ const SHORT_LANGUAGE = /^[a-z]{2,3}$/
67
+ const EXTLANG = /^[a-z]{3}$/
68
+ const SCRIPT = /^[a-z]{4}$/
69
+ const REGION = /^(?:[a-z]{2}|[0-9]{3})$/
70
+ const VARIANT = /^(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3})$/
71
+ const SINGLETON = /^[0-9a-z]$/
72
+ const EXTENSION_BODY = /^[a-z0-9]{2,8}$/
73
+
74
+ /**
75
+ * The grammar admits up to three extlang subtags after a two- or three-letter language.
76
+ */
77
+ const MAX_EXTLANGS = 3
78
+
79
+ function refuse(input: string, reason: ParseFailure, part?: string): Parsed<LanguageTag> {
80
+ return part ? { ok: false, reason, input, part } : { ok: false, reason, input }
81
+ }
82
+
83
+ function titleCase(subtag: string): string {
84
+ return subtag.charAt(0).toUpperCase() + subtag.slice(1)
85
+ }
86
+
87
+ function compose(parts: Omit<LanguageTag, "tag">): BCP47.LanguageTag {
88
+ return [parts.language, parts.script, parts.region, ...parts.variants, ...parts.extensions, parts.privateUse]
89
+ .filter((part): part is string => typeof part === "string" && part !== "")
90
+ .join("-") as BCP47.LanguageTag
91
+ }
92
+
93
+ /**
94
+ * Parses, validates and canonicalizes a BCP 47 tag in any case.
95
+ *
96
+ * A refusal reports `shape` for an ill-formed tag and `not-found-in-snapshot` for a well-formed
97
+ * tag with an unregistered or misplaced subtag, with the offending subtag as `part`.
98
+ */
99
+ export function parseLanguageTag(input: string): Parsed<LanguageTag> {
100
+ const lower = input.toLowerCase()
101
+ const grandfathered = grandfatheredTags().get(lower)
102
+
103
+ if (grandfathered) {
104
+ if (grandfathered.preferredValue) return parseLanguageTag(grandfathered.preferredValue)
105
+
106
+ return {
107
+ ok: true,
108
+ value: {
109
+ tag: grandfathered.subtag as BCP47.LanguageTag,
110
+ language: grandfathered.subtag,
111
+ script: null,
112
+ region: null,
113
+ variants: [],
114
+ extensions: [],
115
+ privateUse: null,
116
+ },
117
+ }
118
+ }
119
+
120
+ const redundant = redundantTags().get(lower)
121
+
122
+ if (redundant?.preferredValue) return parseLanguageTag(redundant.preferredValue)
123
+
124
+ const subtags = lower.split("-")
125
+
126
+ if (subtags.some((subtag) => !SUBTAG.test(subtag))) return refuse(input, ParseFailure.Shape)
127
+
128
+ let position = 0
129
+ const at = (): string | undefined => subtags[position]
130
+ const matches = (grammar: RegExp): boolean => grammar.test(at() ?? "")
131
+
132
+ if (at() === "x") {
133
+ if (!subtags[1]) return refuse(input, ParseFailure.Shape)
134
+
135
+ const privateUse = subtags.join("-")
136
+
137
+ return {
138
+ ok: true,
139
+ value: {
140
+ tag: privateUse as BCP47.LanguageTag,
141
+ language: "",
142
+ script: null,
143
+ region: null,
144
+ variants: [],
145
+ extensions: [],
146
+ privateUse,
147
+ },
148
+ }
149
+ }
150
+
151
+ let language = at()
152
+
153
+ if (!language || !LANGUAGE.test(language)) return refuse(input, ParseFailure.Shape)
154
+
155
+ const languageRow = languages().get(language)
156
+
157
+ if (!languageRow) return refuse(input, ParseFailure.NotFound, language)
158
+
159
+ language = languageRow.preferredValue ?? language
160
+
161
+ position++
162
+
163
+ // One extlang is valid.
164
+ // The grammar admits three, so a second is well-formed and refused as invalid.
165
+ const extlangsSeen: string[] = []
166
+
167
+ while (SHORT_LANGUAGE.test(subtags[0]!) && matches(EXTLANG)) {
168
+ extlangsSeen.push(at()!)
169
+
170
+ position++
171
+ }
172
+
173
+ if (extlangsSeen.length > MAX_EXTLANGS) return refuse(input, ParseFailure.Shape)
174
+
175
+ if (extlangsSeen.length > 1) return refuse(input, ParseFailure.NotFound, extlangsSeen[1])
176
+
177
+ const extlang = extlangsSeen[0]
178
+
179
+ if (extlang) {
180
+ const extlangRow = extlangs().get(extlang)
181
+
182
+ if (!extlangRow || extlangRow.prefixes?.[0] !== subtags[0]) return refuse(input, ParseFailure.NotFound, extlang)
183
+
184
+ language = extlangRow.preferredValue ?? extlang
185
+ }
186
+
187
+ let script: string | null = null
188
+
189
+ if (matches(SCRIPT)) {
190
+ const row = scripts().get(at()!)
191
+
192
+ if (!row) return refuse(input, ParseFailure.NotFound, at())
193
+
194
+ script = titleCase(row.preferredValue ?? at()!)
195
+
196
+ position++
197
+ }
198
+
199
+ let region: string | null = null
200
+
201
+ if (matches(REGION)) {
202
+ const row = regions().get(at()!)
203
+
204
+ if (!row) return refuse(input, ParseFailure.NotFound, at())
205
+
206
+ region = (row.preferredValue ?? at()!).toUpperCase()
207
+
208
+ position++
209
+ }
210
+
211
+ const variantsSeen: string[] = []
212
+
213
+ while (at()) {
214
+ const subtag = at()!
215
+
216
+ if (!VARIANT.test(subtag)) break
217
+
218
+ const row = variants().get(subtag)
219
+
220
+ if (!row) return refuse(input, ParseFailure.NotFound, subtag)
221
+
222
+ const canonical = row.preferredValue ?? subtag
223
+
224
+ if (variantsSeen.includes(canonical)) return refuse(input, ParseFailure.NotFound, subtag)
225
+
226
+ variantsSeen.push(canonical)
227
+
228
+ position++
229
+ }
230
+
231
+ const extensions: string[] = []
232
+ const singletons = new Set<string>()
233
+ let privateUse: string | null = null
234
+
235
+ while (at()) {
236
+ const singleton = at()!
237
+
238
+ if (!SINGLETON.test(singleton)) return refuse(input, ParseFailure.Shape, singleton)
239
+
240
+ position++
241
+
242
+ const body: string[] = []
243
+
244
+ if (singleton === "x") {
245
+ while (at()) {
246
+ body.push(at()!)
247
+
248
+ position++
249
+ }
250
+
251
+ if (!body.length) return refuse(input, ParseFailure.Shape, singleton)
252
+
253
+ privateUse = ["x", ...body].join("-")
254
+
255
+ break
256
+ }
257
+
258
+ while (matches(EXTENSION_BODY)) {
259
+ body.push(at()!)
260
+
261
+ position++
262
+ }
263
+
264
+ if (!body.length) return refuse(input, ParseFailure.Shape, singleton)
265
+
266
+ if (singletons.has(singleton)) return refuse(input, ParseFailure.NotFound, singleton)
267
+
268
+ singletons.add(singleton)
269
+ extensions.push([singleton, ...body].join("-"))
270
+ }
271
+
272
+ extensions.sort()
273
+
274
+ const parts = { language, script, region, variants: variantsSeen, extensions, privateUse }
275
+
276
+ return { ok: true, value: { tag: compose(parts), ...parts } }
277
+ }
278
+
279
+ /**
280
+ * Whether `input` is a valid tag already in canonical form.
281
+ */
282
+ export function isLanguageTag(input: string): input is BCP47.LanguageTag {
283
+ const parsed = parseLanguageTag(input)
284
+
285
+ return parsed.ok && parsed.value.tag === input
286
+ }
287
+
288
+ /**
289
+ * The script a tag's text is written in: its explicit script subtag,
290
+ * else its language's suppressed script, else `null`.
291
+ *
292
+ * `ja-Jpan` and `ja` both give `Jpan`; `zh` gives `null`, because Chinese is written
293
+ * in `Hans` or `Hant` and the registry suppresses neither.
294
+ */
295
+ export function impliedScript(tag: LanguageTag): BCP47.ScriptCode | null {
296
+ if (tag.script) return tag.script as BCP47.ScriptCode
297
+
298
+ const suppressed = languages().get(tag.language)?.suppressScript
299
+
300
+ return suppressed ? (suppressed as BCP47.ScriptCode) : null
301
+ }
package/lib/errors.ts CHANGED
@@ -29,7 +29,17 @@ export type ParseFailure = (typeof ParseFailure)[keyof typeof ParseFailure]
29
29
  /**
30
30
  * A structured parse result: the branded value, or why the input was refused.
31
31
  */
32
- export type Parsed<T> = { ok: true; value: T } | { ok: false; reason: ParseFailure; input: string }
32
+ export type Parsed<T> =
33
+ | { ok: true; value: T }
34
+ | {
35
+ ok: false
36
+ reason: ParseFailure
37
+ input: string
38
+ /**
39
+ * The part of a compound input that was refused, such as one subtag of a BCP 47 tag.
40
+ */
41
+ part?: string
42
+ }
33
43
 
34
44
  /**
35
45
  * Reports which refusal a fixed-length grammar gives an input, or `null` when the shape passes.
package/lib/index.ts CHANGED
@@ -12,11 +12,15 @@
12
12
  * Import a subpath such as `@mailwoman/registry/iso3166/alpha2` when a bundle must retain one table only.
13
13
  */
14
14
 
15
+ export type { LanguageTag } from "#bcp47/tag"
16
+ export { impliedScript, isLanguageTag, parseLanguageTag } from "#bcp47/tag"
15
17
  export type { ParseFailure, Parsed } from "#errors"
16
18
  export { getAirportByIATA, airportsInCountry, airportRecordCount, airportRecordsHeader } from "#iata/airports/records"
17
19
  export { isAirportCode, parseAirportCode } from "#iata/airports/validate"
18
20
  export type { ArtifactInspection } from "#inspect"
19
21
  export { inspectArtifact } from "#inspect"
22
+ export type { ScriptRecord } from "#iso15924/codes"
23
+ export { getScript, isScriptCode, isWrittenInScript, parseScriptCode, unicodeScriptsOf } from "#iso15924/codes"
20
24
  export { isCountryCodeAlpha2, parseCountryCodeAlpha2 } from "#iso3166/alpha2"
21
25
  export { isCountryCodeAlpha3, parseCountryCodeAlpha3 } from "#iso3166/alpha3"
22
26
 
@@ -29,9 +33,11 @@ export {
29
33
  } from "#iso3166/records"
30
34
 
31
35
  export { alpha2ForAlpha3, alpha2ForNumeric, alpha3ForAlpha2 } from "#iso3166/relations"
36
+ export type { LanguageRecord } from "#iso639/languages"
37
+ export { getLanguage, isLanguageSubtag, parseLanguageSubtag } from "#iso639/languages"
32
38
  export type { Normalization } from "#normalize"
33
39
  export { canonicalSpelling } from "#normalize"
34
40
  export type { CodeMatch } from "#overlap/country-airport"
35
41
  export { interpretCountryOrAirportCode, isCountryAirportCollision } from "#overlap/country-airport"
36
- export type { AirportRecord, CountryRecord, IATA, ICAO, ISO } from "#types"
37
- export { AirportCountryStatus, CountryStatus } from "#types"
42
+ export type { AirportRecord, BCP47, CountryRecord, IATA, ICAO, ISO, SubtagRow } from "#types"
43
+ export { AirportCountryStatus, CountryStatus, SubtagType } from "#types"
@@ -0,0 +1,169 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * ISO 15924 script codes, read from the script subtags of the IANA Language Subtag Registry.
6
+ *
7
+ * An import of this module retains the 225-row script table and no language or region row.
8
+ */
9
+
10
+ import { scriptSubtagRows } from "#artifacts/bcp47/script"
11
+ import { lazySubtagIndex } from "#bcp47/subtag-index"
12
+ import { type Parsed, ParseFailure } from "#errors"
13
+ import type { BCP47 } from "#types"
14
+
15
+ const index = lazySubtagIndex(scriptSubtagRows)
16
+
17
+ const CANONICAL = /^[A-Z][a-z]{3}$/
18
+ const LETTERS = /^[A-Za-z]{4}$/
19
+
20
+ /**
21
+ * One script as the registry describes it.
22
+ */
23
+ export interface ScriptRecord {
24
+ code: BCP47.ScriptCode
25
+ /**
26
+ * The registry's first description, such as `Japanese (alias for Han + Hiragana + Katakana)`.
27
+ */
28
+ name: string
29
+ descriptions: readonly string[]
30
+ /**
31
+ * The date the registry deprecated the code, or `null`.
32
+ */
33
+ deprecated: string | null
34
+ }
35
+
36
+ /**
37
+ * Whether `input` is a script code the registry holds, in its canonical title case.
38
+ *
39
+ * `Latn` and `Jpan` are.
40
+ * `latn`, `LATN` and `Latin` are not.
41
+ */
42
+ export function isScriptCode(input: string): input is BCP47.ScriptCode {
43
+ return CANONICAL.test(input) && index().get(input) !== null
44
+ }
45
+
46
+ /**
47
+ * The branded script code, or the reason the input was refused.
48
+ */
49
+ export function parseScriptCode(input: string): Parsed<BCP47.ScriptCode> {
50
+ if (!LETTERS.test(input)) return { ok: false, reason: ParseFailure.Shape, input }
51
+
52
+ if (!CANONICAL.test(input)) return { ok: false, reason: ParseFailure.Case, input }
53
+
54
+ if (!isScriptCode(input)) return { ok: false, reason: ParseFailure.NotFound, input }
55
+
56
+ return { ok: true, value: input }
57
+ }
58
+
59
+ /**
60
+ * The record of a canonical script code, or `null`.
61
+ */
62
+ export function getScript(code: string): ScriptRecord | null {
63
+ if (!CANONICAL.test(code)) return null
64
+
65
+ const row = index().get(code)
66
+
67
+ if (!row) return null
68
+
69
+ return {
70
+ code: code as BCP47.ScriptCode,
71
+ name: row.descriptions[0] ?? code,
72
+ descriptions: row.descriptions,
73
+ deprecated: row.deprecated ?? null,
74
+ }
75
+ }
76
+
77
+ /**
78
+ * ISO 15924 codes that name a combination or a variant of Unicode scripts, mapped to the
79
+ * Unicode Script property values (short aliases) whose characters they cover.
80
+ *
81
+ * Unicode encodes the characters of a variant code, such as Fraktur `Latf`, under the base script.
82
+ * A combined code, such as Japanese `Jpan`, covers several scripts at once.
83
+ */
84
+ const UNICODE_SCRIPT_EXPANSIONS: Readonly<Record<string, readonly string[]>> = {
85
+ Jpan: ["Hani", "Hira", "Kana"],
86
+ Kore: ["Hang", "Hani"],
87
+ Hans: ["Hani"],
88
+ Hant: ["Hani"],
89
+ Hanb: ["Hani", "Bopo"],
90
+ Hrkt: ["Hira", "Kana"],
91
+ Latf: ["Latn"],
92
+ Latg: ["Latn"],
93
+ Aran: ["Arab"],
94
+ Cyrs: ["Cyrl"],
95
+ Syre: ["Syrc"],
96
+ Syrj: ["Syrc"],
97
+ Syrn: ["Syrc"],
98
+ Geok: ["Geor"],
99
+ }
100
+
101
+ function isUnicodeScriptValue(code: string): boolean {
102
+ try {
103
+ new RegExp(`\\p{Script=${code}}`, "u")
104
+
105
+ return true
106
+ } catch {
107
+ return false
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The Unicode Script property values whose characters a script code covers.
113
+ *
114
+ * `Jpan` gives `Hani`, `Hira` and `Kana`, and `Latn` gives `Latn`.
115
+ * A code with no Unicode script of its own, such as `Zmth` (mathematical notation)
116
+ * or a private-use code, gives an empty list.
117
+ *
118
+ * The runtime's regular-expression engine decides which values it knows.
119
+ */
120
+ export function unicodeScriptsOf(code: BCP47.ScriptCode): readonly string[] {
121
+ const expanded = UNICODE_SCRIPT_EXPANSIONS[code]
122
+
123
+ if (expanded) return expanded
124
+
125
+ return isUnicodeScriptValue(code) ? [code] : []
126
+ }
127
+
128
+ /**
129
+ * Whether every letter in `text` belongs to one of the scripts the code covers.
130
+ *
131
+ * Digits, punctuation, spaces and other non-letters are ignored, so `ニューヨーク州 10001` is written in `Jpan`.
132
+ * A text without letters returns `false`, because it shows no script at all.
133
+ *
134
+ * Common and Inherited letters, such as the prolonged sound mark `ー` in `ニューヨーク`,
135
+ * are accepted beside any script and don't count as evidence of one.
136
+ *
137
+ * Letters of an `alsoAccepted` script pass without counting, so `金龍酒家, 12 Gerrard Street`
138
+ * is written in `Latn` when `Hani` is also accepted: the Latin letters make up
139
+ * the address, and the Han name sits inside it.
140
+ */
141
+ export function isWrittenInScript(
142
+ text: string,
143
+ code: BCP47.ScriptCode,
144
+ alsoAccepted: readonly BCP47.ScriptCode[] = []
145
+ ): boolean {
146
+ const scripts = unicodeScriptsOf(code)
147
+
148
+ if (!scripts.length) return false
149
+
150
+ const own = scriptClass(scripts)
151
+ const accepted = scriptClass([...alsoAccepted.flatMap(unicodeScriptsOf), "Zyyy", "Zinh"])
152
+ let letters = 0
153
+
154
+ for (const character of text) {
155
+ if (!/\p{L}|\p{M}/u.test(character)) continue
156
+
157
+ if (own.test(character)) {
158
+ letters++
159
+ } else if (!accepted.test(character)) {
160
+ return false
161
+ }
162
+ }
163
+
164
+ return letters > 0
165
+ }
166
+
167
+ function scriptClass(scripts: readonly string[]): RegExp {
168
+ return new RegExp(`^[${scripts.map((script) => `\\p{Script=${script}}`).join("")}]$`, "u")
169
+ }
@@ -0,0 +1,124 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The ISO 15924 script of a code point, from the Unicode Script property of the runtime.
6
+ *
7
+ * The answer is the registry's own code: `Latn`, `Grek`, `Hani`, `Deva`.
8
+ * `Zyyy` marks a Common code point (digits and punctuation), `Zinh` an Inherited one
9
+ * (a combining mark), and `Zzzz` a code point that has no script in the runtime's Unicode version.
10
+ *
11
+ * # The Unicode version is the runtime's
12
+ *
13
+ * The tables are the regular-expression engine's `\p{Script=…}` classes, so they add no byte to a bundle.
14
+ * The answer for a code point that a later Unicode version assigned depends on
15
+ * the runtime that runs the call: a Worker, a browser and Node can report `Zzzz`
16
+ * for a script that a newer one reports by name.
17
+ *
18
+ * The test of this module pins the answers for a fixed list of code points.
19
+ *
20
+ * The candidates are the registry's script codes that the runtime's regular-expression
21
+ * engine also names as a Script value, so the set follows both tables.
22
+ * A code point of a Unicode script that the registry omits reports `Zzzz`.
23
+ *
24
+ * The lookup costs one array read for ASCII, and one cached read for a code point seen before.
25
+ */
26
+
27
+ import { scriptSubtagRows } from "#artifacts/bcp47/script"
28
+ import type { BCP47 } from "#types"
29
+
30
+ /**
31
+ * The scripts tried first, because most addresses are written in them.
32
+ * The rest follow in the registry's order.
33
+ */
34
+ const COMMON_FIRST = [
35
+ "Zyyy",
36
+ "Zinh",
37
+ "Latn",
38
+ "Hani",
39
+ "Cyrl",
40
+ "Arab",
41
+ "Hang",
42
+ "Hira",
43
+ "Kana",
44
+ "Grek",
45
+ "Deva",
46
+ "Thai",
47
+ "Hebr",
48
+ ]
49
+
50
+ /**
51
+ * The most code points the cache holds before it starts again.
52
+ */
53
+ const CACHE_LIMIT = 65_536
54
+
55
+ let matcher: { readonly pattern: RegExp; readonly codes: readonly BCP47.ScriptCode[] } | null = null
56
+
57
+ const cache = new Map<number, BCP47.ScriptCode>()
58
+
59
+ function isScriptValue(code: string): boolean {
60
+ try {
61
+ new RegExp(`\\p{Script=${code}}`, "u")
62
+
63
+ return true
64
+ } catch {
65
+ return false
66
+ }
67
+ }
68
+
69
+ function build(): NonNullable<typeof matcher> {
70
+ const known = scriptSubtagRows()
71
+ .map((row) => row.subtag)
72
+ .filter((code) => /^[A-Z][a-z]{3}$/.test(code) && isScriptValue(code))
73
+
74
+ const present = new Set(known)
75
+ const first = COMMON_FIRST.filter((code) => present.has(code))
76
+ const codes = [...first, ...known.filter((code) => !first.includes(code))] as BCP47.ScriptCode[]
77
+
78
+ // Each script is one capture group, so one `exec` reports which group matched.
79
+ const pattern = new RegExp(codes.map((code) => `(\\p{Script=${code}})`).join("|"), "u")
80
+
81
+ return { pattern, codes }
82
+ }
83
+
84
+ /**
85
+ * The ISO 15924 script of a code point.
86
+ *
87
+ * @param codePoint A Unicode scalar value, from 0 to 0x10FFFF.
88
+ * @returns `Zyyy` for Common, `Zinh` for Inherited, and `Zzzz` when the runtime
89
+ * assigns the code point no registry script.
90
+ */
91
+ export function codePointScript(codePoint: number): BCP47.ScriptCode {
92
+ if (codePoint < 0x80) {
93
+ const lower = codePoint | 0x20
94
+
95
+ return (lower >= 0x61 && lower <= 0x7a ? "Latn" : "Zyyy") as BCP47.ScriptCode
96
+ }
97
+
98
+ const cached = cache.get(codePoint)
99
+
100
+ if (cached) return cached
101
+
102
+ matcher ??= build()
103
+
104
+ const found = matcher.pattern.exec(String.fromCodePoint(codePoint))
105
+ let script: BCP47.ScriptCode = "Zzzz" as BCP47.ScriptCode
106
+
107
+ if (found) {
108
+ for (let group = 1; group < found.length; group++) {
109
+ if (found[group] !== undefined) {
110
+ script = matcher.codes[group - 1]!
111
+
112
+ break
113
+ }
114
+ }
115
+ }
116
+
117
+ if (cache.size >= CACHE_LIMIT) {
118
+ cache.clear()
119
+ }
120
+
121
+ cache.set(codePoint, script)
122
+
123
+ return script
124
+ }