jp-postal-lookup 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +442 -2
- package/index.d.ts +158 -0
- package/package.json +57 -4
- package/src/index.cjs +191 -0
- package/src/index.js +297 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dungdao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,443 @@
|
|
|
1
|
-
#
|
|
1
|
+
# jp-postal-lookup 📮
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/jp-postal-lookup)
|
|
4
|
+
[](https://nodejs.org/)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
[](package.json)
|
|
7
|
+
[](index.d.ts)
|
|
8
|
+
|
|
9
|
+
> **Zero-dependency** Japanese address and postal code lookup library powered by [HeartRails Geo API](https://geoapi.heartrails.com/).
|
|
10
|
+
> Lightweight, universal, and easy to use across **ESM**, **CommonJS**, **TypeScript**, **Node.js 18+**, and **Modern Browsers**.
|
|
11
|
+
> 日本の郵便番号・住所検索ライブラリ(ゼロ依存関係、ブラウザ・Node.js両対応)。
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## 📑 Table of Contents
|
|
16
|
+
|
|
17
|
+
1. [Key Features](#-key-features)
|
|
18
|
+
2. [Environment Requirements](#-environment-requirements)
|
|
19
|
+
3. [Installation](#-installation)
|
|
20
|
+
4. [Quick Start](#-quick-start)
|
|
21
|
+
5. [Framework Integration](#-framework-integration)
|
|
22
|
+
- [Vue 3 / Nuxt 3](#1-vue-3--nuxt-3)
|
|
23
|
+
- [React / Next.js](#2-react--nextjs)
|
|
24
|
+
- [Node.js (Express / Backend)](#3-nodejs-backend-express)
|
|
25
|
+
- [Legacy Compatibility](#4-drop-in-replacement-for-legacy-getaddressjs)
|
|
26
|
+
6. [API Reference](#-api-reference)
|
|
27
|
+
- [Modern Promise API](#modern-promise-api)
|
|
28
|
+
- [Legacy Compatible API](#legacy-compatible-api)
|
|
29
|
+
- [TypeScript Interfaces](#typescript-interfaces)
|
|
30
|
+
7. [Testing](#-testing)
|
|
31
|
+
8. [Error Handling & Gotchas](#-error-handling--gotchas)
|
|
32
|
+
9. [Publishing to npm](#-publishing-to-npm)
|
|
33
|
+
10. [License](#-license)
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## ✨ Key Features
|
|
38
|
+
|
|
39
|
+
- 🚀 **Zero Dependencies**: Pure native JavaScript using built-in `fetch`. No external dependencies like `axios` or `lodash`.
|
|
40
|
+
- 🌐 **Universal Runtime**: Works seamlessly in modern browsers and Node.js 18+.
|
|
41
|
+
- 📦 **Dual Module Format**: Native ES Module (`import`) and CommonJS (`require`) support with comprehensive exports mapping.
|
|
42
|
+
- 🔷 **Full TypeScript Support**: Bundled type definitions (`index.d.ts`) with rich autocompletion and JSDoc documentation.
|
|
43
|
+
- 🧹 **Automatic Normalization**: Automatically handles full-width characters (`100ー0001`), hyphens (`-`, `ー`, `-`), and spaces.
|
|
44
|
+
- 🔄 **Two-Way Lookup**: Search address by postal code, or search postal code by address name.
|
|
45
|
+
- 🛡️ **Fail-Safe**: Gracefully handles network failures, malformed input, and non-existent codes without throwing uncaught exceptions.
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 💻 Environment Requirements
|
|
50
|
+
|
|
51
|
+
| Environment | Supported Versions | Notes |
|
|
52
|
+
| :--- | :--- | :--- |
|
|
53
|
+
| **Node.js** | `>= 18.0.0` (Recommended: 18.x, 20.x, 22.x LTS) | Utilizes native `globalThis.fetch` |
|
|
54
|
+
| **Browsers** | Chrome 66+, Firefox 57+, Safari 11.1+, Edge 79+ | Requires standard Fetch API & ES6 Modules |
|
|
55
|
+
| **TypeScript** | `>= 4.5.0` | Ships with complete `index.d.ts` definitions |
|
|
56
|
+
| **Package Managers** | npm 7+, yarn 1/3+, pnpm 7+, bun 1+ | Full `exports` map support |
|
|
57
|
+
| **Dependencies** | **0 dependencies** | Zero bloat, minimal bundle size |
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## 📦 Installation
|
|
62
|
+
|
|
63
|
+
### From npm registry:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
# npm
|
|
67
|
+
npm install jp-postal-lookup
|
|
68
|
+
|
|
69
|
+
# yarn
|
|
70
|
+
yarn add jp-postal-lookup
|
|
71
|
+
|
|
72
|
+
# pnpm
|
|
73
|
+
pnpm add jp-postal-lookup
|
|
74
|
+
|
|
75
|
+
# bun
|
|
76
|
+
bun add jp-postal-lookup
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Direct Browser Usage (CDN):
|
|
80
|
+
|
|
81
|
+
```html
|
|
82
|
+
<script type="module">
|
|
83
|
+
import { searchAddressByPostal } from 'https://esm.sh/jp-postal-lookup';
|
|
84
|
+
|
|
85
|
+
const address = await searchAddressByPostal('100-0001');
|
|
86
|
+
console.log(address); // "東京都千代田区千代田"
|
|
87
|
+
</script>
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## ⚡ Quick Start
|
|
93
|
+
|
|
94
|
+
### ES Module (`import`)
|
|
95
|
+
|
|
96
|
+
```javascript
|
|
97
|
+
import { searchAddressByPostal, searchPostalByAddress } from 'jp-postal-lookup';
|
|
98
|
+
|
|
99
|
+
// 1. Search address by postal code (auto-normalizes '100-0001', '100ー0001' -> '1000001')
|
|
100
|
+
const address = await searchAddressByPostal('100-0001');
|
|
101
|
+
console.log(address);
|
|
102
|
+
// Output: "東京都千代田区千代田"
|
|
103
|
+
|
|
104
|
+
// 2. Search postal code by address keyword
|
|
105
|
+
const postal = await searchPostalByAddress('千代田区千代田');
|
|
106
|
+
console.log(postal);
|
|
107
|
+
// Output: "1000001"
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### CommonJS (`require`)
|
|
111
|
+
|
|
112
|
+
```javascript
|
|
113
|
+
const { searchAddressByPostal, onSearchAddressByPostcode } = require('jp-postal-lookup');
|
|
114
|
+
|
|
115
|
+
async function run() {
|
|
116
|
+
const address = await searchAddressByPostal('100-0001');
|
|
117
|
+
console.log('Address:', address);
|
|
118
|
+
}
|
|
119
|
+
run();
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## 🧩 Framework Integration
|
|
125
|
+
|
|
126
|
+
### 1. Vue 3 / Nuxt 3
|
|
127
|
+
|
|
128
|
+
```vue
|
|
129
|
+
<template>
|
|
130
|
+
<div class="address-lookup">
|
|
131
|
+
<input
|
|
132
|
+
v-model="postalCode"
|
|
133
|
+
placeholder="100-0001"
|
|
134
|
+
@blur="handleLookup"
|
|
135
|
+
/>
|
|
136
|
+
<button :disabled="loading" @click="handleLookup">
|
|
137
|
+
{{ loading ? 'Searching...' : 'Lookup Address' }}
|
|
138
|
+
</button>
|
|
139
|
+
<p v-if="address">Address: {{ address }}</p>
|
|
140
|
+
<p v-if="error" class="error">{{ error }}</p>
|
|
141
|
+
</div>
|
|
142
|
+
</template>
|
|
143
|
+
|
|
144
|
+
<script setup>
|
|
145
|
+
import { ref } from 'vue';
|
|
146
|
+
import { searchAddressByPostal } from 'jp-postal-lookup';
|
|
147
|
+
|
|
148
|
+
const postalCode = ref('');
|
|
149
|
+
const address = ref('');
|
|
150
|
+
const error = ref('');
|
|
151
|
+
const loading = ref(false);
|
|
152
|
+
|
|
153
|
+
const handleLookup = async () => {
|
|
154
|
+
if (!postalCode.value) return;
|
|
155
|
+
loading.value = true;
|
|
156
|
+
error.value = '';
|
|
157
|
+
try {
|
|
158
|
+
const result = await searchAddressByPostal(postalCode.value);
|
|
159
|
+
if (result) {
|
|
160
|
+
address.value = result;
|
|
161
|
+
} else {
|
|
162
|
+
error.value = 'No address found for this postal code.';
|
|
163
|
+
}
|
|
164
|
+
} catch (err) {
|
|
165
|
+
error.value = 'Lookup failed: ' + err.message;
|
|
166
|
+
} finally {
|
|
167
|
+
loading.value = false;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
</script>
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### 2. React / Next.js
|
|
174
|
+
|
|
175
|
+
```tsx
|
|
176
|
+
import React, { useState } from 'react';
|
|
177
|
+
import { searchAddressByPostal, type GeoLocation } from 'jp-postal-lookup';
|
|
178
|
+
|
|
179
|
+
export function AddressForm() {
|
|
180
|
+
const [postal, setPostal] = useState('');
|
|
181
|
+
const [location, setLocation] = useState<GeoLocation | null>(null);
|
|
182
|
+
|
|
183
|
+
const onSearch = async () => {
|
|
184
|
+
// Retrieve detailed object (prefecture, city, town, coordinates x/y)
|
|
185
|
+
const data = await searchAddressByPostal(postal, { raw: true });
|
|
186
|
+
setLocation(data);
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
return (
|
|
190
|
+
<div>
|
|
191
|
+
<input
|
|
192
|
+
value={postal}
|
|
193
|
+
onChange={(e) => setPostal(e.target.value)}
|
|
194
|
+
placeholder="100-0001"
|
|
195
|
+
/>
|
|
196
|
+
<button onClick={onSearch}>Lookup</button>
|
|
197
|
+
{location && (
|
|
198
|
+
<div>
|
|
199
|
+
<p>Prefecture: {location.prefecture}</p>
|
|
200
|
+
<p>City: {location.city}</p>
|
|
201
|
+
<p>Town: {location.town}</p>
|
|
202
|
+
</div>
|
|
203
|
+
)}
|
|
204
|
+
</div>
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### 3. Node.js Backend (Express)
|
|
210
|
+
|
|
211
|
+
```javascript
|
|
212
|
+
import express from 'express';
|
|
213
|
+
import { searchAddressByPostal } from 'jp-postal-lookup';
|
|
214
|
+
|
|
215
|
+
const app = express();
|
|
216
|
+
|
|
217
|
+
app.get('/api/lookup-postal', async (req, res) => {
|
|
218
|
+
const { code } = req.query;
|
|
219
|
+
if (!code) {
|
|
220
|
+
return res.status(400).json({ error: 'Missing postal code parameter' });
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const address = await searchAddressByPostal(code, { raw: true });
|
|
224
|
+
if (!address) {
|
|
225
|
+
return res.status(404).json({ message: 'Address not found' });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return res.json({ data: address });
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### 4. Drop-in Replacement for Legacy `getAddress.js`
|
|
235
|
+
|
|
236
|
+
If your existing project has a legacy `getAddress.js` utility, simply update the import statement:
|
|
237
|
+
|
|
238
|
+
```diff
|
|
239
|
+
- import { onSearchAddressByPostcode, onSearchPostcodeByAddress } from '@/utilities/getAddress.js';
|
|
240
|
+
+ import { onSearchAddressByPostcode, onSearchPostcodeByAddress } from 'jp-postal-lookup';
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
All method names, parameters, callback signatures, and return formats remain 100% identical.
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
## 📖 API Reference
|
|
248
|
+
|
|
249
|
+
### Modern Promise API
|
|
250
|
+
|
|
251
|
+
#### 1. `searchAddressByPostal(postal, options?)`
|
|
252
|
+
Searches address information by Japanese postal code.
|
|
253
|
+
|
|
254
|
+
- **Parameters**:
|
|
255
|
+
- `postal` (`string | number`): Japanese postal code (e.g. `'100-0001'`, `'1000001'`, `'100ー0001'`).
|
|
256
|
+
- `options` (`object`, optional):
|
|
257
|
+
- `raw` (`boolean`, default: `false`): When `true`, returns a `GeoLocation` object containing x, y coordinates and furigana.
|
|
258
|
+
- `all` (`boolean`, default: `false`): When `true`, returns an array `GeoLocation[]` of all matching locations.
|
|
259
|
+
- `baseUrl` (`string`, optional): Custom API endpoint (e.g., when routing through a reverse proxy).
|
|
260
|
+
- **Returns**: `Promise<string | GeoLocation | GeoLocation[] | null>`
|
|
261
|
+
|
|
262
|
+
```javascript
|
|
263
|
+
// Returns full address string
|
|
264
|
+
const address = await searchAddressByPostal('100-0001');
|
|
265
|
+
// "東京都千代田区千代田"
|
|
266
|
+
|
|
267
|
+
// Returns detailed GeoLocation object
|
|
268
|
+
const location = await searchAddressByPostal('100-0001', { raw: true });
|
|
269
|
+
// {
|
|
270
|
+
// postal: "1000001",
|
|
271
|
+
// prefecture: "東京都",
|
|
272
|
+
// city: "千代田区",
|
|
273
|
+
// town: "千代田",
|
|
274
|
+
// city_kana: "ちよだく",
|
|
275
|
+
// town_kana: "ちよだ",
|
|
276
|
+
// x: "139.7533",
|
|
277
|
+
// y: "35.6852"
|
|
278
|
+
// }
|
|
279
|
+
|
|
280
|
+
// Returns all matching locations
|
|
281
|
+
const list = await searchAddressByPostal('100-0001', { all: true });
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
---
|
|
285
|
+
|
|
286
|
+
#### 2. `searchPostalByAddress(address, options?)`
|
|
287
|
+
Searches postal codes by address name keyword.
|
|
288
|
+
|
|
289
|
+
- **Parameters**:
|
|
290
|
+
- `address` (`string`): Address keyword (e.g. `'千代田区千代田'`).
|
|
291
|
+
- `options` (`object`, optional):
|
|
292
|
+
- `raw` (`boolean`, default: `false`): Returns `GeoLocation` object.
|
|
293
|
+
- `all` (`boolean`, default: `false`): Returns array `GeoLocation[]`.
|
|
294
|
+
- `matching` (`'prefix' | 'suffix' | 'like'`, default: `'suffix'`).
|
|
295
|
+
- **Returns**: `Promise<string | GeoLocation | GeoLocation[] | null>`
|
|
296
|
+
|
|
297
|
+
```javascript
|
|
298
|
+
const postal = await searchPostalByAddress('千代田区千代田');
|
|
299
|
+
// "1000001"
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
---
|
|
303
|
+
|
|
304
|
+
#### 3. `getAreas()`
|
|
305
|
+
Retrieves list of major Japanese geographic regions.
|
|
306
|
+
- **Returns**: `Promise<string[]>`
|
|
307
|
+
- **Result**: `['北海道', '東北', '関東', '中部', '近畿', '中国', '四国', '九州']`
|
|
308
|
+
|
|
309
|
+
---
|
|
310
|
+
|
|
311
|
+
#### 4. `getPrefectures(area)`
|
|
312
|
+
Retrieves prefectures belonging to a specific region.
|
|
313
|
+
- **Parameters**: `area` (`string`): e.g. `'関東'`.
|
|
314
|
+
- **Returns**: `Promise<string[]>`
|
|
315
|
+
- **Result**: `['茨城県', '栃木県', '群馬県', '埼玉県', '千葉県', '東京都', '神奈川県']`
|
|
316
|
+
|
|
317
|
+
---
|
|
318
|
+
|
|
319
|
+
#### 5. `getCities(prefecture, area?)`
|
|
320
|
+
Retrieves cities/districts belonging to a prefecture.
|
|
321
|
+
- **Parameters**:
|
|
322
|
+
- `prefecture` (`string`): e.g. `'東京都'`.
|
|
323
|
+
- `area` (`string`, optional).
|
|
324
|
+
- **Returns**: `Promise<string[]>`
|
|
325
|
+
- **Result**: `['千代田区', '中央区', '港区', '新宿区', ...]`
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
329
|
+
#### 6. `getTowns(city, prefecture?)`
|
|
330
|
+
Retrieves towns/wards belonging to a city.
|
|
331
|
+
- **Parameters**:
|
|
332
|
+
- `city` (`string`): e.g. `'千代田区'`.
|
|
333
|
+
- `prefecture` (`string`, optional): e.g. `'東京都'`.
|
|
334
|
+
- **Returns**: `Promise<string[]>`
|
|
335
|
+
- **Result**: `['丸の内', '大手町', '一ツ橋', ...]`
|
|
336
|
+
|
|
337
|
+
---
|
|
338
|
+
|
|
339
|
+
#### 7. `normalizePostal(postal)`
|
|
340
|
+
Utility function that sanitizes and formats postal code strings.
|
|
341
|
+
- **Parameters**: `postal` (`string | number`)
|
|
342
|
+
- **Behavior**:
|
|
343
|
+
- `normalizePostal('100-0001')` ➜ `'1000001'`
|
|
344
|
+
- `normalizePostal(' 100ー0001 ')` ➜ `'1000001'`
|
|
345
|
+
- `normalizePostal('100 0001')` ➜ `'1000001'`
|
|
346
|
+
|
|
347
|
+
---
|
|
348
|
+
|
|
349
|
+
### Legacy Compatible API
|
|
350
|
+
|
|
351
|
+
For backwards compatibility with legacy codebase conventions:
|
|
352
|
+
|
|
353
|
+
| Function Name | Signature | Description |
|
|
354
|
+
| :--- | :--- | :--- |
|
|
355
|
+
| `onSearchAddressByPostcode(postcode, isResponse?)` | `(string\|number, boolean?) => Promise<string \| GeoLocation \| null>` | `isResponse=false` returns formatted address string; `isResponse=true` returns location object |
|
|
356
|
+
| `onSearchPostcodeByAddress(address, isResponse?, matching?)` | `(string, boolean?, string?) => Promise<string \| GeoLocation \| null>` | Searches postal code by address keyword |
|
|
357
|
+
| `getPrefecturesByArea(area, callback?)` | `(string, (res) => void) => Promise<object>` | Gets prefectures, supports callback |
|
|
358
|
+
| `onGetCitiesByPrefecture(area, prefecture, callback?)` | `(string, string, (res) => void) => Promise<object>` | Gets cities, supports callback |
|
|
359
|
+
| `onGetTownsByCity(city, prefecture, callback?)` | `(string, string, (res) => void) => Promise<object>` | Gets towns, supports callback |
|
|
360
|
+
|
|
361
|
+
---
|
|
362
|
+
|
|
363
|
+
### TypeScript Interfaces
|
|
364
|
+
|
|
365
|
+
```typescript
|
|
366
|
+
export interface GeoLocation {
|
|
367
|
+
city: string; // "千代田区"
|
|
368
|
+
city_kana: string; // "ちよだく"
|
|
369
|
+
town: string; // "千代田"
|
|
370
|
+
town_kana: string; // "ちよだ"
|
|
371
|
+
x: string; // "139.7533" (Longitude)
|
|
372
|
+
y: string; // "35.6852" (Latitude)
|
|
373
|
+
prefecture: string; // "東京都"
|
|
374
|
+
postal: string; // "1000001"
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export interface SearchOptions {
|
|
378
|
+
raw?: boolean;
|
|
379
|
+
all?: boolean;
|
|
380
|
+
baseUrl?: string;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export interface SuggestOptions extends SearchOptions {
|
|
384
|
+
matching?: 'prefix' | 'suffix' | 'like';
|
|
385
|
+
}
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
---
|
|
389
|
+
|
|
390
|
+
## 🧪 Testing
|
|
391
|
+
|
|
392
|
+
The library uses the standard Node.js native test runner (`node:test` and `node:assert/strict`), requiring zero test framework overhead:
|
|
393
|
+
|
|
394
|
+
```bash
|
|
395
|
+
npm test
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
### Test Coverage Highlights:
|
|
399
|
+
1. `normalizePostal`: Handles half-width, full-width hyphens (`-`, `ー`, `-`), spaces, and nullish inputs.
|
|
400
|
+
2. `onSearchAddressByPostcode`: Exact postal code match in string and object formats.
|
|
401
|
+
3. Non-existent codes (`000-0000`) or invalid inputs: Safely returns empty strings or `null` without throwing errors.
|
|
402
|
+
4. `onSearchPostcodeByAddress`: Keyword address search and unmatched fallback.
|
|
403
|
+
5. Regional breakdown: `getPrefecturesByArea`, `onGetCitiesByPrefecture`, `onGetTownsByCity` with Promises and callbacks.
|
|
404
|
+
6. Modern API features: `{ raw: true }`, `{ all: true }`, and `{ matching: 'like' }` options.
|
|
405
|
+
|
|
406
|
+
---
|
|
407
|
+
|
|
408
|
+
## ⚠️ Error Handling & Gotchas
|
|
409
|
+
|
|
410
|
+
1. **HeartRails Geo API Endpoint**:
|
|
411
|
+
- Queries are resolved via the public [HeartRails Geo API](https://geoapi.heartrails.com/api/json).
|
|
412
|
+
- If your environment requires an internal reverse proxy or custom mock server, pass `baseUrl`:
|
|
413
|
+
```javascript
|
|
414
|
+
searchAddressByPostal('1000001', { baseUrl: 'https://my-internal-proxy.com/api/json' });
|
|
415
|
+
```
|
|
416
|
+
2. **Network Fail-Safe**:
|
|
417
|
+
- All network calls are protected with internal `try/catch` handlers. If an outage occurs or the API returns non-200 status codes, the functions return `''`, `null`, or `[]` depending on options, preventing uncaught promise rejections.
|
|
418
|
+
|
|
419
|
+
---
|
|
420
|
+
|
|
421
|
+
## 🚢 Publishing to npm
|
|
422
|
+
|
|
423
|
+
### Step 1: Login to npm
|
|
424
|
+
```bash
|
|
425
|
+
npm login
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
### Step 2: Run Tests and Validate Bundle
|
|
429
|
+
```bash
|
|
430
|
+
npm test
|
|
431
|
+
npm pack --dry-run
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
### Step 3: Publish to npm Registry
|
|
435
|
+
```bash
|
|
436
|
+
npm publish --access public
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
---
|
|
440
|
+
|
|
441
|
+
## 📄 License
|
|
442
|
+
|
|
443
|
+
Published under the [MIT License](LICENSE).
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
export interface GeoLocation {
|
|
2
|
+
city: string;
|
|
3
|
+
city_kana: string;
|
|
4
|
+
town: string;
|
|
5
|
+
town_kana: string;
|
|
6
|
+
x: string;
|
|
7
|
+
y: string;
|
|
8
|
+
prefecture: string;
|
|
9
|
+
postal: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface SearchOptions {
|
|
13
|
+
raw?: boolean;
|
|
14
|
+
all?: boolean;
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface SuggestOptions extends SearchOptions {
|
|
19
|
+
matching?: 'prefix' | 'suffix' | 'like';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export declare const DEFAULT_API_BASE_URL: string;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Remove hyphens and whitespace from postal code.
|
|
26
|
+
*/
|
|
27
|
+
export declare function normalizePostal(postal: string | number): string;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Legacy API: Get prefectures by area with optional callback.
|
|
31
|
+
*/
|
|
32
|
+
export declare function getPrefecturesByArea(
|
|
33
|
+
area: string,
|
|
34
|
+
callback?: (response: { prefecture: string[] } | null) => void,
|
|
35
|
+
baseUrl?: string
|
|
36
|
+
): Promise<{ prefecture: string[] } | null>;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Legacy API: Get cities by area and prefecture with optional callback.
|
|
40
|
+
*/
|
|
41
|
+
export declare function onGetCitiesByPrefecture(
|
|
42
|
+
area: string,
|
|
43
|
+
prefecture: string,
|
|
44
|
+
callback?: (response: { city: string[] } | null) => void,
|
|
45
|
+
baseUrl?: string
|
|
46
|
+
): Promise<{ city: string[] } | null>;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Legacy API: Get towns by city and prefecture with optional callback.
|
|
50
|
+
*/
|
|
51
|
+
export declare function onGetTownsByCity(
|
|
52
|
+
city: string,
|
|
53
|
+
prefecture: string,
|
|
54
|
+
callback?: (response: { town: string[] } | null) => void,
|
|
55
|
+
baseUrl?: string
|
|
56
|
+
): Promise<{ town: string[] } | null>;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Legacy API: Search address by postal code.
|
|
60
|
+
* @param postcode - Postal code with or without hyphen
|
|
61
|
+
* @param isResponse - If true returns raw GeoLocation, otherwise formatted string
|
|
62
|
+
*/
|
|
63
|
+
export declare function onSearchAddressByPostcode(
|
|
64
|
+
postcode: string | number,
|
|
65
|
+
isResponse?: false,
|
|
66
|
+
baseUrl?: string
|
|
67
|
+
): Promise<string>;
|
|
68
|
+
export declare function onSearchAddressByPostcode(
|
|
69
|
+
postcode: string | number,
|
|
70
|
+
isResponse: true,
|
|
71
|
+
baseUrl?: string
|
|
72
|
+
): Promise<GeoLocation | null>;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Legacy API: Search postal code by address string.
|
|
76
|
+
*/
|
|
77
|
+
export declare function onSearchPostcodeByAddress(
|
|
78
|
+
address: string,
|
|
79
|
+
isResponse?: false,
|
|
80
|
+
matching?: 'prefix' | 'suffix' | 'like',
|
|
81
|
+
baseUrl?: string
|
|
82
|
+
): Promise<string>;
|
|
83
|
+
export declare function onSearchPostcodeByAddress(
|
|
84
|
+
address: string,
|
|
85
|
+
isResponse: true,
|
|
86
|
+
matching?: 'prefix' | 'suffix' | 'like',
|
|
87
|
+
baseUrl?: string
|
|
88
|
+
): Promise<GeoLocation | null>;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Modern Promise API: Search address by postal code.
|
|
92
|
+
*/
|
|
93
|
+
export declare function searchAddressByPostal(
|
|
94
|
+
postal: string | number,
|
|
95
|
+
options?: { raw?: false; all?: false; baseUrl?: string }
|
|
96
|
+
): Promise<string>;
|
|
97
|
+
export declare function searchAddressByPostal(
|
|
98
|
+
postal: string | number,
|
|
99
|
+
options: { raw: true; all?: false; baseUrl?: string }
|
|
100
|
+
): Promise<GeoLocation | null>;
|
|
101
|
+
export declare function searchAddressByPostal(
|
|
102
|
+
postal: string | number,
|
|
103
|
+
options: { all: true; raw?: boolean; baseUrl?: string }
|
|
104
|
+
): Promise<GeoLocation[]>;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Modern Promise API: Search postal code by address keyword.
|
|
108
|
+
*/
|
|
109
|
+
export declare function searchPostalByAddress(
|
|
110
|
+
address: string,
|
|
111
|
+
options?: { raw?: false; all?: false; matching?: 'prefix' | 'suffix' | 'like'; baseUrl?: string }
|
|
112
|
+
): Promise<string>;
|
|
113
|
+
export declare function searchPostalByAddress(
|
|
114
|
+
address: string,
|
|
115
|
+
options: { raw: true; all?: false; matching?: 'prefix' | 'suffix' | 'like'; baseUrl?: string }
|
|
116
|
+
): Promise<GeoLocation | null>;
|
|
117
|
+
export declare function searchPostalByAddress(
|
|
118
|
+
address: string,
|
|
119
|
+
options: { all: true; raw?: boolean; matching?: 'prefix' | 'suffix' | 'like'; baseUrl?: string }
|
|
120
|
+
): Promise<GeoLocation[]>;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Get all areas in Japan.
|
|
124
|
+
*/
|
|
125
|
+
export declare function getAreas(baseUrl?: string): Promise<string[]>;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Get prefectures for a given area.
|
|
129
|
+
*/
|
|
130
|
+
export declare function getPrefectures(area: string, baseUrl?: string): Promise<string[]>;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Get cities in a prefecture.
|
|
134
|
+
*/
|
|
135
|
+
export declare function getCities(prefecture: string, area?: string, baseUrl?: string): Promise<string[]>;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Get towns in a city.
|
|
139
|
+
*/
|
|
140
|
+
export declare function getTowns(city: string, prefecture?: string, baseUrl?: string): Promise<string[]>;
|
|
141
|
+
|
|
142
|
+
declare const _default: {
|
|
143
|
+
DEFAULT_API_BASE_URL: string;
|
|
144
|
+
normalizePostal: typeof normalizePostal;
|
|
145
|
+
getPrefecturesByArea: typeof getPrefecturesByArea;
|
|
146
|
+
onGetCitiesByPrefecture: typeof onGetCitiesByPrefecture;
|
|
147
|
+
onGetTownsByCity: typeof onGetTownsByCity;
|
|
148
|
+
onSearchAddressByPostcode: typeof onSearchAddressByPostcode;
|
|
149
|
+
onSearchPostcodeByAddress: typeof onSearchPostcodeByAddress;
|
|
150
|
+
searchAddressByPostal: typeof searchAddressByPostal;
|
|
151
|
+
searchPostalByAddress: typeof searchPostalByAddress;
|
|
152
|
+
getAreas: typeof getAreas;
|
|
153
|
+
getPrefectures: typeof getPrefectures;
|
|
154
|
+
getCities: typeof getCities;
|
|
155
|
+
getTowns: typeof getTowns;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
export default _default;
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jp-postal-lookup",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Zero-dependency Japanese address and postal code lookup library using HeartRails Geo API. Supports ESM, CommonJS, and TypeScript. 日本の郵便番号・住所検索ライブラリ。",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"japan",
|
|
7
|
+
"japanese",
|
|
8
|
+
"postal",
|
|
9
|
+
"postcode",
|
|
10
|
+
"zipcode",
|
|
11
|
+
"postal-code",
|
|
12
|
+
"postal-code-lookup",
|
|
13
|
+
"japan-postal-code",
|
|
14
|
+
"japanese-postal-code",
|
|
15
|
+
"japan-zipcode",
|
|
16
|
+
"address",
|
|
17
|
+
"japan-address",
|
|
18
|
+
"japanese-address",
|
|
19
|
+
"address-lookup",
|
|
20
|
+
"address-search",
|
|
21
|
+
"heartrails",
|
|
22
|
+
"geo",
|
|
23
|
+
"geoapi",
|
|
24
|
+
"prefecture",
|
|
25
|
+
"city",
|
|
26
|
+
"town",
|
|
27
|
+
"yubinbango",
|
|
28
|
+
"ken-all",
|
|
29
|
+
"郵便番号",
|
|
30
|
+
"住所検索",
|
|
31
|
+
"郵便番号検索",
|
|
32
|
+
"都道府県"
|
|
33
|
+
],
|
|
34
|
+
"author": "dungdao",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"type": "module",
|
|
37
|
+
"main": "./src/index.cjs",
|
|
38
|
+
"module": "./src/index.js",
|
|
39
|
+
"types": "./index.d.ts",
|
|
40
|
+
"exports": {
|
|
41
|
+
".": {
|
|
42
|
+
"types": "./index.d.ts",
|
|
43
|
+
"import": "./src/index.js",
|
|
44
|
+
"require": "./src/index.cjs"
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"files": [
|
|
48
|
+
"src",
|
|
49
|
+
"index.d.ts",
|
|
50
|
+
"README.md",
|
|
51
|
+
"LICENSE"
|
|
52
|
+
],
|
|
53
|
+
"scripts": {
|
|
54
|
+
"test": "node --test tests/index.test.js"
|
|
55
|
+
},
|
|
56
|
+
"engines": {
|
|
57
|
+
"node": ">=18.0.0"
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/index.cjs
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
const DEFAULT_API_BASE_URL = 'https://geoapi.heartrails.com/api/json';
|
|
2
|
+
|
|
3
|
+
function normalizePostal(postal) {
|
|
4
|
+
if (postal === null || postal === undefined) return '';
|
|
5
|
+
return String(postal)
|
|
6
|
+
.replace(/[ー--]/g, '')
|
|
7
|
+
.replace(/[\s\u3000]/g, '')
|
|
8
|
+
.trim();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async function fetchJson(url, options = {}) {
|
|
12
|
+
const fetchFn = typeof globalThis.fetch === 'function' ? globalThis.fetch : null;
|
|
13
|
+
if (!fetchFn) {
|
|
14
|
+
throw new Error('jp-postal-lookup: Fetch API is not available in this environment.');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
const response = await fetchFn(url, options);
|
|
19
|
+
if (!response.ok) {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
const data = await response.json();
|
|
23
|
+
return data?.response ?? null;
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function getPrefecturesByArea(area, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
30
|
+
const url = `${baseUrl}?method=getPrefectures&area=${encodeURIComponent(area || '')}`;
|
|
31
|
+
const result = await fetchJson(url);
|
|
32
|
+
if (typeof callback === 'function') {
|
|
33
|
+
callback(result);
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function onGetCitiesByPrefecture(area, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
39
|
+
const queryArea = area ? `&area=${encodeURIComponent(area)}` : '';
|
|
40
|
+
const url = `${baseUrl}?method=getCities${queryArea}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
41
|
+
const result = await fetchJson(url);
|
|
42
|
+
if (typeof callback === 'function') {
|
|
43
|
+
callback(result);
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function onGetTownsByCity(city, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
49
|
+
const url = `${baseUrl}?method=getTowns&city=${encodeURIComponent(city || '')}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
50
|
+
const result = await fetchJson(url);
|
|
51
|
+
if (typeof callback === 'function') {
|
|
52
|
+
callback(result);
|
|
53
|
+
}
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function onSearchAddressByPostcode(postcode, isResponse = false, baseUrl = DEFAULT_API_BASE_URL) {
|
|
58
|
+
const cleanCode = normalizePostal(postcode);
|
|
59
|
+
if (!cleanCode) return isResponse ? null : '';
|
|
60
|
+
|
|
61
|
+
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(cleanCode)}`;
|
|
62
|
+
const response = await fetchJson(url);
|
|
63
|
+
|
|
64
|
+
if (!response) {
|
|
65
|
+
return isResponse ? null : '';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const dataAddress = response?.location;
|
|
69
|
+
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
70
|
+
const address = dataAddress[0];
|
|
71
|
+
if (isResponse) {
|
|
72
|
+
return address;
|
|
73
|
+
}
|
|
74
|
+
return `${address.prefecture || ''}${address.city || ''}${address.town || ''}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return isResponse ? null : '';
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function onSearchPostcodeByAddress(
|
|
81
|
+
address,
|
|
82
|
+
isResponse = false,
|
|
83
|
+
matching = 'suffix',
|
|
84
|
+
baseUrl = DEFAULT_API_BASE_URL
|
|
85
|
+
) {
|
|
86
|
+
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
87
|
+
return isResponse ? null : '';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
91
|
+
const response = await fetchJson(url);
|
|
92
|
+
|
|
93
|
+
if (!response) {
|
|
94
|
+
return isResponse ? null : '';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const dataAddress = response?.location;
|
|
98
|
+
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
99
|
+
const item = dataAddress[0];
|
|
100
|
+
return isResponse ? item : item?.postal || '';
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return isResponse ? null : '';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function searchAddressByPostal(postal, { raw = false, all = false, baseUrl = DEFAULT_API_BASE_URL } = {}) {
|
|
107
|
+
const clean = normalizePostal(postal);
|
|
108
|
+
if (!clean) return all ? [] : raw ? null : '';
|
|
109
|
+
|
|
110
|
+
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(clean)}`;
|
|
111
|
+
const response = await fetchJson(url);
|
|
112
|
+
const locations = response?.location || [];
|
|
113
|
+
|
|
114
|
+
if (!locations.length) {
|
|
115
|
+
return all ? [] : raw ? null : '';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (all) {
|
|
119
|
+
return locations;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const first = locations[0];
|
|
123
|
+
if (raw) {
|
|
124
|
+
return first;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return `${first.prefecture || ''}${first.city || ''}${first.town || ''}`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function searchPostalByAddress(
|
|
131
|
+
address,
|
|
132
|
+
{ raw = false, all = false, matching = 'suffix', baseUrl = DEFAULT_API_BASE_URL } = {}
|
|
133
|
+
) {
|
|
134
|
+
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
135
|
+
return all ? [] : raw ? null : '';
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
139
|
+
const response = await fetchJson(url);
|
|
140
|
+
const locations = response?.location || [];
|
|
141
|
+
|
|
142
|
+
if (!locations.length) {
|
|
143
|
+
return all ? [] : raw ? null : '';
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (all) {
|
|
147
|
+
return locations;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const first = locations[0];
|
|
151
|
+
return raw ? first : first.postal || '';
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function getAreas(baseUrl = DEFAULT_API_BASE_URL) {
|
|
155
|
+
const url = `${baseUrl}?method=getAreas`;
|
|
156
|
+
const response = await fetchJson(url);
|
|
157
|
+
return response?.area || [];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function getPrefectures(area, baseUrl = DEFAULT_API_BASE_URL) {
|
|
161
|
+
const response = await getPrefecturesByArea(area, null, baseUrl);
|
|
162
|
+
return response?.prefecture || [];
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function getCities(prefecture, area = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
166
|
+
const response = await onGetCitiesByPrefecture(area, prefecture, null, baseUrl);
|
|
167
|
+
const locations = response?.location || [];
|
|
168
|
+
return locations.map((item) => (typeof item === 'string' ? item : item.city)).filter(Boolean);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function getTowns(city, prefecture = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
172
|
+
const response = await onGetTownsByCity(city, prefecture, null, baseUrl);
|
|
173
|
+
const locations = response?.location || [];
|
|
174
|
+
return locations.map((item) => (typeof item === 'string' ? item : item.town)).filter(Boolean);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
module.exports = {
|
|
178
|
+
DEFAULT_API_BASE_URL,
|
|
179
|
+
normalizePostal,
|
|
180
|
+
getPrefecturesByArea,
|
|
181
|
+
onGetCitiesByPrefecture,
|
|
182
|
+
onGetTownsByCity,
|
|
183
|
+
onSearchAddressByPostcode,
|
|
184
|
+
onSearchPostcodeByAddress,
|
|
185
|
+
searchAddressByPostal,
|
|
186
|
+
searchPostalByAddress,
|
|
187
|
+
getAreas,
|
|
188
|
+
getPrefectures,
|
|
189
|
+
getCities,
|
|
190
|
+
getTowns
|
|
191
|
+
};
|
package/src/index.js
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* jp-postal-lookup
|
|
3
|
+
* Lightweight library to search Japanese addresses, postal codes, prefectures, cities, and towns
|
|
4
|
+
* using HeartRails Geo API with zero runtime dependencies.
|
|
5
|
+
*
|
|
6
|
+
* Compatible with Node.js 18+ and modern browsers.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_API_BASE_URL = 'https://geoapi.heartrails.com/api/json';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Format postal code by removing hyphens and full-width spaces.
|
|
13
|
+
* E.g., "100-0001" -> "1000001"
|
|
14
|
+
* @param {string|number} postal
|
|
15
|
+
* @returns {string}
|
|
16
|
+
*/
|
|
17
|
+
export function normalizePostal(postal) {
|
|
18
|
+
if (postal === null || postal === undefined) return '';
|
|
19
|
+
return String(postal)
|
|
20
|
+
.replace(/[ー--]/g, '')
|
|
21
|
+
.replace(/[\s\u3000]/g, '')
|
|
22
|
+
.trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Internal fetch helper with JSON parsing and error handling.
|
|
27
|
+
* @param {string} url
|
|
28
|
+
* @param {RequestInit} [options]
|
|
29
|
+
* @returns {Promise<any>}
|
|
30
|
+
*/
|
|
31
|
+
async function fetchJson(url, options = {}) {
|
|
32
|
+
const fetchFn = typeof globalThis.fetch === 'function' ? globalThis.fetch : null;
|
|
33
|
+
if (!fetchFn) {
|
|
34
|
+
throw new Error('jp-postal-lookup: Fetch API is not available in this environment.');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
const response = await fetchFn(url, options);
|
|
39
|
+
if (!response.ok) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
const data = await response.json();
|
|
43
|
+
return data?.response ?? null;
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Get list of prefectures by area.
|
|
51
|
+
* @param {string} area - e.g., '関東', '近畿', '中部', etc.
|
|
52
|
+
* @param {Function} [callback] - Optional callback (response) => void
|
|
53
|
+
* @param {string} [baseUrl]
|
|
54
|
+
* @returns {Promise<any>}
|
|
55
|
+
*/
|
|
56
|
+
export async function getPrefecturesByArea(area, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
57
|
+
const url = `${baseUrl}?method=getPrefectures&area=${encodeURIComponent(area || '')}`;
|
|
58
|
+
const result = await fetchJson(url);
|
|
59
|
+
if (typeof callback === 'function') {
|
|
60
|
+
callback(result);
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Get cities by area and prefecture.
|
|
67
|
+
* @param {string} area
|
|
68
|
+
* @param {string} prefecture - e.g., '東京都'
|
|
69
|
+
* @param {Function} [callback]
|
|
70
|
+
* @param {string} [baseUrl]
|
|
71
|
+
* @returns {Promise<any>}
|
|
72
|
+
*/
|
|
73
|
+
export async function onGetCitiesByPrefecture(area, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
74
|
+
const queryArea = area ? `&area=${encodeURIComponent(area)}` : '';
|
|
75
|
+
const url = `${baseUrl}?method=getCities${queryArea}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
76
|
+
const result = await fetchJson(url);
|
|
77
|
+
if (typeof callback === 'function') {
|
|
78
|
+
callback(result);
|
|
79
|
+
}
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Get towns by city and prefecture.
|
|
85
|
+
* @param {string} city - e.g., '千代田区'
|
|
86
|
+
* @param {string} prefecture - e.g., '東京都'
|
|
87
|
+
* @param {Function} [callback]
|
|
88
|
+
* @param {string} [baseUrl]
|
|
89
|
+
* @returns {Promise<any>}
|
|
90
|
+
*/
|
|
91
|
+
export async function onGetTownsByCity(city, prefecture, callback, baseUrl = DEFAULT_API_BASE_URL) {
|
|
92
|
+
const url = `${baseUrl}?method=getTowns&city=${encodeURIComponent(city || '')}&prefecture=${encodeURIComponent(prefecture || '')}`;
|
|
93
|
+
const result = await fetchJson(url);
|
|
94
|
+
if (typeof callback === 'function') {
|
|
95
|
+
callback(result);
|
|
96
|
+
}
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Search address by postal code.
|
|
102
|
+
* @param {string|number} postcode - Japanese postal code (with or without hyphen)
|
|
103
|
+
* @param {boolean} [isResponse=false] - If true, returns the raw location object; otherwise returns formatted address string
|
|
104
|
+
* @param {string} [baseUrl]
|
|
105
|
+
* @returns {Promise<string|object|null>}
|
|
106
|
+
*/
|
|
107
|
+
export async function onSearchAddressByPostcode(postcode, isResponse = false, baseUrl = DEFAULT_API_BASE_URL) {
|
|
108
|
+
const cleanCode = normalizePostal(postcode);
|
|
109
|
+
if (!cleanCode) return isResponse ? null : '';
|
|
110
|
+
|
|
111
|
+
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(cleanCode)}`;
|
|
112
|
+
const response = await fetchJson(url);
|
|
113
|
+
|
|
114
|
+
if (!response) {
|
|
115
|
+
return isResponse ? null : '';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const dataAddress = response?.location;
|
|
119
|
+
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
120
|
+
const address = dataAddress[0];
|
|
121
|
+
if (isResponse) {
|
|
122
|
+
return address;
|
|
123
|
+
}
|
|
124
|
+
return `${address.prefecture || ''}${address.city || ''}${address.town || ''}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return isResponse ? null : '';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Search postal code by address string.
|
|
132
|
+
* @param {string} address - Address keyword (e.g. '東京都千代田区')
|
|
133
|
+
* @param {boolean} [isResponse=false] - If true, returns the raw location object; otherwise returns postal string
|
|
134
|
+
* @param {string} [matching='suffix'] - 'prefix', 'suffix', or 'like'
|
|
135
|
+
* @param {string} [baseUrl]
|
|
136
|
+
* @returns {Promise<string|object|null>}
|
|
137
|
+
*/
|
|
138
|
+
export async function onSearchPostcodeByAddress(
|
|
139
|
+
address,
|
|
140
|
+
isResponse = false,
|
|
141
|
+
matching = 'suffix',
|
|
142
|
+
baseUrl = DEFAULT_API_BASE_URL
|
|
143
|
+
) {
|
|
144
|
+
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
145
|
+
return isResponse ? null : '';
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
149
|
+
const response = await fetchJson(url);
|
|
150
|
+
|
|
151
|
+
if (!response) {
|
|
152
|
+
return isResponse ? null : '';
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const dataAddress = response?.location;
|
|
156
|
+
if (Array.isArray(dataAddress) && dataAddress.length > 0) {
|
|
157
|
+
const item = dataAddress[0];
|
|
158
|
+
return isResponse ? item : item?.postal || '';
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return isResponse ? null : '';
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// -------------------------------------------------------------
|
|
165
|
+
// Modern Idiomatic Aliases
|
|
166
|
+
// -------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Search full address by postal code.
|
|
170
|
+
* @param {string|number} postal
|
|
171
|
+
* @param {object} [options]
|
|
172
|
+
* @param {boolean} [options.raw=false]
|
|
173
|
+
* @param {boolean} [options.all=false] - Return array of all matched locations
|
|
174
|
+
* @param {string} [options.baseUrl]
|
|
175
|
+
* @returns {Promise<string|object|object[]|null>}
|
|
176
|
+
*/
|
|
177
|
+
export async function searchAddressByPostal(postal, { raw = false, all = false, baseUrl = DEFAULT_API_BASE_URL } = {}) {
|
|
178
|
+
const clean = normalizePostal(postal);
|
|
179
|
+
if (!clean) return all ? [] : raw ? null : '';
|
|
180
|
+
|
|
181
|
+
const url = `${baseUrl}?method=searchByPostal&postal=${encodeURIComponent(clean)}`;
|
|
182
|
+
const response = await fetchJson(url);
|
|
183
|
+
const locations = response?.location || [];
|
|
184
|
+
|
|
185
|
+
if (!locations.length) {
|
|
186
|
+
return all ? [] : raw ? null : '';
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (all) {
|
|
190
|
+
return locations;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const first = locations[0];
|
|
194
|
+
if (raw) {
|
|
195
|
+
return first;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return `${first.prefecture || ''}${first.city || ''}${first.town || ''}`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Search postal code by address keyword.
|
|
203
|
+
* @param {string} address
|
|
204
|
+
* @param {object} [options]
|
|
205
|
+
* @param {boolean} [options.raw=false]
|
|
206
|
+
* @param {boolean} [options.all=false]
|
|
207
|
+
* @param {'prefix'|'suffix'|'like'} [options.matching='suffix']
|
|
208
|
+
* @param {string} [options.baseUrl]
|
|
209
|
+
* @returns {Promise<string|object|object[]|null>}
|
|
210
|
+
*/
|
|
211
|
+
export async function searchPostalByAddress(
|
|
212
|
+
address,
|
|
213
|
+
{ raw = false, all = false, matching = 'suffix', baseUrl = DEFAULT_API_BASE_URL } = {}
|
|
214
|
+
) {
|
|
215
|
+
if (!address || typeof address !== 'string' || !address.trim()) {
|
|
216
|
+
return all ? [] : raw ? null : '';
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const url = `${baseUrl}?method=suggest&matching=${encodeURIComponent(matching)}&keyword=${encodeURIComponent(address.trim())}`;
|
|
220
|
+
const response = await fetchJson(url);
|
|
221
|
+
const locations = response?.location || [];
|
|
222
|
+
|
|
223
|
+
if (!locations.length) {
|
|
224
|
+
return all ? [] : raw ? null : '';
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (all) {
|
|
228
|
+
return locations;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const first = locations[0];
|
|
232
|
+
return raw ? first : first.postal || '';
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Get areas in Japan (Hokkaido, Tohoku, Kanto, Chubu, Kinki, Chugoku, Shikoku, Kyushu).
|
|
237
|
+
* @param {string} [baseUrl]
|
|
238
|
+
* @returns {Promise<string[]>}
|
|
239
|
+
*/
|
|
240
|
+
export async function getAreas(baseUrl = DEFAULT_API_BASE_URL) {
|
|
241
|
+
const url = `${baseUrl}?method=getAreas`;
|
|
242
|
+
const response = await fetchJson(url);
|
|
243
|
+
return response?.area || [];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Get prefectures in an area.
|
|
248
|
+
* @param {string} area
|
|
249
|
+
* @param {string} [baseUrl]
|
|
250
|
+
* @returns {Promise<string[]>}
|
|
251
|
+
*/
|
|
252
|
+
export async function getPrefectures(area, baseUrl = DEFAULT_API_BASE_URL) {
|
|
253
|
+
const response = await getPrefecturesByArea(area, null, baseUrl);
|
|
254
|
+
return response?.prefecture || [];
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Get cities in a prefecture.
|
|
259
|
+
* @param {string} prefecture
|
|
260
|
+
* @param {string} [area]
|
|
261
|
+
* @param {string} [baseUrl]
|
|
262
|
+
* @returns {Promise<string[]>}
|
|
263
|
+
*/
|
|
264
|
+
export async function getCities(prefecture, area = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
265
|
+
const response = await onGetCitiesByPrefecture(area, prefecture, null, baseUrl);
|
|
266
|
+
const locations = response?.location || [];
|
|
267
|
+
return locations.map((item) => (typeof item === 'string' ? item : item.city)).filter(Boolean);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Get towns in a city.
|
|
272
|
+
* @param {string} city
|
|
273
|
+
* @param {string} [prefecture]
|
|
274
|
+
* @param {string} [baseUrl]
|
|
275
|
+
* @returns {Promise<string[]>}
|
|
276
|
+
*/
|
|
277
|
+
export async function getTowns(city, prefecture = '', baseUrl = DEFAULT_API_BASE_URL) {
|
|
278
|
+
const response = await onGetTownsByCity(city, prefecture, null, baseUrl);
|
|
279
|
+
const locations = response?.location || [];
|
|
280
|
+
return locations.map((item) => (typeof item === 'string' ? item : item.town)).filter(Boolean);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export default {
|
|
284
|
+
DEFAULT_API_BASE_URL,
|
|
285
|
+
normalizePostal,
|
|
286
|
+
getPrefecturesByArea,
|
|
287
|
+
onGetCitiesByPrefecture,
|
|
288
|
+
onGetTownsByCity,
|
|
289
|
+
onSearchAddressByPostcode,
|
|
290
|
+
onSearchPostcodeByAddress,
|
|
291
|
+
searchAddressByPostal,
|
|
292
|
+
searchPostalByAddress,
|
|
293
|
+
getAreas,
|
|
294
|
+
getPrefectures,
|
|
295
|
+
getCities,
|
|
296
|
+
getTowns
|
|
297
|
+
};
|