@metamask-previews/geolocation-controller 0.1.3-preview-d67bfdbad → 0.1.3-preview-937b1a1
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/CHANGELOG.md +0 -2
- package/dist/GeolocationController-method-action-types.cjs.map +1 -1
- package/dist/GeolocationController-method-action-types.d.cts +1 -13
- package/dist/GeolocationController-method-action-types.d.cts.map +1 -1
- package/dist/GeolocationController-method-action-types.d.mts +1 -13
- package/dist/GeolocationController-method-action-types.d.mts.map +1 -1
- package/dist/GeolocationController-method-action-types.mjs.map +1 -1
- package/dist/GeolocationController.cjs +6 -44
- package/dist/GeolocationController.cjs.map +1 -1
- package/dist/GeolocationController.d.cts +2 -18
- package/dist/GeolocationController.d.cts.map +1 -1
- package/dist/GeolocationController.d.mts +2 -18
- package/dist/GeolocationController.d.mts.map +1 -1
- package/dist/GeolocationController.mjs +7 -45
- package/dist/GeolocationController.mjs.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service-method-action-types.cjs.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service-method-action-types.d.cts +1 -17
- package/dist/geolocation-api-service/geolocation-api-service-method-action-types.d.cts.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service-method-action-types.d.mts +1 -17
- package/dist/geolocation-api-service/geolocation-api-service-method-action-types.d.mts.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service-method-action-types.mjs.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service.cjs +20 -131
- package/dist/geolocation-api-service/geolocation-api-service.cjs.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service.d.cts +5 -52
- package/dist/geolocation-api-service/geolocation-api-service.d.cts.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service.d.mts +5 -52
- package/dist/geolocation-api-service/geolocation-api-service.d.mts.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service.mjs +19 -128
- package/dist/geolocation-api-service/geolocation-api-service.mjs.map +1 -1
- package/dist/index.cjs +1 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -9,14 +9,11 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _GeolocationApiService_instances, _GeolocationApiService_messenger, _GeolocationApiService_fetch, _GeolocationApiService_url, _GeolocationApiService_ttlMs, _GeolocationApiService_policy,
|
|
12
|
+
var _GeolocationApiService_instances, _GeolocationApiService_messenger, _GeolocationApiService_fetch, _GeolocationApiService_url, _GeolocationApiService_ttlMs, _GeolocationApiService_policy, _GeolocationApiService_cachedLocation, _GeolocationApiService_lastFetchedAt, _GeolocationApiService_fetchPromise, _GeolocationApiService_isCacheValid, _GeolocationApiService_performFetch;
|
|
13
13
|
import { createServicePolicy, HttpError } from "@metamask/controller-utils";
|
|
14
14
|
import { Env } from "../types.mjs";
|
|
15
15
|
const DEFAULT_TTL_MS = 5 * 60 * 1000;
|
|
16
|
-
const ENDPOINT_PATH = '/
|
|
17
|
-
const COUNTRY_PATTERN = /^[A-Z]{2}$/u;
|
|
18
|
-
const REGION_PATTERN = /^[A-Z0-9]{1,3}$/u;
|
|
19
|
-
const TIMEZONE_PATTERN = /^[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)*$/u;
|
|
16
|
+
const ENDPOINT_PATH = '/v1/geolocation';
|
|
20
17
|
// === GENERAL ===
|
|
21
18
|
/**
|
|
22
19
|
* The name of the {@link GeolocationApiService}, used to namespace the
|
|
@@ -28,47 +25,8 @@ export const serviceName = 'GeolocationApiService';
|
|
|
28
25
|
* the API returns an empty / invalid response.
|
|
29
26
|
*/
|
|
30
27
|
export const UNKNOWN_LOCATION = 'UNKNOWN';
|
|
31
|
-
/**
|
|
32
|
-
* Constructs a {@link GeolocationData} with no known fields.
|
|
33
|
-
*
|
|
34
|
-
* @returns Geolocation data where every field is `null`.
|
|
35
|
-
*/
|
|
36
|
-
export function getUnknownGeolocationData() {
|
|
37
|
-
return { country: null, region: null, timezone: null };
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Country codes for which the location code includes the region. This mirrors
|
|
41
|
-
* the legacy `v1` geolocation endpoint, which only appended the subdivision for
|
|
42
|
-
* the United States and Canada (e.g. `US-NY`, `CA-ON`) and returned the country
|
|
43
|
-
* alone for everywhere else.
|
|
44
|
-
*/
|
|
45
|
-
const REGION_APPENDED_COUNTRIES = new Set(['US', 'CA']);
|
|
46
|
-
/**
|
|
47
|
-
* Converts geolocation data to a location code.
|
|
48
|
-
*
|
|
49
|
-
* To preserve backwards compatibility with the legacy `v1` endpoint, the region
|
|
50
|
-
* is appended only for {@link REGION_APPENDED_COUNTRIES} (e.g. `US-NY`,
|
|
51
|
-
* `CA-ON`); all other countries return the country code alone (e.g. `FR`), even
|
|
52
|
-
* when a region is known.
|
|
53
|
-
*
|
|
54
|
-
* @param data - The geolocation data to convert.
|
|
55
|
-
* @returns The location code (e.g. `US-NY`, `FR`), or
|
|
56
|
-
* {@link UNKNOWN_LOCATION} when the country is unknown.
|
|
57
|
-
*/
|
|
58
|
-
export function toLocationCode(data) {
|
|
59
|
-
if (data.country === null) {
|
|
60
|
-
return UNKNOWN_LOCATION;
|
|
61
|
-
}
|
|
62
|
-
if (data.region !== null && REGION_APPENDED_COUNTRIES.has(data.country)) {
|
|
63
|
-
return `${data.country}-${data.region}`;
|
|
64
|
-
}
|
|
65
|
-
return data.country;
|
|
66
|
-
}
|
|
67
28
|
// === MESSENGER ===
|
|
68
|
-
const MESSENGER_EXPOSED_METHODS = [
|
|
69
|
-
'fetchGeolocation',
|
|
70
|
-
'fetchGeolocationData',
|
|
71
|
-
];
|
|
29
|
+
const MESSENGER_EXPOSED_METHODS = ['fetchGeolocation'];
|
|
72
30
|
// === SERVICE DEFINITION ===
|
|
73
31
|
/**
|
|
74
32
|
* Returns the base URL for the geolocation API for the given environment.
|
|
@@ -86,66 +44,18 @@ function getGeolocationUrl(env) {
|
|
|
86
44
|
return `https://geolocation.${envPrefix}api.cx.metamask.io${ENDPOINT_PATH}`;
|
|
87
45
|
}
|
|
88
46
|
/**
|
|
89
|
-
*
|
|
90
|
-
* matches the expected format.
|
|
91
|
-
*
|
|
92
|
-
* @param body - The parsed response body.
|
|
93
|
-
* @param field - The name of the field to read.
|
|
94
|
-
* @param pattern - The pattern the field value must match.
|
|
95
|
-
* @returns The trimmed field value, or `null` when it is missing or invalid.
|
|
96
|
-
*/
|
|
97
|
-
function readValidatedField(body, field, pattern) {
|
|
98
|
-
const value = body[field];
|
|
99
|
-
if (typeof value !== 'string') {
|
|
100
|
-
return null;
|
|
101
|
-
}
|
|
102
|
-
const trimmed = value.trim();
|
|
103
|
-
return pattern.test(trimmed) ? trimmed : null;
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* Parses and validates the geolocation API response body.
|
|
107
|
-
*
|
|
108
|
-
* The endpoint is expected to return JSON such as
|
|
109
|
-
* `{"country":"US","region":"WA","timezone":"America/Los_Angeles"}`. Anything
|
|
110
|
-
* that cannot be parsed, or any individual field that fails validation, is
|
|
111
|
-
* reported as unknown rather than throwing, so that consumers can keep working
|
|
112
|
-
* with partial or missing data.
|
|
113
|
-
*
|
|
114
|
-
* @param raw - The raw response body.
|
|
115
|
-
* @returns The validated geolocation data.
|
|
116
|
-
*/
|
|
117
|
-
function parseGeolocationResponse(raw) {
|
|
118
|
-
let body;
|
|
119
|
-
try {
|
|
120
|
-
body = JSON.parse(raw);
|
|
121
|
-
}
|
|
122
|
-
catch {
|
|
123
|
-
return getUnknownGeolocationData();
|
|
124
|
-
}
|
|
125
|
-
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
|
126
|
-
return getUnknownGeolocationData();
|
|
127
|
-
}
|
|
128
|
-
const record = body;
|
|
129
|
-
return {
|
|
130
|
-
country: readValidatedField(record, 'country', COUNTRY_PATTERN),
|
|
131
|
-
region: readValidatedField(record, 'region', REGION_PATTERN),
|
|
132
|
-
timezone: readValidatedField(record, 'timezone', TIMEZONE_PATTERN),
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* Low-level data service that fetches geolocation details from the geolocation
|
|
137
|
-
* API.
|
|
47
|
+
* Low-level data service that fetches a location code from the geolocation API.
|
|
138
48
|
*
|
|
139
49
|
* Responsibilities:
|
|
140
50
|
* - HTTP request to the geolocation endpoint (wrapped in a service policy)
|
|
141
|
-
* -
|
|
51
|
+
* - ISO 3166-2 response validation (country code with optional subdivision,
|
|
52
|
+
* e.g. `US`, `US-NY`, `CA-ON`)
|
|
142
53
|
* - TTL-based in-memory cache
|
|
143
54
|
* - Promise deduplication (concurrent callers share a single in-flight request)
|
|
144
55
|
*
|
|
145
56
|
* This class is intentionally not a controller: it does not manage UI state.
|
|
146
|
-
* Its {@link fetchGeolocation}
|
|
147
|
-
*
|
|
148
|
-
* packages can call them directly.
|
|
57
|
+
* Its {@link fetchGeolocation} method is automatically registered on the
|
|
58
|
+
* messenger so that controllers and other packages can call it directly.
|
|
149
59
|
*/
|
|
150
60
|
export class GeolocationApiService {
|
|
151
61
|
/**
|
|
@@ -173,7 +83,7 @@ export class GeolocationApiService {
|
|
|
173
83
|
* @see {@link createServicePolicy}
|
|
174
84
|
*/
|
|
175
85
|
_GeolocationApiService_policy.set(this, void 0);
|
|
176
|
-
|
|
86
|
+
_GeolocationApiService_cachedLocation.set(this, UNKNOWN_LOCATION);
|
|
177
87
|
_GeolocationApiService_lastFetchedAt.set(this, null);
|
|
178
88
|
_GeolocationApiService_fetchPromise.set(this, null);
|
|
179
89
|
this.name = serviceName;
|
|
@@ -230,26 +140,11 @@ export class GeolocationApiService {
|
|
|
230
140
|
* {@link UNKNOWN_LOCATION} when the API returns an empty or invalid body.
|
|
231
141
|
*/
|
|
232
142
|
async fetchGeolocation(options) {
|
|
233
|
-
return toLocationCode(await this.fetchGeolocationData(options));
|
|
234
|
-
}
|
|
235
|
-
/**
|
|
236
|
-
* Returns the country, region, and timezone for the current client. Serves
|
|
237
|
-
* from cache when the TTL has not expired, otherwise performs a network
|
|
238
|
-
* fetch. Concurrent callers are deduplicated to a single in-flight request.
|
|
239
|
-
*
|
|
240
|
-
* @param options - Optional fetch options.
|
|
241
|
-
* @param options.bypassCache - When true, invalidates the TTL cache. If a
|
|
242
|
-
* request is already in-flight it will be reused (deduplication always
|
|
243
|
-
* applies).
|
|
244
|
-
* @returns The geolocation data, where each field is `null` when the API
|
|
245
|
-
* omits it or returns a value that fails validation.
|
|
246
|
-
*/
|
|
247
|
-
async fetchGeolocationData(options) {
|
|
248
143
|
if (options?.bypassCache) {
|
|
249
144
|
__classPrivateFieldSet(this, _GeolocationApiService_lastFetchedAt, null, "f");
|
|
250
145
|
}
|
|
251
146
|
if (__classPrivateFieldGet(this, _GeolocationApiService_instances, "m", _GeolocationApiService_isCacheValid).call(this)) {
|
|
252
|
-
return __classPrivateFieldGet(this,
|
|
147
|
+
return __classPrivateFieldGet(this, _GeolocationApiService_cachedLocation, "f");
|
|
253
148
|
}
|
|
254
149
|
if (__classPrivateFieldGet(this, _GeolocationApiService_fetchPromise, "f")) {
|
|
255
150
|
return __classPrivateFieldGet(this, _GeolocationApiService_fetchPromise, "f");
|
|
@@ -264,7 +159,7 @@ export class GeolocationApiService {
|
|
|
264
159
|
}
|
|
265
160
|
}
|
|
266
161
|
}
|
|
267
|
-
_GeolocationApiService_messenger = new WeakMap(), _GeolocationApiService_fetch = new WeakMap(), _GeolocationApiService_url = new WeakMap(), _GeolocationApiService_ttlMs = new WeakMap(), _GeolocationApiService_policy = new WeakMap(),
|
|
162
|
+
_GeolocationApiService_messenger = new WeakMap(), _GeolocationApiService_fetch = new WeakMap(), _GeolocationApiService_url = new WeakMap(), _GeolocationApiService_ttlMs = new WeakMap(), _GeolocationApiService_policy = new WeakMap(), _GeolocationApiService_cachedLocation = new WeakMap(), _GeolocationApiService_lastFetchedAt = new WeakMap(), _GeolocationApiService_fetchPromise = new WeakMap(), _GeolocationApiService_instances = new WeakSet(), _GeolocationApiService_isCacheValid = function _GeolocationApiService_isCacheValid() {
|
|
268
163
|
return (__classPrivateFieldGet(this, _GeolocationApiService_lastFetchedAt, "f") !== null &&
|
|
269
164
|
Date.now() - __classPrivateFieldGet(this, _GeolocationApiService_lastFetchedAt, "f") < __classPrivateFieldGet(this, _GeolocationApiService_ttlMs, "f"));
|
|
270
165
|
}, _GeolocationApiService_performFetch =
|
|
@@ -272,7 +167,7 @@ _GeolocationApiService_messenger = new WeakMap(), _GeolocationApiService_fetch =
|
|
|
272
167
|
* Performs the actual HTTP fetch, wrapped in the service policy for automatic
|
|
273
168
|
* retry and circuit-breaking, and validates the response.
|
|
274
169
|
*
|
|
275
|
-
* @returns The
|
|
170
|
+
* @returns The ISO 3166-2 location code string.
|
|
276
171
|
*/
|
|
277
172
|
async function _GeolocationApiService_performFetch() {
|
|
278
173
|
const response = await __classPrivateFieldGet(this, _GeolocationApiService_policy, "f").execute(async () => {
|
|
@@ -282,18 +177,14 @@ async function _GeolocationApiService_performFetch() {
|
|
|
282
177
|
}
|
|
283
178
|
return localResponse;
|
|
284
179
|
});
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
geolocation.region !== null ||
|
|
292
|
-
geolocation.timezone !== null;
|
|
293
|
-
if (hasKnownField) {
|
|
294
|
-
__classPrivateFieldSet(this, _GeolocationApiService_cachedGeolocation, geolocation, "f");
|
|
180
|
+
const raw = (await response.text()).trim();
|
|
181
|
+
const location = /^[A-Z]{2}(-[A-Z0-9]{1,3})?$/u.test(raw)
|
|
182
|
+
? raw
|
|
183
|
+
: UNKNOWN_LOCATION;
|
|
184
|
+
if (location !== UNKNOWN_LOCATION) {
|
|
185
|
+
__classPrivateFieldSet(this, _GeolocationApiService_cachedLocation, location, "f");
|
|
295
186
|
__classPrivateFieldSet(this, _GeolocationApiService_lastFetchedAt, Date.now(), "f");
|
|
296
187
|
}
|
|
297
|
-
return
|
|
188
|
+
return location;
|
|
298
189
|
};
|
|
299
190
|
//# sourceMappingURL=geolocation-api-service.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"geolocation-api-service.mjs","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,mCAAmC;AAI5E,OAAO,EAAE,GAAG,EAAE,qBAAoB;AAGlC,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAErC,MAAM,aAAa,GAAG,iBAAiB,CAAC;AAExC,MAAM,eAAe,GAAG,aAAa,CAAC;AAEtC,MAAM,cAAc,GAAG,kBAAkB,CAAC;AAE1C,MAAM,gBAAgB,GAAG,kDAAkD,CAAC;AAE5E,kBAAkB;AAElB;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,uBAAuB,CAAC;AAEnD;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,SAAS,CAAC;AAiB1C;;;;GAIG;AACH,MAAM,UAAU,yBAAyB;IACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,yBAAyB,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,cAA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AC;QAC5B,CAAC;IACH,CAAC;CAoDF;;IA5CG,OAAO,CACL,uBAAA,IAAI,4CAAe,KAAK,IAAI;QAC5B,IAAI,CAAC,GAAG,EAAE,GAAG,uBAAA,IAAI,4CAAe,GAAG,uBAAA,IAAI,oCAAO,CAC/C,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,MAAM,QAAQ,GAAG,MAAM,uBAAA,IAAI,qCAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE;QACrD,MAAM,aAAa,GAAG,MAAM,uBAAA,IAAI,oCAAO,MAAX,IAAI,EAAQ,uBAAA,IAAI,kCAAK,CAAC,CAAC;QACnD,IAAI,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC;YACtB,MAAM,IAAI,SAAS,CACjB,aAAa,CAAC,MAAM,EACpB,6BAA6B,aAAa,CAAC,MAAM,EAAE,CACpD,CAAC;QACJ,CAAC;QACD,OAAO,aAAa,CAAC;IACvB,CAAC,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,wBAAwB,CAC1C,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAC/B,CAAC;IAEF,uEAAuE;IACvE,0EAA0E;IAC1E,0EAA0E;IAC1E,sCAAsC;IACtC,MAAM,aAAa,GACjB,WAAW,CAAC,OAAO,KAAK,IAAI;QAC5B,WAAW,CAAC,MAAM,KAAK,IAAI;QAC3B,WAAW,CAAC,QAAQ,KAAK,IAAI,CAAC;IAEhC,IAAI,aAAa,EAAE,CAAC;QAClB,uBAAA,IAAI,4CAAsB,WAAW,MAAA,CAAC;QACtC,uBAAA,IAAI,wCAAkB,IAAI,CAAC,GAAG,EAAE,MAAA,CAAC;IACnC,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport { createServicePolicy, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { IDisposable } from 'cockatiel';\n\nimport { Env } from '../types.js';\nimport type { GeolocationApiServiceMethodActions } from './geolocation-api-service-method-action-types.js';\n\nconst DEFAULT_TTL_MS = 5 * 60 * 1000;\n\nconst ENDPOINT_PATH = '/v2/geolocation';\n\nconst COUNTRY_PATTERN = /^[A-Z]{2}$/u;\n\nconst REGION_PATTERN = /^[A-Z0-9]{1,3}$/u;\n\nconst TIMEZONE_PATTERN = /^[A-Za-z][A-Za-z0-9_+-]*(?:\\/[A-Za-z0-9_+-]+)*$/u;\n\n// === GENERAL ===\n\n/**\n * The name of the {@link GeolocationApiService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'GeolocationApiService';\n\n/**\n * Sentinel value used when the geolocation has not been determined yet or when\n * the API returns an empty / invalid response.\n */\nexport const UNKNOWN_LOCATION = 'UNKNOWN';\n\n/**\n * Geolocation details returned by the geolocation API.\n *\n * Each field is `null` when the API omits it or returns a value that fails\n * validation.\n */\nexport type GeolocationData = {\n /** ISO 3166-1 alpha-2 country code (e.g. `US`, `FR`). */\n country: string | null;\n /** ISO 3166-2 subdivision code without the country prefix (e.g. `WA`). */\n region: string | null;\n /** IANA time zone name (e.g. `America/Los_Angeles`). */\n timezone: string | null;\n};\n\n/**\n * Constructs a {@link GeolocationData} with no known fields.\n *\n * @returns Geolocation data where every field is `null`.\n */\nexport function getUnknownGeolocationData(): GeolocationData {\n return { country: null, region: null, timezone: null };\n}\n\n/**\n * Country codes for which the location code includes the region. This mirrors\n * the legacy `v1` geolocation endpoint, which only appended the subdivision for\n * the United States and Canada (e.g. `US-NY`, `CA-ON`) and returned the country\n * alone for everywhere else.\n */\nconst REGION_APPENDED_COUNTRIES = new Set(['US', 'CA']);\n\n/**\n * Converts geolocation data to a location code.\n *\n * To preserve backwards compatibility with the legacy `v1` endpoint, the region\n * is appended only for {@link REGION_APPENDED_COUNTRIES} (e.g. `US-NY`,\n * `CA-ON`); all other countries return the country code alone (e.g. `FR`), even\n * when a region is known.\n *\n * @param data - The geolocation data to convert.\n * @returns The location code (e.g. `US-NY`, `FR`), or\n * {@link UNKNOWN_LOCATION} when the country is unknown.\n */\nexport function toLocationCode(data: GeolocationData): string {\n if (data.country === null) {\n return UNKNOWN_LOCATION;\n }\n\n if (data.region !== null && REGION_APPENDED_COUNTRIES.has(data.country)) {\n return `${data.country}-${data.region}`;\n }\n\n return data.country;\n}\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'fetchGeolocation',\n 'fetchGeolocationData',\n] as const;\n\n/**\n * Actions that {@link GeolocationApiService} exposes to other consumers.\n */\nexport type GeolocationApiServiceActions = GeolocationApiServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link GeolocationApiServiceMessenger}\n * calls.\n */\ntype AllowedActions = never;\n\n/**\n * Events that {@link GeolocationApiService} exposes to other consumers.\n */\nexport type GeolocationApiServiceEvents = never;\n\n/**\n * Events from other messengers that {@link GeolocationApiService} subscribes\n * to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link GeolocationApiService}.\n */\nexport type GeolocationApiServiceMessenger = Messenger<\n typeof serviceName,\n GeolocationApiServiceActions | AllowedActions,\n GeolocationApiServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * Returns the base URL for the geolocation API for the given environment.\n *\n * Served by API Platform's `geolocation-api` service, not the legacy\n * Ramps-owned `on-ramp` endpoint this previously pointed to. API Platform has\n * not yet provisioned a dedicated UAT deployment for this service, so UAT\n * temporarily resolves to the production URL until one exists.\n *\n * @param env - The environment to get the URL for.\n * @returns The full URL for the geolocation endpoint.\n */\nfunction getGeolocationUrl(env: Env): string {\n const envPrefix = env === Env.DEV ? 'dev-' : '';\n return `https://geolocation.${envPrefix}api.cx.metamask.io${ENDPOINT_PATH}`;\n}\n\n/**\n * Reads a string field from a parsed response body, keeping it only when it\n * matches the expected format.\n *\n * @param body - The parsed response body.\n * @param field - The name of the field to read.\n * @param pattern - The pattern the field value must match.\n * @returns The trimmed field value, or `null` when it is missing or invalid.\n */\nfunction readValidatedField(\n body: Record<string, unknown>,\n field: string,\n pattern: RegExp,\n): string | null {\n const value = body[field];\n\n if (typeof value !== 'string') {\n return null;\n }\n\n const trimmed = value.trim();\n\n return pattern.test(trimmed) ? trimmed : null;\n}\n\n/**\n * Parses and validates the geolocation API response body.\n *\n * The endpoint is expected to return JSON such as\n * `{\"country\":\"US\",\"region\":\"WA\",\"timezone\":\"America/Los_Angeles\"}`. Anything\n * that cannot be parsed, or any individual field that fails validation, is\n * reported as unknown rather than throwing, so that consumers can keep working\n * with partial or missing data.\n *\n * @param raw - The raw response body.\n * @returns The validated geolocation data.\n */\nfunction parseGeolocationResponse(raw: string): GeolocationData {\n let body: unknown;\n\n try {\n body = JSON.parse(raw);\n } catch {\n return getUnknownGeolocationData();\n }\n\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n return getUnknownGeolocationData();\n }\n\n const record = body as Record<string, unknown>;\n\n return {\n country: readValidatedField(record, 'country', COUNTRY_PATTERN),\n region: readValidatedField(record, 'region', REGION_PATTERN),\n timezone: readValidatedField(record, 'timezone', TIMEZONE_PATTERN),\n };\n}\n\n/**\n * Options accepted by {@link GeolocationApiService.fetchGeolocation}.\n */\nexport type FetchGeolocationOptions = {\n /** When true, the TTL cache is invalidated so the next request fetches fresh data. */\n bypassCache?: boolean;\n};\n\n/**\n * Low-level data service that fetches geolocation details from the geolocation\n * API.\n *\n * Responsibilities:\n * - HTTP request to the geolocation endpoint (wrapped in a service policy)\n * - Response validation of the country, region, and timezone fields\n * - TTL-based in-memory cache\n * - Promise deduplication (concurrent callers share a single in-flight request)\n *\n * This class is intentionally not a controller: it does not manage UI state.\n * Its {@link fetchGeolocation} and {@link fetchGeolocationData} methods are\n * automatically registered on the messenger so that controllers and other\n * packages can call them directly.\n */\nexport class GeolocationApiService {\n /**\n * The name of the service.\n */\n readonly name: typeof serviceName;\n\n readonly #messenger: GeolocationApiServiceMessenger;\n\n readonly #fetch: typeof globalThis.fetch;\n\n readonly #url: string;\n\n readonly #ttlMs: number;\n\n /**\n * The policy that wraps each HTTP request.\n *\n * @see {@link createServicePolicy}\n */\n readonly #policy: ServicePolicy;\n\n #cachedGeolocation: GeolocationData = getUnknownGeolocationData();\n\n #lastFetchedAt: number | null = null;\n\n #fetchPromise: Promise<GeolocationData> | null = null;\n\n /**\n * Constructs a new {@link GeolocationApiService}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.env - The environment to determine the correct API endpoint.\n * Defaults to PRD.\n * @param args.fetch - A function that can be used to make an HTTP request.\n * Defaults to the global fetch.\n * @param args.ttlMs - Cache TTL in milliseconds. Defaults to 5 minutes.\n * @param args.policyOptions - Options to pass to `createServicePolicy`, which\n * is used to wrap each request. See {@link CreateServicePolicyOptions}.\n */\n constructor({\n messenger,\n env = Env.PRD,\n fetch: fetchFunction = globalThis.fetch,\n ttlMs,\n policyOptions = {},\n }: {\n messenger: GeolocationApiServiceMessenger;\n env?: Env;\n fetch?: typeof fetch;\n ttlMs?: number;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n this.name = serviceName;\n this.#messenger = messenger;\n this.#url = getGeolocationUrl(env);\n this.#fetch = fetchFunction;\n this.#ttlMs = ttlMs ?? DEFAULT_TTL_MS;\n this.#policy = createServicePolicy(policyOptions);\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Registers a handler that will be called after a request returns a 5xx\n * response, causing a retry.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler.\n * @see {@link createServicePolicy}\n */\n onRetry(listener: Parameters<ServicePolicy['onRetry']>[0]): IDisposable {\n return this.#policy.onRetry(listener);\n }\n\n /**\n * Registers a handler that will be called after a set number of retry rounds\n * prove that requests to the API endpoint consistently return a 5xx response.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler.\n * @see {@link createServicePolicy}\n */\n onBreak(listener: Parameters<ServicePolicy['onBreak']>[0]): IDisposable {\n return this.#policy.onBreak(listener);\n }\n\n /**\n * Registers a handler that will be called when requests are consistently\n * failing or when a successful request takes longer than the degraded\n * threshold.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler.\n */\n onDegraded(\n listener: Parameters<ServicePolicy['onDegraded']>[0],\n ): IDisposable {\n return this.#policy.onDegraded(listener);\n }\n\n /**\n * Returns the geolocation code. Serves from cache when the TTL has not\n * expired, otherwise performs a network fetch. Concurrent callers are\n * deduplicated to a single in-flight request.\n *\n * @param options - Optional fetch options.\n * @param options.bypassCache - When true, invalidates the TTL cache. If a\n * request is already in-flight it will be reused (deduplication always\n * applies).\n * @returns An ISO 3166-2 location code (e.g. `US`, `US-NY`, `CA-ON`), or\n * {@link UNKNOWN_LOCATION} when the API returns an empty or invalid body.\n */\n async fetchGeolocation(options?: FetchGeolocationOptions): Promise<string> {\n return toLocationCode(await this.fetchGeolocationData(options));\n }\n\n /**\n * Returns the country, region, and timezone for the current client. Serves\n * from cache when the TTL has not expired, otherwise performs a network\n * fetch. Concurrent callers are deduplicated to a single in-flight request.\n *\n * @param options - Optional fetch options.\n * @param options.bypassCache - When true, invalidates the TTL cache. If a\n * request is already in-flight it will be reused (deduplication always\n * applies).\n * @returns The geolocation data, where each field is `null` when the API\n * omits it or returns a value that fails validation.\n */\n async fetchGeolocationData(\n options?: FetchGeolocationOptions,\n ): Promise<GeolocationData> {\n if (options?.bypassCache) {\n this.#lastFetchedAt = null;\n }\n\n if (this.#isCacheValid()) {\n return this.#cachedGeolocation;\n }\n\n if (this.#fetchPromise) {\n return this.#fetchPromise;\n }\n\n const promise = this.#performFetch();\n this.#fetchPromise = promise;\n\n try {\n return await promise;\n } finally {\n this.#fetchPromise = null;\n }\n }\n\n /**\n * Checks whether the cached geolocation is still within the TTL window.\n *\n * @returns True if the cache is valid.\n */\n #isCacheValid(): boolean {\n return (\n this.#lastFetchedAt !== null &&\n Date.now() - this.#lastFetchedAt < this.#ttlMs\n );\n }\n\n /**\n * Performs the actual HTTP fetch, wrapped in the service policy for automatic\n * retry and circuit-breaking, and validates the response.\n *\n * @returns The validated geolocation data.\n */\n async #performFetch(): Promise<GeolocationData> {\n const response = await this.#policy.execute(async () => {\n const localResponse = await this.#fetch(this.#url);\n if (!localResponse.ok) {\n throw new HttpError(\n localResponse.status,\n `Geolocation fetch failed: ${localResponse.status}`,\n );\n }\n return localResponse;\n });\n\n const geolocation = parseGeolocationResponse(\n (await response.text()).trim(),\n );\n\n // Cache whenever at least one field resolved. A partially-known result\n // (e.g. timezone without a valid country) is still worth caching so we do\n // not re-fetch it within the TTL window; only a fully-unknown response is\n // left uncached so it can be retried.\n const hasKnownField =\n geolocation.country !== null ||\n geolocation.region !== null ||\n geolocation.timezone !== null;\n\n if (hasKnownField) {\n this.#cachedGeolocation = geolocation;\n this.#lastFetchedAt = Date.now();\n }\n\n return geolocation;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"geolocation-api-service.mjs","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,mCAAmC;AAI5E,OAAO,EAAE,GAAG,EAAE,qBAAoB;AAGlC,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAErC,MAAM,aAAa,GAAG,iBAAiB,CAAC;AAExC,kBAAkB;AAElB;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,uBAAuB,CAAC;AAEnD;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,SAAS,CAAC;AAE1C,oBAAoB;AAEpB,MAAM,yBAAyB,GAAG,CAAC,kBAAkB,CAAU,CAAC;AAkChE,6BAA6B;AAE7B;;;;;;;;;;GAUG;AACH,SAAS,iBAAiB,CAAC,GAAQ;IACjC,MAAM,SAAS,GAAG,GAAG,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aAAa,CAAC,MAAM,EAAE,CACpD,CAAC;QACJ,CAAC;QACD,OAAO,aAAa,CAAC;IACvB,CAAC,CAAC,CAAC;IAEH,MAAM,GAAG,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3C,MAAM,QAAQ,GAAG,8BAA8B,CAAC,IAAI,CAAC,GAAG,CAAC;QACvD,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,gBAAgB,CAAC;IAErB,IAAI,QAAQ,KAAK,gBAAgB,EAAE,CAAC;QAClC,uBAAA,IAAI,yCAAmB,QAAQ,MAAA,CAAC;QAChC,uBAAA,IAAI,wCAAkB,IAAI,CAAC,GAAG,EAAE,MAAA,CAAC;IACnC,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport { createServicePolicy, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { IDisposable } from 'cockatiel';\n\nimport { Env } from '../types.js';\nimport type { GeolocationApiServiceMethodActions } from './geolocation-api-service-method-action-types.js';\n\nconst DEFAULT_TTL_MS = 5 * 60 * 1000;\n\nconst ENDPOINT_PATH = '/v1/geolocation';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link GeolocationApiService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'GeolocationApiService';\n\n/**\n * Sentinel value used when the geolocation has not been determined yet or when\n * the API returns an empty / invalid response.\n */\nexport const UNKNOWN_LOCATION = 'UNKNOWN';\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchGeolocation'] as const;\n\n/**\n * Actions that {@link GeolocationApiService} exposes to other consumers.\n */\nexport type GeolocationApiServiceActions = GeolocationApiServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link GeolocationApiServiceMessenger}\n * calls.\n */\ntype AllowedActions = never;\n\n/**\n * Events that {@link GeolocationApiService} exposes to other consumers.\n */\nexport type GeolocationApiServiceEvents = never;\n\n/**\n * Events from other messengers that {@link GeolocationApiService} subscribes\n * to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link GeolocationApiService}.\n */\nexport type GeolocationApiServiceMessenger = Messenger<\n typeof serviceName,\n GeolocationApiServiceActions | AllowedActions,\n GeolocationApiServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * Returns the base URL for the geolocation API for the given environment.\n *\n * Served by API Platform's `geolocation-api` service, not the legacy\n * Ramps-owned `on-ramp` endpoint this previously pointed to. API Platform has\n * not yet provisioned a dedicated UAT deployment for this service, so UAT\n * temporarily resolves to the production URL until one exists.\n *\n * @param env - The environment to get the URL for.\n * @returns The full URL for the geolocation endpoint.\n */\nfunction getGeolocationUrl(env: Env): string {\n const envPrefix = env === Env.DEV ? 'dev-' : '';\n return `https://geolocation.${envPrefix}api.cx.metamask.io${ENDPOINT_PATH}`;\n}\n\n/**\n * Options accepted by {@link GeolocationApiService.fetchGeolocation}.\n */\nexport type FetchGeolocationOptions = {\n /** When true, the TTL cache is invalidated so the next request fetches fresh data. */\n bypassCache?: boolean;\n};\n\n/**\n * Low-level data service that fetches a location code from the geolocation API.\n *\n * Responsibilities:\n * - HTTP request to the geolocation endpoint (wrapped in a service policy)\n * - ISO 3166-2 response validation (country code with optional subdivision,\n * e.g. `US`, `US-NY`, `CA-ON`)\n * - TTL-based in-memory cache\n * - Promise deduplication (concurrent callers share a single in-flight request)\n *\n * This class is intentionally not a controller: it does not manage UI state.\n * Its {@link fetchGeolocation} method is automatically registered on the\n * messenger so that controllers and other packages can call it directly.\n */\nexport class GeolocationApiService {\n /**\n * The name of the service.\n */\n readonly name: typeof serviceName;\n\n readonly #messenger: GeolocationApiServiceMessenger;\n\n readonly #fetch: typeof globalThis.fetch;\n\n readonly #url: string;\n\n readonly #ttlMs: number;\n\n /**\n * The policy that wraps each HTTP request.\n *\n * @see {@link createServicePolicy}\n */\n readonly #policy: ServicePolicy;\n\n #cachedLocation: string = UNKNOWN_LOCATION;\n\n #lastFetchedAt: number | null = null;\n\n #fetchPromise: Promise<string> | null = null;\n\n /**\n * Constructs a new {@link GeolocationApiService}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.env - The environment to determine the correct API endpoint.\n * Defaults to PRD.\n * @param args.fetch - A function that can be used to make an HTTP request.\n * Defaults to the global fetch.\n * @param args.ttlMs - Cache TTL in milliseconds. Defaults to 5 minutes.\n * @param args.policyOptions - Options to pass to `createServicePolicy`, which\n * is used to wrap each request. See {@link CreateServicePolicyOptions}.\n */\n constructor({\n messenger,\n env = Env.PRD,\n fetch: fetchFunction = globalThis.fetch,\n ttlMs,\n policyOptions = {},\n }: {\n messenger: GeolocationApiServiceMessenger;\n env?: Env;\n fetch?: typeof fetch;\n ttlMs?: number;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n this.name = serviceName;\n this.#messenger = messenger;\n this.#url = getGeolocationUrl(env);\n this.#fetch = fetchFunction;\n this.#ttlMs = ttlMs ?? DEFAULT_TTL_MS;\n this.#policy = createServicePolicy(policyOptions);\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Registers a handler that will be called after a request returns a 5xx\n * response, causing a retry.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler.\n * @see {@link createServicePolicy}\n */\n onRetry(listener: Parameters<ServicePolicy['onRetry']>[0]): IDisposable {\n return this.#policy.onRetry(listener);\n }\n\n /**\n * Registers a handler that will be called after a set number of retry rounds\n * prove that requests to the API endpoint consistently return a 5xx response.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler.\n * @see {@link createServicePolicy}\n */\n onBreak(listener: Parameters<ServicePolicy['onBreak']>[0]): IDisposable {\n return this.#policy.onBreak(listener);\n }\n\n /**\n * Registers a handler that will be called when requests are consistently\n * failing or when a successful request takes longer than the degraded\n * threshold.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler.\n */\n onDegraded(\n listener: Parameters<ServicePolicy['onDegraded']>[0],\n ): IDisposable {\n return this.#policy.onDegraded(listener);\n }\n\n /**\n * Returns the geolocation code. Serves from cache when the TTL has not\n * expired, otherwise performs a network fetch. Concurrent callers are\n * deduplicated to a single in-flight request.\n *\n * @param options - Optional fetch options.\n * @param options.bypassCache - When true, invalidates the TTL cache. If a\n * request is already in-flight it will be reused (deduplication always\n * applies).\n * @returns An ISO 3166-2 location code (e.g. `US`, `US-NY`, `CA-ON`), or\n * {@link UNKNOWN_LOCATION} when the API returns an empty or invalid body.\n */\n async fetchGeolocation(options?: FetchGeolocationOptions): Promise<string> {\n if (options?.bypassCache) {\n this.#lastFetchedAt = null;\n }\n\n if (this.#isCacheValid()) {\n return this.#cachedLocation;\n }\n\n if (this.#fetchPromise) {\n return this.#fetchPromise;\n }\n\n const promise = this.#performFetch();\n this.#fetchPromise = promise;\n\n try {\n return await promise;\n } finally {\n this.#fetchPromise = null;\n }\n }\n\n /**\n * Checks whether the cached geolocation is still within the TTL window.\n *\n * @returns True if the cache is valid.\n */\n #isCacheValid(): boolean {\n return (\n this.#lastFetchedAt !== null &&\n Date.now() - this.#lastFetchedAt < this.#ttlMs\n );\n }\n\n /**\n * Performs the actual HTTP fetch, wrapped in the service policy for automatic\n * retry and circuit-breaking, and validates the response.\n *\n * @returns The ISO 3166-2 location code string.\n */\n async #performFetch(): Promise<string> {\n const response = await this.#policy.execute(async () => {\n const localResponse = await this.#fetch(this.#url);\n if (!localResponse.ok) {\n throw new HttpError(\n localResponse.status,\n `Geolocation fetch failed: ${localResponse.status}`,\n );\n }\n return localResponse;\n });\n\n const raw = (await response.text()).trim();\n const location = /^[A-Z]{2}(-[A-Z0-9]{1,3})?$/u.test(raw)\n ? raw\n : UNKNOWN_LOCATION;\n\n if (location !== UNKNOWN_LOCATION) {\n this.#cachedLocation = location;\n this.#lastFetchedAt = Date.now();\n }\n\n return location;\n }\n}\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.UNKNOWN_LOCATION = exports.
|
|
3
|
+
exports.UNKNOWN_LOCATION = exports.GeolocationApiService = exports.getDefaultGeolocationControllerState = exports.GeolocationController = exports.Env = void 0;
|
|
4
4
|
var types_js_1 = require("./types.cjs");
|
|
5
5
|
Object.defineProperty(exports, "Env", { enumerable: true, get: function () { return types_js_1.Env; } });
|
|
6
6
|
var GeolocationController_js_1 = require("./GeolocationController.cjs");
|
|
@@ -8,7 +8,5 @@ Object.defineProperty(exports, "GeolocationController", { enumerable: true, get:
|
|
|
8
8
|
Object.defineProperty(exports, "getDefaultGeolocationControllerState", { enumerable: true, get: function () { return GeolocationController_js_1.getDefaultGeolocationControllerState; } });
|
|
9
9
|
var geolocation_api_service_js_1 = require("./geolocation-api-service/geolocation-api-service.cjs");
|
|
10
10
|
Object.defineProperty(exports, "GeolocationApiService", { enumerable: true, get: function () { return geolocation_api_service_js_1.GeolocationApiService; } });
|
|
11
|
-
Object.defineProperty(exports, "getUnknownGeolocationData", { enumerable: true, get: function () { return geolocation_api_service_js_1.getUnknownGeolocationData; } });
|
|
12
|
-
Object.defineProperty(exports, "toLocationCode", { enumerable: true, get: function () { return geolocation_api_service_js_1.toLocationCode; } });
|
|
13
11
|
Object.defineProperty(exports, "UNKNOWN_LOCATION", { enumerable: true, get: function () { return geolocation_api_service_js_1.UNKNOWN_LOCATION; } });
|
|
14
12
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAcA,wCAAiC;AAAxB,+FAAA,GAAG,OAAA;AACZ,wEAGoC;AAFlC,iIAAA,qBAAqB,OAAA;AACrB,gJAAA,oCAAoC,OAAA;AAEtC,oGAG8D;AAF5D,mIAAA,qBAAqB,OAAA;AACrB,8HAAA,gBAAgB,OAAA","sourcesContent":["export type {\n GeolocationControllerState,\n GeolocationControllerGetStateAction,\n GeolocationControllerActions,\n GeolocationControllerStateChangeEvent,\n GeolocationControllerEvents,\n GeolocationControllerMessenger,\n GeolocationControllerOptions,\n} from './GeolocationController.js';\nexport type {\n GeolocationControllerGetGeolocationAction,\n GeolocationControllerRefreshGeolocationAction,\n} from './GeolocationController-method-action-types.js';\nexport type { GeolocationRequestStatus } from './types.js';\nexport { Env } from './types.js';\nexport {\n GeolocationController,\n getDefaultGeolocationControllerState,\n} from './GeolocationController.js';\nexport {\n GeolocationApiService,\n UNKNOWN_LOCATION,\n} from './geolocation-api-service/geolocation-api-service.js';\nexport type {\n GeolocationApiServiceMessenger,\n GeolocationApiServiceActions,\n GeolocationApiServiceEvents,\n FetchGeolocationOptions,\n} from './geolocation-api-service/geolocation-api-service.js';\nexport type { GeolocationApiServiceFetchGeolocationAction } from './geolocation-api-service/geolocation-api-service-method-action-types.js';\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
export type { GeolocationControllerState, GeolocationControllerGetStateAction, GeolocationControllerActions, GeolocationControllerStateChangeEvent, GeolocationControllerEvents, GeolocationControllerMessenger, GeolocationControllerOptions, } from "./GeolocationController.cjs";
|
|
2
|
-
export type { GeolocationControllerGetGeolocationAction,
|
|
2
|
+
export type { GeolocationControllerGetGeolocationAction, GeolocationControllerRefreshGeolocationAction, } from "./GeolocationController-method-action-types.cjs";
|
|
3
3
|
export type { GeolocationRequestStatus } from "./types.cjs";
|
|
4
4
|
export { Env } from "./types.cjs";
|
|
5
5
|
export { GeolocationController, getDefaultGeolocationControllerState, } from "./GeolocationController.cjs";
|
|
6
|
-
export { GeolocationApiService,
|
|
7
|
-
export type { GeolocationApiServiceMessenger, GeolocationApiServiceActions, GeolocationApiServiceEvents, FetchGeolocationOptions,
|
|
8
|
-
export type { GeolocationApiServiceFetchGeolocationAction
|
|
6
|
+
export { GeolocationApiService, UNKNOWN_LOCATION, } from "./geolocation-api-service/geolocation-api-service.cjs";
|
|
7
|
+
export type { GeolocationApiServiceMessenger, GeolocationApiServiceActions, GeolocationApiServiceEvents, FetchGeolocationOptions, } from "./geolocation-api-service/geolocation-api-service.cjs";
|
|
8
|
+
export type { GeolocationApiServiceFetchGeolocationAction } from "./geolocation-api-service/geolocation-api-service-method-action-types.cjs";
|
|
9
9
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,0BAA0B,EAC1B,mCAAmC,EACnC,4BAA4B,EAC5B,qCAAqC,EACrC,2BAA2B,EAC3B,8BAA8B,EAC9B,4BAA4B,GAC7B,oCAAmC;AACpC,YAAY,EACV,yCAAyC,EACzC,6CAA6C,
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,0BAA0B,EAC1B,mCAAmC,EACnC,4BAA4B,EAC5B,qCAAqC,EACrC,2BAA2B,EAC3B,8BAA8B,EAC9B,4BAA4B,GAC7B,oCAAmC;AACpC,YAAY,EACV,yCAAyC,EACzC,6CAA6C,GAC9C,wDAAuD;AACxD,YAAY,EAAE,wBAAwB,EAAE,oBAAmB;AAC3D,OAAO,EAAE,GAAG,EAAE,oBAAmB;AACjC,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,oCAAmC;AACpC,OAAO,EACL,qBAAqB,EACrB,gBAAgB,GACjB,8DAA6D;AAC9D,YAAY,EACV,8BAA8B,EAC9B,4BAA4B,EAC5B,2BAA2B,EAC3B,uBAAuB,GACxB,8DAA6D;AAC9D,YAAY,EAAE,2CAA2C,EAAE,kFAAiF"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
export type { GeolocationControllerState, GeolocationControllerGetStateAction, GeolocationControllerActions, GeolocationControllerStateChangeEvent, GeolocationControllerEvents, GeolocationControllerMessenger, GeolocationControllerOptions, } from "./GeolocationController.mjs";
|
|
2
|
-
export type { GeolocationControllerGetGeolocationAction,
|
|
2
|
+
export type { GeolocationControllerGetGeolocationAction, GeolocationControllerRefreshGeolocationAction, } from "./GeolocationController-method-action-types.mjs";
|
|
3
3
|
export type { GeolocationRequestStatus } from "./types.mjs";
|
|
4
4
|
export { Env } from "./types.mjs";
|
|
5
5
|
export { GeolocationController, getDefaultGeolocationControllerState, } from "./GeolocationController.mjs";
|
|
6
|
-
export { GeolocationApiService,
|
|
7
|
-
export type { GeolocationApiServiceMessenger, GeolocationApiServiceActions, GeolocationApiServiceEvents, FetchGeolocationOptions,
|
|
8
|
-
export type { GeolocationApiServiceFetchGeolocationAction
|
|
6
|
+
export { GeolocationApiService, UNKNOWN_LOCATION, } from "./geolocation-api-service/geolocation-api-service.mjs";
|
|
7
|
+
export type { GeolocationApiServiceMessenger, GeolocationApiServiceActions, GeolocationApiServiceEvents, FetchGeolocationOptions, } from "./geolocation-api-service/geolocation-api-service.mjs";
|
|
8
|
+
export type { GeolocationApiServiceFetchGeolocationAction } from "./geolocation-api-service/geolocation-api-service-method-action-types.mjs";
|
|
9
9
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,0BAA0B,EAC1B,mCAAmC,EACnC,4BAA4B,EAC5B,qCAAqC,EACrC,2BAA2B,EAC3B,8BAA8B,EAC9B,4BAA4B,GAC7B,oCAAmC;AACpC,YAAY,EACV,yCAAyC,EACzC,6CAA6C,
|
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,0BAA0B,EAC1B,mCAAmC,EACnC,4BAA4B,EAC5B,qCAAqC,EACrC,2BAA2B,EAC3B,8BAA8B,EAC9B,4BAA4B,GAC7B,oCAAmC;AACpC,YAAY,EACV,yCAAyC,EACzC,6CAA6C,GAC9C,wDAAuD;AACxD,YAAY,EAAE,wBAAwB,EAAE,oBAAmB;AAC3D,OAAO,EAAE,GAAG,EAAE,oBAAmB;AACjC,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,oCAAmC;AACpC,OAAO,EACL,qBAAqB,EACrB,gBAAgB,GACjB,8DAA6D;AAC9D,YAAY,EACV,8BAA8B,EAC9B,4BAA4B,EAC5B,2BAA2B,EAC3B,uBAAuB,GACxB,8DAA6D;AAC9D,YAAY,EAAE,2CAA2C,EAAE,kFAAiF"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { Env } from "./types.mjs";
|
|
2
2
|
export { GeolocationController, getDefaultGeolocationControllerState } from "./GeolocationController.mjs";
|
|
3
|
-
export { GeolocationApiService,
|
|
3
|
+
export { GeolocationApiService, UNKNOWN_LOCATION } from "./geolocation-api-service/geolocation-api-service.mjs";
|
|
4
4
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,GAAG,EAAE,oBAAmB;AACjC,OAAO,EACL,qBAAqB,EACrB,oCAAoC,EACrC,oCAAmC;AACpC,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EACjB,8DAA6D","sourcesContent":["export type {\n GeolocationControllerState,\n GeolocationControllerGetStateAction,\n GeolocationControllerActions,\n GeolocationControllerStateChangeEvent,\n GeolocationControllerEvents,\n GeolocationControllerMessenger,\n GeolocationControllerOptions,\n} from './GeolocationController.js';\nexport type {\n GeolocationControllerGetGeolocationAction,\n GeolocationControllerRefreshGeolocationAction,\n} from './GeolocationController-method-action-types.js';\nexport type { GeolocationRequestStatus } from './types.js';\nexport { Env } from './types.js';\nexport {\n GeolocationController,\n getDefaultGeolocationControllerState,\n} from './GeolocationController.js';\nexport {\n GeolocationApiService,\n UNKNOWN_LOCATION,\n} from './geolocation-api-service/geolocation-api-service.js';\nexport type {\n GeolocationApiServiceMessenger,\n GeolocationApiServiceActions,\n GeolocationApiServiceEvents,\n FetchGeolocationOptions,\n} from './geolocation-api-service/geolocation-api-service.js';\nexport type { GeolocationApiServiceFetchGeolocationAction } from './geolocation-api-service/geolocation-api-service-method-action-types.js';\n"]}
|
package/package.json
CHANGED