@chofter/geo 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -21,9 +21,9 @@ import { createGeo } from "@chofter/geo";
21
21
 
22
22
  const geo = createGeo();
23
23
  const places = await geo.search("IE", "dub", { limit: 5 });
24
- // [{ id: 2964574, name: "Dublin", region: "Leinster", country: "Ireland",
24
+ // [{ id: 2964574, name: "Dublin", region: "County Dublin", country: "Ireland",
25
25
  // countryCode: "IE", lat: 53.3331, lng: -6.2489, population: 1024027,
26
- // label: "Dublin, Leinster, Ireland" }, ...]
26
+ // label: "Dublin, County Dublin, Ireland" }, ...]
27
27
  ```
28
28
 
29
29
  Without a bundler, import it straight from the CDN:
@@ -74,12 +74,16 @@ Returns an object with:
74
74
  Munich) starts with the query, or has a later word that does. Case, accents
75
75
  and punctuation are ignored. Exact matches come first, then larger places.
76
76
  An empty query returns the largest places.
77
- - `countries()`: `[{ code, name, count }]` for a country picker.
77
+ - `countries()`: `[{ code, name, count, altNames? }]` for a country picker.
78
78
  - `preload(countryCode)`: fetches the country's index early, for example when
79
79
  the user picks a country.
80
80
 
81
- `countryCode` is an ISO 3166-1 alpha-2 code such as `"US"` or `"ie"`.
82
- Results include `matched` when the query matched an alternate name.
81
+ `countryCode` is an ISO 3166-1 alpha-2 code such as `"US"` or `"ie"`, or for the
82
+ UK one of its nations (`"GB-ENG"`, `"GB-SCT"`, `"GB-WLS"`, `"GB-NIR"`) or `"GB"`
83
+ for all four.
84
+ Results include `matched` when the query matched an alternate name,
85
+ `district` when another place in the country has the same name and region, and
86
+ `localName` when the country's own language has a different name for the place.
83
87
 
84
88
  ## Examples
85
89
 
@@ -97,36 +101,36 @@ await geo.search("IE", "dub", { limit: 3 });
97
101
  {
98
102
  "id": 2964574,
99
103
  "name": "Dublin",
100
- "region": "Leinster",
104
+ "region": "County Dublin",
101
105
  "country": "Ireland",
102
106
  "countryCode": "IE",
103
107
  "lat": 53.3331,
104
108
  "lng": -6.2489,
105
109
  "population": 1024027,
106
- "label": "Dublin, Leinster, Ireland"
110
+ "label": "Dublin, County Dublin, Ireland"
107
111
  },
108
112
  {
109
113
  "id": 2964690,
110
114
  "name": "Douglas",
111
- "region": "Munster",
115
+ "region": "County Cork",
112
116
  "country": "Ireland",
113
117
  "countryCode": "IE",
114
118
  "lat": 51.8744,
115
119
  "lng": -8.435,
116
120
  "population": 26883,
117
- "label": "Douglas, Munster, Ireland",
121
+ "label": "Douglas, County Cork, Ireland",
118
122
  "matched": "Dúbhglas"
119
123
  },
120
124
  {
121
125
  "id": 2966131,
122
126
  "name": "Blackrock",
123
- "region": "Leinster",
127
+ "region": "County Dublin",
124
128
  "country": "Ireland",
125
129
  "countryCode": "IE",
126
130
  "lat": 53.3015,
127
131
  "lng": -6.1778,
128
132
  "population": 8821,
129
- "label": "Blackrock, Leinster, Ireland",
133
+ "label": "Blackrock, County Dublin, Ireland",
130
134
  "matched": "Carraig Dubh"
131
135
  }
132
136
  ]
@@ -145,16 +149,39 @@ await geo.search("RU", "Москва", { limit: 1 });
145
149
 
146
150
  ```jsonc
147
151
  [
148
- { "name": "Munich", "label": "Munich, Bavaria, Germany", "lat": 48.1374, "lng": 11.5755, "matched": "München" /* … */ },
152
+ { "name": "Munich", "label": "Munich, Bavaria, Germany", "localName": "München", "matched": "München" /* … */ },
149
153
  { "name": "Münchenbernsdorf", "label": "Münchenbernsdorf, Thuringia, Germany" /* … */ }
150
154
  ]
151
155
  [
152
- { "name": "Moscow", "label": "Moscow, Moscow, Russia", "lat": 55.752, "lng": 37.6178, "matched": "Москва" /* … */ }
156
+ { "name": "Moscow", "label": "Moscow, Moscow, Russia", "localName": "Москва", "matched": "Москва" /* … */ }
153
157
  ]
154
158
  ```
155
159
 
156
160
  Accents are optional: `"munchen"` and `"sao pau"` work just as well.
157
161
 
162
+ ### Local names
163
+
164
+ `name` is in English where English has its own name for the place, and
165
+ otherwise in the local spelling in Latin letters. `localName` gives the name in
166
+ the country's own language, whatever you searched for:
167
+
168
+ ```js
169
+ (await geo.search("KR", "", { limit: 3 })).map((p) => [p.name, p.localName]);
170
+ ```
171
+
172
+ ```json
173
+ [
174
+ ["Seoul", "서울"],
175
+ ["Busan", "부산"],
176
+ ["Incheon", "인천"]
177
+ ]
178
+ ```
179
+
180
+ It is left out when there is nothing to add: when the country's first language
181
+ is English (the US, Ireland, India), when GeoNames has no name in it, or when it
182
+ is the same as `name` (Paris, Berlin). Countries with several languages use the
183
+ first one GeoNames lists, so Geneva's `localName` is German, "Genf".
184
+
158
185
  ### Same name, different places
159
186
 
160
187
  ```js
@@ -170,8 +197,45 @@ Accents are optional: `"munchen"` and `"sao pau"` work just as well.
170
197
  ]
171
198
  ```
172
199
 
173
- Use `region`, `lat` and `lng` (or `id`) to tell them apart. Exact matches come
174
- first, largest first.
200
+ Exact matches come first, largest first. When two places share a name and a
201
+ region, they also get a `district` (a county or district), and the label
202
+ includes it:
203
+
204
+ ```js
205
+ (await geo.search("US", "plantation", { limit: 3 })).map((p) => p.label);
206
+ ```
207
+
208
+ ```json
209
+ [
210
+ "Plantation, Broward County, Florida, United States",
211
+ "Plantation, Sarasota County, Florida, United States",
212
+ "Plantation, Monroe County, Florida, United States"
213
+ ]
214
+ ```
215
+
216
+ So `label` tells namesakes apart in nearly every case. A few small places share
217
+ their name, region and district too; use `lat` and `lng` (or `id`) for those.
218
+
219
+ ### Ireland and the UK
220
+
221
+ In Ireland the region is the county. The UK is four countries, England,
222
+ Scotland, Wales and Northern Ireland, with codes `GB-ENG`, `GB-SCT`, `GB-WLS`
223
+ and `GB-NIR`, and the region is the council area. Searching `"GB"`, which is
224
+ what browsers and IP lookups report, covers all four, and each result says
225
+ which nation it is in:
226
+
227
+ ```js
228
+ (await geo.search("IE", "blackrock", { limit: 2 })).map((p) => p.label);
229
+ (await geo.search("GB", "newport", { limit: 2 })).map((p) => [p.label, p.countryCode]);
230
+ ```
231
+
232
+ ```json
233
+ ["Blackrock, County Dublin, Ireland", "Blackrock, County Louth, Ireland"]
234
+ [
235
+ ["Newport, Newport, Wales", "GB-WLS"],
236
+ ["Newport, Isle of Wight, England", "GB-ENG"]
237
+ ]
238
+ ```
175
239
 
176
240
  ### Ranking: exact names, then prefixes and later words
177
241
 
@@ -221,11 +285,15 @@ await geo.countries();
221
285
  { "code": "AF", "name": "Afghanistan", "count": 319 },
222
286
  { "code": "AX", "name": "Aland Islands", "count": 21 },
223
287
  { "code": "AL", "name": "Albania", "count": 418 },
224
- // … 246 countries in all, sorted by name
288
+ // …
289
+ { "code": "GB-SCT", "name": "Scotland", "count": 667, "altNames": ["United Kingdom", "UK"] },
290
+ // … 249 in all, sorted by name
225
291
  ]
226
292
  ```
227
293
 
228
- `count` is the number of places in that country.
294
+ `count` is the number of places in that country. The UK's four nations are
295
+ listed instead of the UK itself, each with `altNames` "United Kingdom" and "UK", so
296
+ a picker that matches those can offer all four.
229
297
 
230
298
  ### No match and errors
231
299
 
package/dist/geo.d.ts CHANGED
@@ -2,14 +2,32 @@ export interface Place {
2
2
  /** GeoNames id. */
3
3
  id: number;
4
4
  name: string;
5
- /** First-level admin division (state, province, county), may be empty. */
5
+ /**
6
+ * First-level admin division (state, province), may be empty. In Ireland it
7
+ * is the county, and in the UK the council area.
8
+ */
6
9
  region: string;
10
+ /**
11
+ * Second-level admin division (county, district), set only when another place
12
+ * in the country has the same name and region.
13
+ */
14
+ district?: string;
15
+ /**
16
+ * The name in the country's own language, such as "서울" for Seoul or "München"
17
+ * for Munich. Absent when that language is English, GeoNames has no name in
18
+ * it, or it is the same as `name`.
19
+ */
20
+ localName?: string;
7
21
  country: string;
22
+ /**
23
+ * ISO 3166-1 alpha-2, except for the UK's nations, which use ISO 3166-2:
24
+ * "GB-ENG", "GB-SCT", "GB-WLS" and "GB-NIR" (also for a search of "GB").
25
+ */
8
26
  countryCode: string;
9
27
  lat: number;
10
28
  lng: number;
11
29
  population: number;
12
- /** "Name, Region, Country". */
30
+ /** "Name, Region, Country", or "Name, District, Region, Country" when `district` is set. */
13
31
  label: string;
14
32
  /** Set when the query matched an alternate name rather than `name`. */
15
33
  matched?: string;
@@ -19,6 +37,8 @@ export interface Country {
19
37
  code: string;
20
38
  name: string;
21
39
  count: number;
40
+ /** Other names to match in a country picker, such as "United Kingdom" and "UK" for England. */
41
+ altNames?: string[];
22
42
  }
23
43
 
24
44
  export interface GeoOptions {
@@ -1,4 +1,4 @@
1
- // @chofter/geo 0.1.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
1
+ // @chofter/geo 0.3.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
2
  (function () {
3
3
  "use strict";
4
4
  // Client for the static place-search files. No dependencies; works in browsers,
@@ -61,10 +61,15 @@ function fileKey(prefix) {
61
61
  }
62
62
 
63
63
  // A place in the JSON files is an array:
64
- // [name, region, lat, lng, population, id, altNames?]
64
+ // [name, region, lat, lng, population, id, altNames?, district?, localName?]
65
+ // `district` is set only when another place in the country has the same name and
66
+ // region. `localName` is the name in the country's own language, when that is not
67
+ // English and differs from `name`. Trailing items are left out; one that is
68
+ // missing before a present one is [] (altNames) or "".
65
69
  const NAME = 0;
66
70
  const POPULATION = 4;
67
71
  const ALT_NAMES = 6;
72
+ const LOCAL_NAME = 8;
68
73
 
69
74
  const EXACT_MATCH = 0;
70
75
  const PREFIX_MATCH = 1;
@@ -74,6 +79,9 @@ const NO_MATCH = -1;
74
79
  function prepare(records) {
75
80
  return records.map((record) => {
76
81
  const names = [record[NAME], ...(record[ALT_NAMES] || [])];
82
+ if (record[LOCAL_NAME]) {
83
+ names.push(record[LOCAL_NAME]);
84
+ }
77
85
  return { record, names, searchKeys: names.map(normalize) };
78
86
  });
79
87
  }
@@ -138,22 +146,39 @@ function createGeo(options = {}) {
138
146
  count: index.count,
139
147
  prefixFiles: new Set(index.shards),
140
148
  topPlaces: prepare(index.top),
149
+ // Set for a code covering several countries ("GB" for the UK's four
150
+ // nations): each region's country code, and each code's name.
151
+ parts: index.parts,
152
+ regionParts: index.regionParts,
141
153
  }));
142
154
  }
143
155
 
156
+ /** The country a place belongs to: its own part of `country`, if it has parts. */
157
+ function countryOf(country, region) {
158
+ const partCode = country.regionParts && country.regionParts[region];
159
+ return partCode ? { code: partCode, name: country.parts[partCode] } : country;
160
+ }
161
+
144
162
  function toResult(country, place, nameIndex) {
145
- const [name, region, lat, lng, population, id] = place.record;
163
+ const [name, region, lat, lng, population, id, , district, localName] = place.record;
164
+ const { code, name: countryName } = countryOf(country, region);
146
165
  const result = {
147
166
  id,
148
167
  name,
149
168
  region,
150
- country: country.name,
151
- countryCode: country.code,
169
+ country: countryName,
170
+ countryCode: code,
152
171
  lat,
153
172
  lng,
154
173
  population,
155
- label: [name, region, country.name].filter(Boolean).join(", "),
174
+ label: [name, district, region, countryName].filter(Boolean).join(", "),
156
175
  };
176
+ if (district) {
177
+ result.district = district;
178
+ }
179
+ if (localName) {
180
+ result.localName = localName;
181
+ }
157
182
  if (nameIndex > 0) {
158
183
  result.matched = place.names[nameIndex];
159
184
  }
@@ -203,10 +228,12 @@ function createGeo(options = {}) {
203
228
  return matches.slice(0, limit).map((match) => toResult(country, match.place, match.nameIndex));
204
229
  }
205
230
 
206
- /** Countries that have data: [{ code, name, count }]. */
231
+ /** Countries that have data: [{ code, name, count, altNames? }]. */
207
232
  function countries() {
208
233
  return load("countries.json", (rows) =>
209
- rows.map(([code, name, count]) => ({ code, name, count })),
234
+ rows.map(([code, name, count, altNames]) =>
235
+ altNames ? { code, name, count, altNames } : { code, name, count },
236
+ ),
210
237
  );
211
238
  }
212
239
 
@@ -1,2 +1,2 @@
1
- // @chofter/geo 0.1.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
- (()=>{var b={ß:"ss",æ:"ae",œ:"oe",ø:"o",đ:"d",ð:"d",þ:"th",ł:"l",ı:"i",ħ:"h"};function E(r){return String(r).toLowerCase().normalize("NFD").replace(/\p{M}+/gu,"").replace(/[ßæœøđðþłıħ]/g,(t)=>b[t]).replace(/['’‘ʼ`]/g,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function x(r,t){return Array.from(r).slice(0,t).join("")}function N(r){let t="";for(let i of r)if(/[a-z0-9]/.test(i))t+=i;else if(i===" ")t+="-";else t+="~"+i.codePointAt(0).toString(16);return t}var P=0,A=4,U=6,j=0,I=1,m=-1;function L(r){return r.map((t)=>{let i=[t[P],...t[U]||[]];return{record:t,names:i,searchKeys:i.map(E)}})}function O(r,t){if(r===t)return j;if(r.startsWith(t)||r.includes(" "+t))return I;return m}function z(r,t){let i=m,f=0;return r.searchKeys.forEach((p,g)=>{let u=O(p,t);if(u!==m&&(i===m||u<i))i=u,f=g}),{tier:i,nameIndex:f}}var D="https://geo.chofter.com/v1",R=10;function F(r={}){let t=String(r.baseUrl||D).replace(/\/+$/,""),i=r.fetch||globalThis.fetch.bind(globalThis),f=new Map;function p(e,n){let a=f.get(e);if(!a)a=i(`${t}/${e}`).then((o)=>{if(!o.ok)throw Error(`geo: ${e} returned ${o.status}`);return o.json()}).then(n),a.catch(()=>f.delete(e)),f.set(e,a);return a}function g(e){return p(`${e}/_.json`,(n)=>({code:e.toUpperCase(),name:n.name,depth:n.depth,count:n.count,prefixFiles:new Set(n.shards),topPlaces:L(n.top)}))}function u(e,n,a){let[o,s,h,T,d,c]=n.record,l={id:c,name:o,region:s,country:e.name,countryCode:e.code,lat:h,lng:T,population:d,label:[o,s,e.name].filter(Boolean).join(", ")};if(a>0)l.matched=n.names[a];return l}function w(e,n){let a=Math.min(e.depth,Array.from(n).length);for(let o=a;o>0;o--){let s=N(x(n,o));if(e.prefixFiles.has(s))return s}return null}async function C(e,n,a={}){let o=a.limit||R,s=await g(String(e).toLowerCase()),h=E(n||"");if(!h)return s.topPlaces.slice(0,o).map((c)=>u(s,c,0));let T=s.topPlaces;if(s.depth>0){let c=w(s,h);if(c===null)return[];T=await p(`${s.code.toLowerCase()}/${c}.json`,L)}let d=[];for(let c of T){let{tier:l,nameIndex:_}=z(c,h);if(l!==m)d.push({place:c,tier:l,nameIndex:_})}return d.sort((c,l)=>c.tier-l.tier||l.place.record[A]-c.place.record[A]),d.slice(0,o).map((c)=>u(s,c.place,c.nameIndex))}function M(){return p("countries.json",(e)=>e.map(([n,a,o])=>({code:n,name:a,count:o})))}function S(e){return g(String(e).toLowerCase()).then(()=>{return})}return{search:C,countries:M,preload:S}}globalThis.choftergeo={createGeo:F};})();
1
+ // @chofter/geo 0.3.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
+ (()=>{var j={ß:"ss",æ:"ae",œ:"oe",ø:"o",đ:"d",ð:"d",þ:"th",ł:"l",ı:"i",ħ:"h"};function w(c){return String(c).toLowerCase().normalize("NFD").replace(/\p{M}+/gu,"").replace(/[ßæœøđðþłıħ]/g,(e)=>j[e]).replace(/['’‘ʼ`]/g,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function I(c,e){return Array.from(c).slice(0,e).join("")}function x(c){let e="";for(let s of c)if(/[a-z0-9]/.test(s))e+=s;else if(s===" ")e+="-";else e+="~"+s.codePointAt(0).toString(16);return e}var z=0,F=4,D=6,M=8,R=0,y=1,d=-1;function P(c){return c.map((e)=>{let s=[e[z],...e[D]||[]];if(e[M])s.push(e[M]);return{record:e,names:s,searchKeys:s.map(w)}})}function H(c,e){if(c===e)return R;if(c.startsWith(e)||c.includes(" "+e))return y;return d}function B(c,e){let s=d,f=0;return c.searchKeys.forEach((u,g)=>{let p=H(u,e);if(p!==d&&(s===d||p<s))s=p,f=g}),{tier:s,nameIndex:f}}var G="https://geo.chofter.com/v1",X=10;function N(c={}){let e=String(c.baseUrl||G).replace(/\/+$/,""),s=c.fetch||globalThis.fetch.bind(globalThis),f=new Map;function u(t,n){let r=f.get(t);if(!r)r=s(`${e}/${t}`).then((i)=>{if(!i.ok)throw Error(`geo: ${t} returned ${i.status}`);return i.json()}).then(n),r.catch(()=>f.delete(t)),f.set(t,r);return r}function g(t){return u(`${t}/_.json`,(n)=>({code:t.toUpperCase(),name:n.name,depth:n.depth,count:n.count,prefixFiles:new Set(n.shards),topPlaces:P(n.top),parts:n.parts,regionParts:n.regionParts}))}function p(t,n){let r=t.regionParts&&t.regionParts[n];return r?{code:r,name:t.parts[r]}:t}function C(t,n,r){let[i,o,h,A,m,a,,l,L]=n.record,{code:U,name:E}=p(t,o),T={id:a,name:i,region:o,country:E,countryCode:U,lat:h,lng:A,population:m,label:[i,l,o,E].filter(Boolean).join(", ")};if(l)T.district=l;if(L)T.localName=L;if(r>0)T.matched=n.names[r];return T}function _(t,n){let r=Math.min(t.depth,Array.from(n).length);for(let i=r;i>0;i--){let o=x(I(n,i));if(t.prefixFiles.has(o))return o}return null}async function S(t,n,r={}){let i=r.limit||X,o=await g(String(t).toLowerCase()),h=w(n||"");if(!h)return o.topPlaces.slice(0,i).map((a)=>C(o,a,0));let A=o.topPlaces;if(o.depth>0){let a=_(o,h);if(a===null)return[];A=await u(`${o.code.toLowerCase()}/${a}.json`,P)}let m=[];for(let a of A){let{tier:l,nameIndex:L}=B(a,h);if(l!==d)m.push({place:a,tier:l,nameIndex:L})}return m.sort((a,l)=>a.tier-l.tier||l.place.record[F]-a.place.record[F]),m.slice(0,i).map((a)=>C(o,a.place,a.nameIndex))}function b(){return u("countries.json",(t)=>t.map(([n,r,i,o])=>o?{code:n,name:r,count:i,altNames:o}:{code:n,name:r,count:i}))}function O(t){return g(String(t).toLowerCase()).then(()=>{return})}return{search:S,countries:b,preload:O}}globalThis.choftergeo={createGeo:N};})();
package/dist/geo.js CHANGED
@@ -1,4 +1,4 @@
1
- // @chofter/geo 0.1.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
1
+ // @chofter/geo 0.3.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
2
  // Client for the static place-search files. No dependencies; works in browsers,
3
3
  // Node 18+, Workers and React Native.
4
4
  //
@@ -59,10 +59,15 @@ function fileKey(prefix) {
59
59
  }
60
60
 
61
61
  // A place in the JSON files is an array:
62
- // [name, region, lat, lng, population, id, altNames?]
62
+ // [name, region, lat, lng, population, id, altNames?, district?, localName?]
63
+ // `district` is set only when another place in the country has the same name and
64
+ // region. `localName` is the name in the country's own language, when that is not
65
+ // English and differs from `name`. Trailing items are left out; one that is
66
+ // missing before a present one is [] (altNames) or "".
63
67
  const NAME = 0;
64
68
  const POPULATION = 4;
65
69
  const ALT_NAMES = 6;
70
+ const LOCAL_NAME = 8;
66
71
 
67
72
  const EXACT_MATCH = 0;
68
73
  const PREFIX_MATCH = 1;
@@ -72,6 +77,9 @@ const NO_MATCH = -1;
72
77
  function prepare(records) {
73
78
  return records.map((record) => {
74
79
  const names = [record[NAME], ...(record[ALT_NAMES] || [])];
80
+ if (record[LOCAL_NAME]) {
81
+ names.push(record[LOCAL_NAME]);
82
+ }
75
83
  return { record, names, searchKeys: names.map(normalize) };
76
84
  });
77
85
  }
@@ -136,22 +144,39 @@ export function createGeo(options = {}) {
136
144
  count: index.count,
137
145
  prefixFiles: new Set(index.shards),
138
146
  topPlaces: prepare(index.top),
147
+ // Set for a code covering several countries ("GB" for the UK's four
148
+ // nations): each region's country code, and each code's name.
149
+ parts: index.parts,
150
+ regionParts: index.regionParts,
139
151
  }));
140
152
  }
141
153
 
154
+ /** The country a place belongs to: its own part of `country`, if it has parts. */
155
+ function countryOf(country, region) {
156
+ const partCode = country.regionParts && country.regionParts[region];
157
+ return partCode ? { code: partCode, name: country.parts[partCode] } : country;
158
+ }
159
+
142
160
  function toResult(country, place, nameIndex) {
143
- const [name, region, lat, lng, population, id] = place.record;
161
+ const [name, region, lat, lng, population, id, , district, localName] = place.record;
162
+ const { code, name: countryName } = countryOf(country, region);
144
163
  const result = {
145
164
  id,
146
165
  name,
147
166
  region,
148
- country: country.name,
149
- countryCode: country.code,
167
+ country: countryName,
168
+ countryCode: code,
150
169
  lat,
151
170
  lng,
152
171
  population,
153
- label: [name, region, country.name].filter(Boolean).join(", "),
172
+ label: [name, district, region, countryName].filter(Boolean).join(", "),
154
173
  };
174
+ if (district) {
175
+ result.district = district;
176
+ }
177
+ if (localName) {
178
+ result.localName = localName;
179
+ }
155
180
  if (nameIndex > 0) {
156
181
  result.matched = place.names[nameIndex];
157
182
  }
@@ -201,10 +226,12 @@ export function createGeo(options = {}) {
201
226
  return matches.slice(0, limit).map((match) => toResult(country, match.place, match.nameIndex));
202
227
  }
203
228
 
204
- /** Countries that have data: [{ code, name, count }]. */
229
+ /** Countries that have data: [{ code, name, count, altNames? }]. */
205
230
  function countries() {
206
231
  return load("countries.json", (rows) =>
207
- rows.map(([code, name, count]) => ({ code, name, count })),
232
+ rows.map(([code, name, count, altNames]) =>
233
+ altNames ? { code, name, count, altNames } : { code, name, count },
234
+ ),
208
235
  );
209
236
  }
210
237
 
package/dist/geo.min.js CHANGED
@@ -1,2 +1,2 @@
1
- // @chofter/geo 0.1.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
- var _={ß:"ss",æ:"ae",œ:"oe",ø:"o",đ:"d",ð:"d",þ:"th",ł:"l",ı:"i",ħ:"h"};function E(r){return String(r).toLowerCase().normalize("NFD").replace(/\p{M}+/gu,"").replace(/[ßæœøđðþłıħ]/g,(t)=>_[t]).replace(/['’‘ʼ`]/g,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function x(r,t){return Array.from(r).slice(0,t).join("")}function N(r){let t="";for(let i of r)if(/[a-z0-9]/.test(i))t+=i;else if(i===" ")t+="-";else t+="~"+i.codePointAt(0).toString(16);return t}var P=0,T=4,U=6,b=0,j=1,h=-1;function L(r){return r.map((t)=>{let i=[t[P],...t[U]||[]];return{record:t,names:i,searchKeys:i.map(E)}})}function I(r,t){if(r===t)return b;if(r.startsWith(t)||r.includes(" "+t))return j;return h}function O(r,t){let i=h,f=0;return r.searchKeys.forEach((p,g)=>{let u=I(p,t);if(u!==h&&(i===h||u<i))i=u,f=g}),{tier:i,nameIndex:f}}var z="https://geo.chofter.com/v1",D=10;function R(r={}){let t=String(r.baseUrl||z).replace(/\/+$/,""),i=r.fetch||globalThis.fetch.bind(globalThis),f=new Map;function p(e,n){let a=f.get(e);if(!a)a=i(`${t}/${e}`).then((o)=>{if(!o.ok)throw Error(`geo: ${e} returned ${o.status}`);return o.json()}).then(n),a.catch(()=>f.delete(e)),f.set(e,a);return a}function g(e){return p(`${e}/_.json`,(n)=>({code:e.toUpperCase(),name:n.name,depth:n.depth,count:n.count,prefixFiles:new Set(n.shards),topPlaces:L(n.top)}))}function u(e,n,a){let[o,s,d,A,m,c]=n.record,l={id:c,name:o,region:s,country:e.name,countryCode:e.code,lat:d,lng:A,population:m,label:[o,s,e.name].filter(Boolean).join(", ")};if(a>0)l.matched=n.names[a];return l}function F(e,n){let a=Math.min(e.depth,Array.from(n).length);for(let o=a;o>0;o--){let s=N(x(n,o));if(e.prefixFiles.has(s))return s}return null}async function w(e,n,a={}){let o=a.limit||D,s=await g(String(e).toLowerCase()),d=E(n||"");if(!d)return s.topPlaces.slice(0,o).map((c)=>u(s,c,0));let A=s.topPlaces;if(s.depth>0){let c=F(s,d);if(c===null)return[];A=await p(`${s.code.toLowerCase()}/${c}.json`,L)}let m=[];for(let c of A){let{tier:l,nameIndex:S}=O(c,d);if(l!==h)m.push({place:c,tier:l,nameIndex:S})}return m.sort((c,l)=>c.tier-l.tier||l.place.record[T]-c.place.record[T]),m.slice(0,o).map((c)=>u(s,c.place,c.nameIndex))}function C(){return p("countries.json",(e)=>e.map(([n,a,o])=>({code:n,name:a,count:o})))}function M(e){return g(String(e).toLowerCase()).then(()=>{return})}return{search:w,countries:C,preload:M}}export{R as createGeo};
1
+ // @chofter/geo 0.3.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
+ var b={ß:"ss",æ:"ae",œ:"oe",ø:"o",đ:"d",ð:"d",þ:"th",ł:"l",ı:"i",ħ:"h"};function w(c){return String(c).toLowerCase().normalize("NFD").replace(/\p{M}+/gu,"").replace(/[ßæœøđðþłıħ]/g,(e)=>b[e]).replace(/['’‘ʼ`]/g,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function j(c,e){return Array.from(c).slice(0,e).join("")}function x(c){let e="";for(let s of c)if(/[a-z0-9]/.test(s))e+=s;else if(s===" ")e+="-";else e+="~"+s.codePointAt(0).toString(16);return e}var I=0,F=4,z=6,M=8,D=0,R=1,d=-1;function P(c){return c.map((e)=>{let s=[e[I],...e[z]||[]];if(e[M])s.push(e[M]);return{record:e,names:s,searchKeys:s.map(w)}})}function y(c,e){if(c===e)return D;if(c.startsWith(e)||c.includes(" "+e))return R;return d}function H(c,e){let s=d,f=0;return c.searchKeys.forEach((u,g)=>{let p=y(u,e);if(p!==d&&(s===d||p<s))s=p,f=g}),{tier:s,nameIndex:f}}var B="https://geo.chofter.com/v1",G=10;function X(c={}){let e=String(c.baseUrl||B).replace(/\/+$/,""),s=c.fetch||globalThis.fetch.bind(globalThis),f=new Map;function u(t,n){let r=f.get(t);if(!r)r=s(`${e}/${t}`).then((i)=>{if(!i.ok)throw Error(`geo: ${t} returned ${i.status}`);return i.json()}).then(n),r.catch(()=>f.delete(t)),f.set(t,r);return r}function g(t){return u(`${t}/_.json`,(n)=>({code:t.toUpperCase(),name:n.name,depth:n.depth,count:n.count,prefixFiles:new Set(n.shards),topPlaces:P(n.top),parts:n.parts,regionParts:n.regionParts}))}function p(t,n){let r=t.regionParts&&t.regionParts[n];return r?{code:r,name:t.parts[r]}:t}function C(t,n,r){let[i,o,m,A,h,a,,l,L]=n.record,{code:U,name:E}=p(t,o),T={id:a,name:i,region:o,country:E,countryCode:U,lat:m,lng:A,population:h,label:[i,l,o,E].filter(Boolean).join(", ")};if(l)T.district=l;if(L)T.localName=L;if(r>0)T.matched=n.names[r];return T}function N(t,n){let r=Math.min(t.depth,Array.from(n).length);for(let i=r;i>0;i--){let o=x(j(n,i));if(t.prefixFiles.has(o))return o}return null}async function _(t,n,r={}){let i=r.limit||G,o=await g(String(t).toLowerCase()),m=w(n||"");if(!m)return o.topPlaces.slice(0,i).map((a)=>C(o,a,0));let A=o.topPlaces;if(o.depth>0){let a=N(o,m);if(a===null)return[];A=await u(`${o.code.toLowerCase()}/${a}.json`,P)}let h=[];for(let a of A){let{tier:l,nameIndex:L}=H(a,m);if(l!==d)h.push({place:a,tier:l,nameIndex:L})}return h.sort((a,l)=>a.tier-l.tier||l.place.record[F]-a.place.record[F]),h.slice(0,i).map((a)=>C(o,a.place,a.nameIndex))}function S(){return u("countries.json",(t)=>t.map(([n,r,i,o])=>o?{code:n,name:r,count:i,altNames:o}:{code:n,name:r,count:i}))}function O(t){return g(String(t).toLowerCase()).then(()=>{return})}return{search:_,countries:S,preload:O}}export{X as createGeo};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chofter/geo",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Tiny, dependency-free town and city search over static GeoNames files. No API, no key.",
5
5
  "keywords": [
6
6
  "geonames",