@cp949/japanpost-react 1.0.3 → 1.0.4

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 (33) hide show
  1. package/dist/client.d.ts +296 -1
  2. package/dist/client.es.js +493 -1
  3. package/dist/index.d.ts +291 -1
  4. package/dist/index.es.js +512 -281
  5. package/package.json +4 -7
  6. package/dist/src/client.d.ts +0 -7
  7. package/dist/src/client.d.ts.map +0 -1
  8. package/dist/src/components/AddressSearchInput.d.ts +0 -8
  9. package/dist/src/components/AddressSearchInput.d.ts.map +0 -1
  10. package/dist/src/components/PostalCodeInput.d.ts +0 -8
  11. package/dist/src/components/PostalCodeInput.d.ts.map +0 -1
  12. package/dist/src/core/errors.d.ts +0 -11
  13. package/dist/src/core/errors.d.ts.map +0 -1
  14. package/dist/src/core/formatters.d.ts +0 -12
  15. package/dist/src/core/formatters.d.ts.map +0 -1
  16. package/dist/src/core/normalizers.d.ts +0 -7
  17. package/dist/src/core/normalizers.d.ts.map +0 -1
  18. package/dist/src/core/types.d.ts +0 -261
  19. package/dist/src/core/types.d.ts.map +0 -1
  20. package/dist/src/core/validators.d.ts +0 -6
  21. package/dist/src/core/validators.d.ts.map +0 -1
  22. package/dist/src/index.d.ts +0 -11
  23. package/dist/src/index.d.ts.map +0 -1
  24. package/dist/src/react/toJapanAddressError.d.ts +0 -8
  25. package/dist/src/react/toJapanAddressError.d.ts.map +0 -1
  26. package/dist/src/react/useJapanAddress.d.ts +0 -8
  27. package/dist/src/react/useJapanAddress.d.ts.map +0 -1
  28. package/dist/src/react/useJapanAddressSearch.d.ts +0 -7
  29. package/dist/src/react/useJapanAddressSearch.d.ts.map +0 -1
  30. package/dist/src/react/useJapanPostalCode.d.ts +0 -7
  31. package/dist/src/react/useJapanPostalCode.d.ts.map +0 -1
  32. package/dist/src/react/useLatestRequestState.d.ts +0 -23
  33. package/dist/src/react/useLatestRequestState.d.ts.map +0 -1
package/dist/index.es.js CHANGED
@@ -1,299 +1,530 @@
1
- import { useCallback as e, useEffect as t, useMemo as n, useRef as r, useState as i } from "react";
2
- import { jsx as a, jsxs as o } from "react/jsx-runtime";
3
- //#region src/components/AddressSearchInput.tsx
4
- function s({ defaultValue: e = "", value: t, disabled: n, label: r = "Address keyword", buttonLabel: s = "Search", inputProps: c, buttonProps: l, onChange: u, onSearch: d }) {
5
- let [f, p] = i(e), m = t ?? f;
6
- function h(e) {
7
- e.preventDefault(), d(m.trim());
8
- }
9
- function g(e) {
10
- t === void 0 && p(e), u?.(e);
11
- }
12
- return /* @__PURE__ */ o("form", {
13
- onSubmit: h,
14
- children: [/* @__PURE__ */ o("label", { children: [r, /* @__PURE__ */ a("input", {
15
- ...c,
16
- disabled: n,
17
- value: m,
18
- onChange: (e) => g(e.target.value)
19
- })] }), /* @__PURE__ */ a("button", {
20
- ...l,
21
- disabled: n,
22
- type: "submit",
23
- children: s
24
- })]
25
- });
1
+ import { useState, useMemo, useRef, useCallback, useEffect } from 'react';
2
+ import { jsxs, jsx } from 'react/jsx-runtime';
3
+
4
+ // src/components/AddressSearchInput.tsx
5
+ function AddressSearchInput({
6
+ defaultValue = "",
7
+ value,
8
+ disabled,
9
+ label = "Address keyword",
10
+ buttonLabel = "Search",
11
+ inputProps,
12
+ buttonProps,
13
+ onChange,
14
+ onSearch
15
+ }) {
16
+ const [internalValue, setInternalValue] = useState(defaultValue);
17
+ const currentValue = value ?? internalValue;
18
+ function handleSubmit(event) {
19
+ event.preventDefault();
20
+ onSearch(currentValue.trim());
21
+ }
22
+ function handleChange(nextValue) {
23
+ if (value === void 0) {
24
+ setInternalValue(nextValue);
25
+ }
26
+ onChange?.(nextValue);
27
+ }
28
+ return /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, children: [
29
+ /* @__PURE__ */ jsxs("label", { children: [
30
+ label,
31
+ /* @__PURE__ */ jsx(
32
+ "input",
33
+ {
34
+ ...inputProps,
35
+ disabled,
36
+ value: currentValue,
37
+ onChange: (event) => handleChange(event.target.value)
38
+ }
39
+ )
40
+ ] }),
41
+ /* @__PURE__ */ jsx("button", { ...buttonProps, disabled, type: "submit", children: buttonLabel })
42
+ ] });
26
43
  }
27
- //#endregion
28
- //#region src/core/formatters.ts
29
- function c(e) {
30
- return e.replace(/[^\d]/g, "");
44
+
45
+ // src/core/formatters.ts
46
+ function normalizeJapanPostalCode(value) {
47
+ return value.replace(/[^\d]/g, "");
31
48
  }
32
- function l(e) {
33
- let t = c(e);
34
- return t.length === 7 ? `${t.slice(0, 3)}-${t.slice(3)}` : t;
49
+ function formatJapanPostalCode(value) {
50
+ const normalized = normalizeJapanPostalCode(value);
51
+ if (normalized.length !== 7) {
52
+ return normalized;
53
+ }
54
+ return `${normalized.slice(0, 3)}-${normalized.slice(3)}`;
35
55
  }
36
- //#endregion
37
- //#region src/components/PostalCodeInput.tsx
38
- function u({ defaultValue: e = "", value: t, disabled: n, label: r = "Postal code", buttonLabel: s = "Search", inputProps: l, buttonProps: u, onChange: d, onSearch: f }) {
39
- let [p, m] = i(e), h = t ?? p;
40
- function g(e) {
41
- e.preventDefault(), f(c(h));
42
- }
43
- function _(e) {
44
- t === void 0 && m(e), d?.(e);
45
- }
46
- return /* @__PURE__ */ o("form", {
47
- onSubmit: g,
48
- children: [/* @__PURE__ */ o("label", { children: [r, /* @__PURE__ */ a("input", {
49
- ...l,
50
- disabled: n,
51
- inputMode: l?.inputMode ?? "numeric",
52
- value: h,
53
- onChange: (e) => _(e.target.value)
54
- })] }), /* @__PURE__ */ a("button", {
55
- ...u,
56
- disabled: n,
57
- type: "submit",
58
- children: s
59
- })]
60
- });
56
+ function PostalCodeInput({
57
+ defaultValue = "",
58
+ value,
59
+ disabled,
60
+ label = "Postal code",
61
+ buttonLabel = "Search",
62
+ inputProps,
63
+ buttonProps,
64
+ onChange,
65
+ onSearch
66
+ }) {
67
+ const [internalValue, setInternalValue] = useState(defaultValue);
68
+ const currentValue = value ?? internalValue;
69
+ function handleSubmit(event) {
70
+ event.preventDefault();
71
+ onSearch(normalizeJapanPostalCode(currentValue));
72
+ }
73
+ function handleChange(nextValue) {
74
+ if (value === void 0) {
75
+ setInternalValue(nextValue);
76
+ }
77
+ onChange?.(nextValue);
78
+ }
79
+ return /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, children: [
80
+ /* @__PURE__ */ jsxs("label", { children: [
81
+ label,
82
+ /* @__PURE__ */ jsx(
83
+ "input",
84
+ {
85
+ ...inputProps,
86
+ disabled,
87
+ inputMode: inputProps?.inputMode ?? "numeric",
88
+ value: currentValue,
89
+ onChange: (event) => handleChange(event.target.value)
90
+ }
91
+ )
92
+ ] }),
93
+ /* @__PURE__ */ jsx("button", { ...buttonProps, disabled, type: "submit", children: buttonLabel })
94
+ ] });
61
95
  }
62
- //#endregion
63
- //#region src/core/errors.ts
64
- function d(e, t, n) {
65
- let r = Error(t);
66
- return r.name = "JapanAddressError", r.code = e, r.cause = n?.cause, r.status = n?.status, r;
96
+
97
+ // src/core/errors.ts
98
+ function createJapanAddressError(code, message, options) {
99
+ const error = new Error(message);
100
+ error.name = "JapanAddressError";
101
+ error.code = code;
102
+ error.cause = options?.cause;
103
+ error.status = options?.status;
104
+ return error;
67
105
  }
68
- //#endregion
69
- //#region src/core/normalizers.ts
70
- function f(e) {
71
- return e.filter(Boolean).join(" ").trim();
106
+
107
+ // src/core/normalizers.ts
108
+ function joinAddressParts(parts) {
109
+ return parts.filter(Boolean).join(" ").trim();
72
110
  }
73
- function p(e) {
74
- let t = f([
75
- e.prefecture,
76
- e.city,
77
- e.town,
78
- e.detail ?? ""
79
- ]);
80
- return {
81
- postalCode: e.postalCode,
82
- prefecture: e.prefecture,
83
- prefectureKana: e.prefectureKana,
84
- city: e.city,
85
- cityKana: e.cityKana,
86
- town: e.town,
87
- townKana: e.townKana,
88
- address: t,
89
- provider: "japan-post"
90
- };
111
+ function normalizeJapanPostAddressRecord(record) {
112
+ const address = joinAddressParts([
113
+ record.prefecture,
114
+ record.city,
115
+ record.town,
116
+ record.detail ?? ""
117
+ ]);
118
+ return {
119
+ postalCode: record.postalCode,
120
+ prefecture: record.prefecture,
121
+ prefectureKana: record.prefectureKana,
122
+ city: record.city,
123
+ cityKana: record.cityKana,
124
+ town: record.town,
125
+ townKana: record.townKana,
126
+ address,
127
+ provider: "japan-post"
128
+ };
91
129
  }
92
- //#endregion
93
- //#region src/core/validators.ts
94
- function m(e) {
95
- return /^\d{7}$/.test(c(e));
130
+
131
+ // src/core/validators.ts
132
+ function isValidJapanPostalCode(value) {
133
+ return /^\d{7}$/.test(normalizeJapanPostalCode(value));
96
134
  }
97
- //#endregion
98
- //#region src/react/toJapanAddressError.ts
99
- function h(e) {
100
- return typeof e == "object" && e && "code" in e && typeof e.code == "string" ? e : d("data_source_error", e instanceof Error ? e.message : "Unknown error", { cause: e });
135
+
136
+ // src/react/toJapanAddressError.ts
137
+ function toJapanAddressError(error) {
138
+ if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "string") {
139
+ return error;
140
+ }
141
+ return createJapanAddressError(
142
+ "data_source_error",
143
+ error instanceof Error ? error.message : "Unknown error",
144
+ {
145
+ cause: error
146
+ }
147
+ );
101
148
  }
102
- //#endregion
103
- //#region src/react/useLatestRequestState.ts
104
- function g() {
105
- let n = r(0), a = r(!0), o = r(null), [s, c] = i(!1), [l, u] = i(null), [d, f] = i(null), p = e((e) => a.current && e === n.current, []), m = e(() => {
106
- n.current += 1, o.current?.abort(), o.current = null;
107
- }, []);
108
- t(() => (a.current = !0, () => {
109
- a.current = !1, m();
110
- }), [m]);
111
- let h = e(() => {
112
- let e = n.current + 1;
113
- n.current = e, o.current?.abort();
114
- let t = new AbortController();
115
- return o.current = t, c(!0), f(null), {
116
- requestId: e,
117
- signal: t.signal
118
- };
119
- }, []), g = e((e, t) => {
120
- p(e) && u(t);
121
- }, [p]), _ = e((e, t) => (p(e) && (f(t), u(null)), null), [p]), v = e(() => {
122
- m(), c(!1);
123
- }, [m]);
124
- return {
125
- loading: s,
126
- data: l,
127
- error: d,
128
- beginRequest: h,
129
- setSuccess: g,
130
- setFailure: _,
131
- finishRequest: e((e) => {
132
- p(e) && (c(!1), o.current = null);
133
- }, [p]),
134
- cancel: v,
135
- reset: e(() => {
136
- v(), u(null), f(null);
137
- }, [v])
138
- };
149
+ function useLatestRequestState() {
150
+ const requestIdRef = useRef(0);
151
+ const isMountedRef = useRef(true);
152
+ const abortControllerRef = useRef(null);
153
+ const [loading, setLoading] = useState(false);
154
+ const [data, setData] = useState(null);
155
+ const [error, setError] = useState(null);
156
+ const isCurrentRequest = useCallback((requestId) => {
157
+ return isMountedRef.current && requestId === requestIdRef.current;
158
+ }, []);
159
+ const invalidateCurrentRequest = useCallback(() => {
160
+ requestIdRef.current += 1;
161
+ abortControllerRef.current?.abort();
162
+ abortControllerRef.current = null;
163
+ }, []);
164
+ useEffect(() => {
165
+ isMountedRef.current = true;
166
+ return () => {
167
+ isMountedRef.current = false;
168
+ invalidateCurrentRequest();
169
+ };
170
+ }, [invalidateCurrentRequest]);
171
+ const beginRequest = useCallback(() => {
172
+ const requestId = requestIdRef.current + 1;
173
+ requestIdRef.current = requestId;
174
+ abortControllerRef.current?.abort();
175
+ const abortController = new AbortController();
176
+ abortControllerRef.current = abortController;
177
+ setLoading(true);
178
+ setError(null);
179
+ return {
180
+ requestId,
181
+ signal: abortController.signal
182
+ };
183
+ }, []);
184
+ const setSuccess = useCallback((requestId, result) => {
185
+ if (isCurrentRequest(requestId)) {
186
+ setData(result);
187
+ }
188
+ }, [isCurrentRequest]);
189
+ const setFailure = useCallback(
190
+ (requestId, nextError) => {
191
+ if (isCurrentRequest(requestId)) {
192
+ setError(nextError);
193
+ setData(null);
194
+ }
195
+ return null;
196
+ },
197
+ [isCurrentRequest]
198
+ );
199
+ const cancel = useCallback(() => {
200
+ invalidateCurrentRequest();
201
+ setLoading(false);
202
+ }, [invalidateCurrentRequest]);
203
+ const finishRequest = useCallback((requestId) => {
204
+ if (isCurrentRequest(requestId)) {
205
+ setLoading(false);
206
+ abortControllerRef.current = null;
207
+ }
208
+ }, [isCurrentRequest]);
209
+ const reset = useCallback(() => {
210
+ cancel();
211
+ setData(null);
212
+ setError(null);
213
+ }, [cancel]);
214
+ return {
215
+ loading,
216
+ data,
217
+ error,
218
+ beginRequest,
219
+ setSuccess,
220
+ setFailure,
221
+ finishRequest,
222
+ cancel,
223
+ reset
224
+ };
139
225
  }
140
- //#endregion
141
- //#region src/react/useJapanAddressSearch.ts
142
- function _(e) {
143
- if (e) return e;
144
- throw Error("useJapanAddressSearch requires options.dataSource");
226
+
227
+ // src/react/useJapanAddressSearch.ts
228
+ function resolveAddressSearchDataSource(dataSource) {
229
+ if (dataSource) {
230
+ return dataSource;
231
+ }
232
+ throw new Error("useJapanAddressSearch requires options.dataSource");
145
233
  }
146
- function v(e) {
147
- return e?.trim() || void 0;
234
+ function normalizeSearchText(value) {
235
+ const normalized = value?.trim();
236
+ return normalized ? normalized : void 0;
148
237
  }
149
- function y(e) {
150
- let t = typeof e == "string" ? { addressQuery: e } : e, n = v(t.addressQuery), r = v(t.prefCode), i = v(t.prefName), a = v(t.prefKana), o = v(t.prefRoma), s = v(t.cityCode), c = v(t.cityName), l = v(t.cityKana), u = v(t.cityRoma), d = v(t.townName), f = v(t.townKana), p = v(t.townRoma);
151
- return n === void 0 && r === void 0 && i === void 0 && a === void 0 && o === void 0 && s === void 0 && c === void 0 && l === void 0 && u === void 0 && d === void 0 && f === void 0 && p === void 0 ? null : {
152
- ...n === void 0 ? {} : { addressQuery: n },
153
- ...r === void 0 ? {} : { prefCode: r },
154
- ...i === void 0 ? {} : { prefName: i },
155
- ...a === void 0 ? {} : { prefKana: a },
156
- ...o === void 0 ? {} : { prefRoma: o },
157
- ...s === void 0 ? {} : { cityCode: s },
158
- ...c === void 0 ? {} : { cityName: c },
159
- ...l === void 0 ? {} : { cityKana: l },
160
- ...u === void 0 ? {} : { cityRoma: u },
161
- ...d === void 0 ? {} : { townName: d },
162
- ...f === void 0 ? {} : { townKana: f },
163
- ...p === void 0 ? {} : { townRoma: p },
164
- pageNumber: t.pageNumber ?? 0,
165
- rowsPerPage: t.rowsPerPage ?? 100,
166
- ...t.includeCityDetails === void 0 ? {} : { includeCityDetails: t.includeCityDetails },
167
- ...t.includePrefectureDetails === void 0 ? {} : { includePrefectureDetails: t.includePrefectureDetails }
168
- };
238
+ function normalizeAddressSearchInput(input) {
239
+ const request = typeof input === "string" ? { addressQuery: input } : input;
240
+ const addressQuery = normalizeSearchText(request.addressQuery);
241
+ const prefCode = normalizeSearchText(request.prefCode);
242
+ const prefName = normalizeSearchText(request.prefName);
243
+ const prefKana = normalizeSearchText(request.prefKana);
244
+ const prefRoma = normalizeSearchText(request.prefRoma);
245
+ const cityCode = normalizeSearchText(request.cityCode);
246
+ const cityName = normalizeSearchText(request.cityName);
247
+ const cityKana = normalizeSearchText(request.cityKana);
248
+ const cityRoma = normalizeSearchText(request.cityRoma);
249
+ const townName = normalizeSearchText(request.townName);
250
+ const townKana = normalizeSearchText(request.townKana);
251
+ const townRoma = normalizeSearchText(request.townRoma);
252
+ if (addressQuery === void 0 && prefCode === void 0 && prefName === void 0 && prefKana === void 0 && prefRoma === void 0 && cityCode === void 0 && cityName === void 0 && cityKana === void 0 && cityRoma === void 0 && townName === void 0 && townKana === void 0 && townRoma === void 0) {
253
+ return null;
254
+ }
255
+ return {
256
+ ...addressQuery === void 0 ? {} : { addressQuery },
257
+ ...prefCode === void 0 ? {} : { prefCode },
258
+ ...prefName === void 0 ? {} : { prefName },
259
+ ...prefKana === void 0 ? {} : { prefKana },
260
+ ...prefRoma === void 0 ? {} : { prefRoma },
261
+ ...cityCode === void 0 ? {} : { cityCode },
262
+ ...cityName === void 0 ? {} : { cityName },
263
+ ...cityKana === void 0 ? {} : { cityKana },
264
+ ...cityRoma === void 0 ? {} : { cityRoma },
265
+ ...townName === void 0 ? {} : { townName },
266
+ ...townKana === void 0 ? {} : { townKana },
267
+ ...townRoma === void 0 ? {} : { townRoma },
268
+ pageNumber: request.pageNumber ?? 0,
269
+ rowsPerPage: request.rowsPerPage ?? 100,
270
+ ...request.includeCityDetails === void 0 ? {} : {
271
+ includeCityDetails: request.includeCityDetails
272
+ },
273
+ ...request.includePrefectureDetails === void 0 ? {} : {
274
+ includePrefectureDetails: request.includePrefectureDetails
275
+ }
276
+ };
169
277
  }
170
- function b(e) {
171
- return e.aborted ? Promise.resolve(null) : new Promise((t) => {
172
- let n = () => {
173
- e.removeEventListener("abort", n), t(null);
174
- };
175
- e.addEventListener("abort", n, { once: !0 });
176
- });
278
+ function waitForAbort(signal) {
279
+ if (signal.aborted) {
280
+ return Promise.resolve(null);
281
+ }
282
+ return new Promise((resolve) => {
283
+ const onAbort = () => {
284
+ signal.removeEventListener("abort", onAbort);
285
+ resolve(null);
286
+ };
287
+ signal.addEventListener("abort", onAbort, { once: true });
288
+ });
177
289
  }
178
- function x(i) {
179
- let a = n(() => _(i.dataSource), [i.dataSource]), o = i.debounceMs ?? 0, s = r(null), c = r(null), { loading: l, data: u, error: f, beginRequest: p, setSuccess: m, setFailure: v, finishRequest: x, cancel: S, reset: C } = g(), w = e((e) => {
180
- s.current !== null && (globalThis.clearTimeout(s.current), s.current = null), c.current?.(e), c.current = null;
181
- }, []);
182
- t(() => () => {
183
- w(null);
184
- }, [w]);
185
- let T = e(() => {
186
- w(null), C();
187
- }, [w, C]), E = e(() => {
188
- w(null), S();
189
- }, [w, S]), D = e(async (e, t, n) => {
190
- try {
191
- let r = { signal: t }, i = a.searchAddress(n, r), o = await Promise.race([i, b(t)]);
192
- return t.aborted || o === null ? null : (m(e, o), o);
193
- } catch (n) {
194
- return t.aborted ? null : v(e, h(n));
195
- } finally {
196
- x(e);
197
- }
198
- }, [
199
- a,
200
- x,
201
- v,
202
- m
203
- ]);
204
- return {
205
- loading: l,
206
- data: u,
207
- error: f,
208
- cancel: E,
209
- reset: T,
210
- search: e((e) => {
211
- let t = y(e), { requestId: n, signal: r } = p();
212
- if (w(null), t === null) {
213
- let e = v(n, d("invalid_query", "Address query is required"));
214
- return x(n), Promise.resolve(e);
215
- }
216
- return o <= 0 ? new Promise((e) => {
217
- c.current = e, D(n, r, t).then((t) => {
218
- e(t), c.current === e && (c.current = null);
219
- });
220
- }) : new Promise((e) => {
221
- c.current = e, s.current = globalThis.setTimeout(() => {
222
- s.current = null;
223
- let e = c.current;
224
- c.current = null, D(n, r, t).then((t) => {
225
- e?.(t);
226
- });
227
- }, o);
228
- });
229
- }, [
230
- p,
231
- w,
232
- o,
233
- D
234
- ])
235
- };
290
+ function useJapanAddressSearch(options) {
291
+ const dataSource = useMemo(
292
+ () => resolveAddressSearchDataSource(options.dataSource),
293
+ [options.dataSource]
294
+ );
295
+ const debounceMs = options.debounceMs ?? 0;
296
+ const timeoutRef = useRef(
297
+ null
298
+ );
299
+ const pendingResolveRef = useRef(null);
300
+ const {
301
+ loading,
302
+ data,
303
+ error,
304
+ beginRequest,
305
+ setSuccess,
306
+ setFailure,
307
+ finishRequest,
308
+ cancel: cancelRequestState,
309
+ reset: resetRequestState
310
+ } = useLatestRequestState();
311
+ const clearPendingDebounce = useCallback(
312
+ (result) => {
313
+ if (timeoutRef.current !== null) {
314
+ globalThis.clearTimeout(timeoutRef.current);
315
+ timeoutRef.current = null;
316
+ }
317
+ pendingResolveRef.current?.(result);
318
+ pendingResolveRef.current = null;
319
+ },
320
+ []
321
+ );
322
+ useEffect(() => {
323
+ return () => {
324
+ clearPendingDebounce(null);
325
+ };
326
+ }, [clearPendingDebounce]);
327
+ const reset = useCallback(() => {
328
+ clearPendingDebounce(null);
329
+ resetRequestState();
330
+ }, [clearPendingDebounce, resetRequestState]);
331
+ const cancel = useCallback(() => {
332
+ clearPendingDebounce(null);
333
+ cancelRequestState();
334
+ }, [clearPendingDebounce, cancelRequestState]);
335
+ const runSearch = useCallback(async (requestId, signal, request) => {
336
+ try {
337
+ const requestOptions = {
338
+ signal
339
+ };
340
+ const searchPromise = dataSource.searchAddress(
341
+ request,
342
+ requestOptions
343
+ );
344
+ const result = await Promise.race([
345
+ searchPromise,
346
+ waitForAbort(signal)
347
+ ]);
348
+ if (signal.aborted || result === null) {
349
+ return null;
350
+ }
351
+ setSuccess(requestId, result);
352
+ return result;
353
+ } catch (caughtError) {
354
+ if (signal.aborted) {
355
+ return null;
356
+ }
357
+ return setFailure(requestId, toJapanAddressError(caughtError));
358
+ } finally {
359
+ finishRequest(requestId);
360
+ }
361
+ }, [dataSource, finishRequest, setFailure, setSuccess]);
362
+ const search = useCallback((input) => {
363
+ const request = normalizeAddressSearchInput(input);
364
+ const { requestId, signal } = beginRequest();
365
+ clearPendingDebounce(null);
366
+ if (request === null) {
367
+ const result = setFailure(
368
+ requestId,
369
+ createJapanAddressError(
370
+ "invalid_query",
371
+ "Address query is required"
372
+ )
373
+ );
374
+ finishRequest(requestId);
375
+ return Promise.resolve(result);
376
+ }
377
+ if (debounceMs <= 0) {
378
+ return new Promise((resolve) => {
379
+ pendingResolveRef.current = resolve;
380
+ void runSearch(requestId, signal, request).then((result) => {
381
+ resolve(result);
382
+ if (pendingResolveRef.current === resolve) {
383
+ pendingResolveRef.current = null;
384
+ }
385
+ });
386
+ });
387
+ }
388
+ return new Promise((resolve) => {
389
+ pendingResolveRef.current = resolve;
390
+ timeoutRef.current = globalThis.setTimeout(() => {
391
+ timeoutRef.current = null;
392
+ const pendingResolve = pendingResolveRef.current;
393
+ pendingResolveRef.current = null;
394
+ void runSearch(requestId, signal, request).then((result) => {
395
+ pendingResolve?.(result);
396
+ });
397
+ }, debounceMs);
398
+ });
399
+ }, [beginRequest, clearPendingDebounce, debounceMs, runSearch]);
400
+ return {
401
+ loading,
402
+ data,
403
+ error,
404
+ cancel,
405
+ reset,
406
+ search
407
+ };
236
408
  }
237
- //#endregion
238
- //#region src/react/useJapanPostalCode.ts
239
- function S(e) {
240
- if (e) return e;
241
- throw Error("useJapanPostalCode requires options.dataSource");
409
+ function resolvePostalCodeDataSource(dataSource) {
410
+ if (dataSource) {
411
+ return dataSource;
412
+ }
413
+ throw new Error("useJapanPostalCode requires options.dataSource");
242
414
  }
243
- function C(t) {
244
- let r = n(() => S(t.dataSource), [t.dataSource]), { loading: i, data: a, error: o, beginRequest: s, setSuccess: l, setFailure: u, finishRequest: f, cancel: p, reset: m } = g();
245
- return {
246
- loading: i,
247
- data: a,
248
- error: o,
249
- cancel: p,
250
- reset: m,
251
- search: e(async (e) => {
252
- let { requestId: t, signal: n } = s();
253
- try {
254
- let i = typeof e == "string" ? { postalCode: e } : e, a = c(i.postalCode);
255
- if (!/^\d{3,7}$/.test(a)) throw d("invalid_postal_code", "Postal code must contain between 3 and 7 digits");
256
- let o = { signal: n }, s = {
257
- postalCode: a,
258
- pageNumber: i.pageNumber ?? 0,
259
- rowsPerPage: i.rowsPerPage ?? 100,
260
- ...i.includeParenthesesTown === void 0 ? {} : { includeParenthesesTown: i.includeParenthesesTown }
261
- }, u = await r.lookupPostalCode(s, o);
262
- return n.aborted ? null : (l(t, u), u);
263
- } catch (e) {
264
- return n.aborted ? null : u(t, h(e));
265
- } finally {
266
- f(t);
267
- }
268
- }, [
269
- s,
270
- r,
271
- f,
272
- u,
273
- l
274
- ])
275
- };
415
+ function useJapanPostalCode(options) {
416
+ const dataSource = useMemo(
417
+ () => resolvePostalCodeDataSource(options.dataSource),
418
+ [options.dataSource]
419
+ );
420
+ const {
421
+ loading,
422
+ data,
423
+ error,
424
+ beginRequest,
425
+ setSuccess,
426
+ setFailure,
427
+ finishRequest,
428
+ cancel,
429
+ reset
430
+ } = useLatestRequestState();
431
+ const search = useCallback(
432
+ async (input) => {
433
+ const { requestId, signal } = beginRequest();
434
+ try {
435
+ const requestInput = typeof input === "string" ? { postalCode: input } : input;
436
+ const postalCode = normalizeJapanPostalCode(requestInput.postalCode);
437
+ if (!/^\d{3,7}$/.test(postalCode)) {
438
+ throw createJapanAddressError(
439
+ "invalid_postal_code",
440
+ "Postal code must contain between 3 and 7 digits"
441
+ );
442
+ }
443
+ const requestOptions = {
444
+ signal
445
+ };
446
+ const request = {
447
+ postalCode,
448
+ pageNumber: requestInput.pageNumber ?? 0,
449
+ rowsPerPage: requestInput.rowsPerPage ?? 100,
450
+ ...requestInput.includeParenthesesTown === void 0 ? {} : {
451
+ includeParenthesesTown: requestInput.includeParenthesesTown
452
+ }
453
+ };
454
+ const result = await dataSource.lookupPostalCode(
455
+ request,
456
+ requestOptions
457
+ );
458
+ if (signal.aborted) {
459
+ return null;
460
+ }
461
+ setSuccess(requestId, result);
462
+ return result;
463
+ } catch (caughtError) {
464
+ if (signal.aborted) {
465
+ return null;
466
+ }
467
+ return setFailure(requestId, toJapanAddressError(caughtError));
468
+ } finally {
469
+ finishRequest(requestId);
470
+ }
471
+ },
472
+ [beginRequest, dataSource, finishRequest, setFailure, setSuccess]
473
+ );
474
+ return {
475
+ loading,
476
+ data,
477
+ error,
478
+ cancel,
479
+ reset,
480
+ search
481
+ };
276
482
  }
277
- //#endregion
278
- //#region src/react/useJapanAddress.ts
279
- function w(t) {
280
- let r = n(() => {
281
- if (t.dataSource) return t.dataSource;
282
- throw Error("useJapanAddress requires options.dataSource");
283
- }, [t.dataSource]), a = C({ dataSource: r }), o = x({
284
- dataSource: r,
285
- debounceMs: t.debounceMs
286
- }), s = a.reset, c = a.search, l = o.reset, u = o.search, [d, f] = i(null), p = e(async (e) => (l(), f("postalCode"), c(e)), [l, c]), m = e(async (e) => (s(), f("addressQuery"), u(e)), [s, u]), h = e(() => {
287
- s(), l(), f(null);
288
- }, [l, s]), g = d === "postalCode" ? a.data : d === "addressQuery" ? o.data : null, _ = d === "postalCode" ? a.error : d === "addressQuery" ? o.error : null;
289
- return {
290
- loading: a.loading || o.loading,
291
- data: g,
292
- error: _,
293
- reset: h,
294
- searchByPostalCode: p,
295
- searchByAddressQuery: m
296
- };
483
+
484
+ // src/react/useJapanAddress.ts
485
+ function useJapanAddress(options) {
486
+ const dataSource = useMemo(() => {
487
+ if (options.dataSource) {
488
+ return options.dataSource;
489
+ }
490
+ throw new Error("useJapanAddress requires options.dataSource");
491
+ }, [options.dataSource]);
492
+ const postalCode = useJapanPostalCode({ dataSource });
493
+ const addressSearch = useJapanAddressSearch({
494
+ dataSource,
495
+ debounceMs: options.debounceMs
496
+ });
497
+ const resetPostalCode = postalCode.reset;
498
+ const searchPostalCode = postalCode.search;
499
+ const resetAddressSearch = addressSearch.reset;
500
+ const searchAddressKeyword = addressSearch.search;
501
+ const [activeSearch, setActiveSearch] = useState(null);
502
+ const searchByPostalCode = useCallback(async (input) => {
503
+ resetAddressSearch();
504
+ setActiveSearch("postalCode");
505
+ return searchPostalCode(input);
506
+ }, [resetAddressSearch, searchPostalCode]);
507
+ const searchByAddressQuery = useCallback(async (input) => {
508
+ resetPostalCode();
509
+ setActiveSearch("addressQuery");
510
+ return searchAddressKeyword(input);
511
+ }, [resetPostalCode, searchAddressKeyword]);
512
+ const reset = useCallback(() => {
513
+ resetPostalCode();
514
+ resetAddressSearch();
515
+ setActiveSearch(null);
516
+ }, [resetAddressSearch, resetPostalCode]);
517
+ const data = activeSearch === "postalCode" ? postalCode.data : activeSearch === "addressQuery" ? addressSearch.data : null;
518
+ const error = activeSearch === "postalCode" ? postalCode.error : activeSearch === "addressQuery" ? addressSearch.error : null;
519
+ return {
520
+ // 사용자는 현재 활성 모드만 보더라도, 내부에서는 두 훅 중 하나라도 정리 중이면 로딩으로 본다.
521
+ loading: postalCode.loading || addressSearch.loading,
522
+ data,
523
+ error,
524
+ reset,
525
+ searchByPostalCode,
526
+ searchByAddressQuery
527
+ };
297
528
  }
298
- //#endregion
299
- export { s as AddressSearchInput, u as PostalCodeInput, d as createJapanAddressError, l as formatJapanPostalCode, m as isValidJapanPostalCode, p as normalizeJapanPostAddressRecord, c as normalizeJapanPostalCode, w as useJapanAddress, x as useJapanAddressSearch, C as useJapanPostalCode };
529
+
530
+ export { AddressSearchInput, PostalCodeInput, createJapanAddressError, formatJapanPostalCode, isValidJapanPostalCode, normalizeJapanPostAddressRecord, normalizeJapanPostalCode, useJapanAddress, useJapanAddressSearch, useJapanPostalCode };