@metamask-previews/geolocation-controller 2.0.0-preview-35f016caa → 2.0.0-preview-01e391e
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 +10 -0
- package/dist/geolocation-api-service/geolocation-api-service-method-action-types.d.ts +6 -9
- package/dist/geolocation-api-service/geolocation-api-service-method-action-types.d.ts.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service-method-action-types.js.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service.d.ts +27 -49
- package/dist/geolocation-api-service/geolocation-api-service.d.ts.map +1 -1
- package/dist/geolocation-api-service/geolocation-api-service.js +42 -114
- package/dist/geolocation-api-service/geolocation-api-service.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -9,12 +9,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Added
|
|
11
11
|
|
|
12
|
+
- Add `GeolocationApiServiceInvalidateQueriesAction`, `GeolocationApiServiceCacheUpdatedEvent` and `GeolocationApiServiceGranularCacheUpdatedEvent`, also included in `GeolocationApiServiceActions` and `GeolocationApiServiceEvents` ([#10881](https://github.com/MetaMask/core/pull/10881))
|
|
12
13
|
- Add support for Node.js 26 ([#10981](https://github.com/MetaMask/core/pull/10981))
|
|
13
14
|
|
|
14
15
|
### Changed
|
|
15
16
|
|
|
17
|
+
- **BREAKING:** `GeolocationApiService` now extends `BaseDataService` from `@metamask/base-data-service` ([#10881](https://github.com/MetaMask/core/pull/10881))
|
|
18
|
+
- `GeolocationApiServiceMessenger` now includes the `GeolocationApiService:invalidateQueries` action and `GeolocationApiService:cacheUpdated` events. Messengers built from `GeolocationApiServiceActions` / `GeolocationApiServiceEvents` pick these up automatically.
|
|
19
|
+
- The hand-rolled TTL cache and in-flight deduplication are replaced by the `BaseDataService` query cache. `ttlMs` and `bypassCache` keep their existing behaviour.
|
|
20
|
+
- Add dependency `@metamask/base-data-service` ([#10881](https://github.com/MetaMask/core/pull/10881))
|
|
21
|
+
- Add dependency `@metamask/superstruct` ([#10881](https://github.com/MetaMask/core/pull/10881))
|
|
16
22
|
- Bump `@metamask/base-controller` from `^10.0.0` to `^10.1.0` ([#10864](https://github.com/MetaMask/core/pull/10864))
|
|
17
23
|
|
|
24
|
+
### Removed
|
|
25
|
+
|
|
26
|
+
- **BREAKING:** Remove `onRetry`, `onBreak` and `onDegraded` from `GeolocationApiService` ([#10881](https://github.com/MetaMask/core/pull/10881))
|
|
27
|
+
|
|
18
28
|
## [2.0.0]
|
|
19
29
|
|
|
20
30
|
### Changed
|
|
@@ -5,13 +5,11 @@
|
|
|
5
5
|
import type { GeolocationApiService } from './geolocation-api-service.js';
|
|
6
6
|
/**
|
|
7
7
|
* Returns the geolocation code. Serves from cache when the TTL has not
|
|
8
|
-
* expired, otherwise performs a network fetch.
|
|
9
|
-
* deduplicated to a single in-flight request.
|
|
8
|
+
* expired, otherwise performs a network fetch.
|
|
10
9
|
*
|
|
11
10
|
* @param options - Optional fetch options.
|
|
12
|
-
* @param options.bypassCache - When true,
|
|
13
|
-
*
|
|
14
|
-
* applies).
|
|
11
|
+
* @param options.bypassCache - When true, ignores any cached result and
|
|
12
|
+
* fetches fresh data.
|
|
15
13
|
* @returns An ISO 3166-2 location code (e.g. `US`, `US-NY`, `CA-ON`), or
|
|
16
14
|
* {@link UNKNOWN_LOCATION} when the API returns an empty or invalid body.
|
|
17
15
|
*/
|
|
@@ -22,12 +20,11 @@ export type GeolocationApiServiceFetchGeolocationAction = {
|
|
|
22
20
|
/**
|
|
23
21
|
* Returns the country, region, and timezone for the current client. Serves
|
|
24
22
|
* from cache when the TTL has not expired, otherwise performs a network
|
|
25
|
-
* fetch.
|
|
23
|
+
* fetch.
|
|
26
24
|
*
|
|
27
25
|
* @param options - Optional fetch options.
|
|
28
|
-
* @param options.bypassCache - When true,
|
|
29
|
-
*
|
|
30
|
-
* applies).
|
|
26
|
+
* @param options.bypassCache - When true, ignores any cached result and
|
|
27
|
+
* fetches fresh data.
|
|
31
28
|
* @returns The geolocation data, where each field is `null` when the API
|
|
32
29
|
* omits it or returns a value that fails validation.
|
|
33
30
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"geolocation-api-service-method-action-types.d.ts","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAE1E
|
|
1
|
+
{"version":3,"file":"geolocation-api-service-method-action-types.d.ts","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAE1E;;;;;;;;;GASG;AACH,MAAM,MAAM,2CAA2C,GAAG;IACxD,IAAI,EAAE,wCAAwC,CAAC;IAC/C,OAAO,EAAE,qBAAqB,CAAC,kBAAkB,CAAC,CAAC;CACpD,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,MAAM,+CAA+C,GAAG;IAC5D,IAAI,EAAE,4CAA4C,CAAC;IACnD,OAAO,EAAE,qBAAqB,CAAC,sBAAsB,CAAC,CAAC;CACxD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAC1C,2CAA2C,GAC3C,+CAA+C,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"geolocation-api-service-method-action-types.js","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { GeolocationApiService } from './geolocation-api-service.js';\n\n/**\n * Returns the geolocation code. Serves from cache when the TTL has not\n * expired, otherwise performs a network fetch
|
|
1
|
+
{"version":3,"file":"geolocation-api-service-method-action-types.js","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { GeolocationApiService } from './geolocation-api-service.js';\n\n/**\n * Returns the geolocation code. Serves from cache when the TTL has not\n * expired, otherwise performs a network fetch.\n *\n * @param options - Optional fetch options.\n * @param options.bypassCache - When true, ignores any cached result and\n * fetches fresh data.\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 */\nexport type GeolocationApiServiceFetchGeolocationAction = {\n type: `GeolocationApiService:fetchGeolocation`;\n handler: GeolocationApiService['fetchGeolocation'];\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.\n *\n * @param options - Optional fetch options.\n * @param options.bypassCache - When true, ignores any cached result and\n * fetches fresh data.\n * @returns The geolocation data, where each field is `null` when the API\n * omits it or returns a value that fails validation.\n */\nexport type GeolocationApiServiceFetchGeolocationDataAction = {\n type: `GeolocationApiService:fetchGeolocationData`;\n handler: GeolocationApiService['fetchGeolocationData'];\n};\n\n/**\n * Union of all GeolocationApiService action types.\n */\nexport type GeolocationApiServiceMethodActions =\n | GeolocationApiServiceFetchGeolocationAction\n | GeolocationApiServiceFetchGeolocationDataAction;\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { BaseDataService } from '@metamask/base-data-service';
|
|
2
|
+
import type { CreateServicePolicyOptions, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, DataServiceInvalidateQueriesAction } from '@metamask/base-data-service';
|
|
2
3
|
import type { Messenger } from '@metamask/messenger';
|
|
3
|
-
import type { IDisposable } from 'cockatiel';
|
|
4
4
|
import { Env } from '../types.js';
|
|
5
5
|
import type { GeolocationApiServiceMethodActions } from './geolocation-api-service-method-action-types.js';
|
|
6
6
|
/**
|
|
@@ -46,19 +46,32 @@ export declare function getUnknownGeolocationData(): GeolocationData;
|
|
|
46
46
|
* {@link UNKNOWN_LOCATION} when the country is unknown.
|
|
47
47
|
*/
|
|
48
48
|
export declare function toLocationCode(data: GeolocationData): string;
|
|
49
|
+
/**
|
|
50
|
+
* Invalidates cached queries for {@link GeolocationApiService}.
|
|
51
|
+
*/
|
|
52
|
+
export type GeolocationApiServiceInvalidateQueriesAction = DataServiceInvalidateQueriesAction<typeof serviceName>;
|
|
49
53
|
/**
|
|
50
54
|
* Actions that {@link GeolocationApiService} exposes to other consumers.
|
|
51
55
|
*/
|
|
52
|
-
export type GeolocationApiServiceActions = GeolocationApiServiceMethodActions;
|
|
56
|
+
export type GeolocationApiServiceActions = GeolocationApiServiceMethodActions | GeolocationApiServiceInvalidateQueriesAction;
|
|
53
57
|
/**
|
|
54
58
|
* Actions from other messengers that {@link GeolocationApiServiceMessenger}
|
|
55
59
|
* calls.
|
|
56
60
|
*/
|
|
57
61
|
type AllowedActions = never;
|
|
62
|
+
/**
|
|
63
|
+
* Published when {@link GeolocationApiService}'s cache is updated.
|
|
64
|
+
*/
|
|
65
|
+
export type GeolocationApiServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<typeof serviceName>;
|
|
66
|
+
/**
|
|
67
|
+
* Published when a key within {@link GeolocationApiService}'s cache is
|
|
68
|
+
* updated.
|
|
69
|
+
*/
|
|
70
|
+
export type GeolocationApiServiceGranularCacheUpdatedEvent = DataServiceGranularCacheUpdatedEvent<typeof serviceName>;
|
|
58
71
|
/**
|
|
59
72
|
* Events that {@link GeolocationApiService} exposes to other consumers.
|
|
60
73
|
*/
|
|
61
|
-
export type GeolocationApiServiceEvents =
|
|
74
|
+
export type GeolocationApiServiceEvents = GeolocationApiServiceCacheUpdatedEvent | GeolocationApiServiceGranularCacheUpdatedEvent;
|
|
62
75
|
/**
|
|
63
76
|
* Events from other messengers that {@link GeolocationApiService} subscribes
|
|
64
77
|
* to.
|
|
@@ -73,7 +86,7 @@ export type GeolocationApiServiceMessenger = Messenger<typeof serviceName, Geolo
|
|
|
73
86
|
* Options accepted by {@link GeolocationApiService.fetchGeolocation}.
|
|
74
87
|
*/
|
|
75
88
|
export type FetchGeolocationOptions = {
|
|
76
|
-
/** When true,
|
|
89
|
+
/** When true, ignores any cached result and fetches fresh data. */
|
|
77
90
|
bypassCache?: boolean;
|
|
78
91
|
};
|
|
79
92
|
/**
|
|
@@ -83,20 +96,14 @@ export type FetchGeolocationOptions = {
|
|
|
83
96
|
* Responsibilities:
|
|
84
97
|
* - HTTP request to the geolocation endpoint (wrapped in a service policy)
|
|
85
98
|
* - Response validation of the country, region, and timezone fields
|
|
86
|
-
* - TTL-based in-memory cache
|
|
87
|
-
* - Promise deduplication (concurrent callers share a single in-flight request)
|
|
88
99
|
*
|
|
89
100
|
* This class is intentionally not a controller: it does not manage UI state.
|
|
90
101
|
* Its {@link fetchGeolocation} and {@link fetchGeolocationData} methods are
|
|
91
102
|
* automatically registered on the messenger so that controllers and other
|
|
92
103
|
* packages can call them directly.
|
|
93
104
|
*/
|
|
94
|
-
export declare class GeolocationApiService {
|
|
105
|
+
export declare class GeolocationApiService extends BaseDataService<typeof serviceName, GeolocationApiServiceMessenger> {
|
|
95
106
|
#private;
|
|
96
|
-
/**
|
|
97
|
-
* The name of the service.
|
|
98
|
-
*/
|
|
99
|
-
readonly name: typeof serviceName;
|
|
100
107
|
/**
|
|
101
108
|
* Constructs a new {@link GeolocationApiService}.
|
|
102
109
|
*
|
|
@@ -106,7 +113,8 @@ export declare class GeolocationApiService {
|
|
|
106
113
|
* Defaults to PRD.
|
|
107
114
|
* @param args.fetch - A function that can be used to make an HTTP request.
|
|
108
115
|
* Defaults to the global fetch.
|
|
109
|
-
* @param args.ttlMs -
|
|
116
|
+
* @param args.ttlMs - How long a fetched result is served from cache, in
|
|
117
|
+
* milliseconds. Defaults to 5 minutes.
|
|
110
118
|
* @param args.policyOptions - Options to pass to `createServicePolicy`, which
|
|
111
119
|
* is used to wrap each request. See {@link CreateServicePolicyOptions}.
|
|
112
120
|
*/
|
|
@@ -117,42 +125,13 @@ export declare class GeolocationApiService {
|
|
|
117
125
|
ttlMs?: number;
|
|
118
126
|
policyOptions?: CreateServicePolicyOptions;
|
|
119
127
|
});
|
|
120
|
-
/**
|
|
121
|
-
* Registers a handler that will be called after a request returns a 5xx
|
|
122
|
-
* response, causing a retry.
|
|
123
|
-
*
|
|
124
|
-
* @param listener - The handler to be called.
|
|
125
|
-
* @returns An object that can be used to unregister the handler.
|
|
126
|
-
* @see {@link createServicePolicy}
|
|
127
|
-
*/
|
|
128
|
-
onRetry(listener: Parameters<ServicePolicy['onRetry']>[0]): IDisposable;
|
|
129
|
-
/**
|
|
130
|
-
* Registers a handler that will be called after a set number of retry rounds
|
|
131
|
-
* prove that requests to the API endpoint consistently return a 5xx response.
|
|
132
|
-
*
|
|
133
|
-
* @param listener - The handler to be called.
|
|
134
|
-
* @returns An object that can be used to unregister the handler.
|
|
135
|
-
* @see {@link createServicePolicy}
|
|
136
|
-
*/
|
|
137
|
-
onBreak(listener: Parameters<ServicePolicy['onBreak']>[0]): IDisposable;
|
|
138
|
-
/**
|
|
139
|
-
* Registers a handler that will be called when requests are consistently
|
|
140
|
-
* failing or when a successful request takes longer than the degraded
|
|
141
|
-
* threshold.
|
|
142
|
-
*
|
|
143
|
-
* @param listener - The handler to be called.
|
|
144
|
-
* @returns An object that can be used to unregister the handler.
|
|
145
|
-
*/
|
|
146
|
-
onDegraded(listener: Parameters<ServicePolicy['onDegraded']>[0]): IDisposable;
|
|
147
128
|
/**
|
|
148
129
|
* Returns the geolocation code. Serves from cache when the TTL has not
|
|
149
|
-
* expired, otherwise performs a network fetch.
|
|
150
|
-
* deduplicated to a single in-flight request.
|
|
130
|
+
* expired, otherwise performs a network fetch.
|
|
151
131
|
*
|
|
152
132
|
* @param options - Optional fetch options.
|
|
153
|
-
* @param options.bypassCache - When true,
|
|
154
|
-
*
|
|
155
|
-
* applies).
|
|
133
|
+
* @param options.bypassCache - When true, ignores any cached result and
|
|
134
|
+
* fetches fresh data.
|
|
156
135
|
* @returns An ISO 3166-2 location code (e.g. `US`, `US-NY`, `CA-ON`), or
|
|
157
136
|
* {@link UNKNOWN_LOCATION} when the API returns an empty or invalid body.
|
|
158
137
|
*/
|
|
@@ -160,12 +139,11 @@ export declare class GeolocationApiService {
|
|
|
160
139
|
/**
|
|
161
140
|
* Returns the country, region, and timezone for the current client. Serves
|
|
162
141
|
* from cache when the TTL has not expired, otherwise performs a network
|
|
163
|
-
* fetch.
|
|
142
|
+
* fetch.
|
|
164
143
|
*
|
|
165
144
|
* @param options - Optional fetch options.
|
|
166
|
-
* @param options.bypassCache - When true,
|
|
167
|
-
*
|
|
168
|
-
* applies).
|
|
145
|
+
* @param options.bypassCache - When true, ignores any cached result and
|
|
146
|
+
* fetches fresh data.
|
|
169
147
|
* @returns The geolocation data, where each field is `null` when the API
|
|
170
148
|
* omits it or returns a value that fails validation.
|
|
171
149
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"geolocation-api-service.d.ts","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"geolocation-api-service.d.ts","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,MAAM,6BAA6B,CAAC;AAErC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAQrD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;A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mEAAmE;IACnE,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,qBAAa,qBAAsB,SAAQ,eAAe,CACxD,OAAO,WAAW,EAClB,8BAA8B,CAC/B;;IAOC;;;;;;;;;;;;;OAaG;IACH,YAAY,EACV,SAAS,EACT,GAAa,EACb,KAAK,EAAE,aAAgC,EACvC,KAAK,EACL,aAAkB,GACnB,EAAE;QACD,SAAS,EAAE,8BAA8B,CAAC;QAC1C,GAAG,CAAC,EAAE,GAAG,CAAC;QACV,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;QACrB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,aAAa,CAAC,EAAE,0BAA0B,CAAC;KAC5C,EAUA;IAED;;;;;;;;;OASG;IACG,gBAAgB,CAAC,OAAO,CAAC,EAAE,uBAAuB,GAAG,OAAO,CAAC,MAAM,CAAC,CAEzE;IAED;;;;;;;;;;OAUG;IACG,oBAAoB,CACxB,OAAO,CAAC,EAAE,uBAAuB,GAChC,OAAO,CAAC,eAAe,CAAC,CAmC1B;CACF"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { BaseDataService } from '@metamask/base-data-service';
|
|
2
|
+
import { HttpError } from '@metamask/controller-utils';
|
|
3
|
+
import { nullable, object, pattern as matches, string, } from '@metamask/superstruct';
|
|
2
4
|
import { Env } from '../types.js';
|
|
3
5
|
const DEFAULT_TTL_MS = 5 * 60 * 1000;
|
|
4
6
|
const ENDPOINT_PATH = '/v2/geolocation';
|
|
@@ -30,6 +32,14 @@ export function getUnknownGeolocationData() {
|
|
|
30
32
|
* the United States and Canada (e.g. `US-NY`, `CA-ON`) and returned the country
|
|
31
33
|
* alone for everywhere else.
|
|
32
34
|
*/
|
|
35
|
+
/**
|
|
36
|
+
* Describes the validated shape of {@link GeolocationData}.
|
|
37
|
+
*/
|
|
38
|
+
const GeolocationDataStruct = object({
|
|
39
|
+
country: nullable(matches(string(), COUNTRY_PATTERN)),
|
|
40
|
+
region: nullable(matches(string(), REGION_PATTERN)),
|
|
41
|
+
timezone: nullable(matches(string(), TIMEZONE_PATTERN)),
|
|
42
|
+
});
|
|
33
43
|
const REGION_APPENDED_COUNTRIES = new Set(['US', 'CA']);
|
|
34
44
|
/**
|
|
35
45
|
* Converts geolocation data to a location code.
|
|
@@ -127,32 +137,16 @@ function parseGeolocationResponse(raw) {
|
|
|
127
137
|
* Responsibilities:
|
|
128
138
|
* - HTTP request to the geolocation endpoint (wrapped in a service policy)
|
|
129
139
|
* - Response validation of the country, region, and timezone fields
|
|
130
|
-
* - TTL-based in-memory cache
|
|
131
|
-
* - Promise deduplication (concurrent callers share a single in-flight request)
|
|
132
140
|
*
|
|
133
141
|
* This class is intentionally not a controller: it does not manage UI state.
|
|
134
142
|
* Its {@link fetchGeolocation} and {@link fetchGeolocationData} methods are
|
|
135
143
|
* automatically registered on the messenger so that controllers and other
|
|
136
144
|
* packages can call them directly.
|
|
137
145
|
*/
|
|
138
|
-
export class GeolocationApiService {
|
|
139
|
-
/**
|
|
140
|
-
* The name of the service.
|
|
141
|
-
*/
|
|
142
|
-
name;
|
|
143
|
-
#messenger;
|
|
146
|
+
export class GeolocationApiService extends BaseDataService {
|
|
144
147
|
#fetch;
|
|
145
148
|
#url;
|
|
146
149
|
#ttlMs;
|
|
147
|
-
/**
|
|
148
|
-
* The policy that wraps each HTTP request.
|
|
149
|
-
*
|
|
150
|
-
* @see {@link createServicePolicy}
|
|
151
|
-
*/
|
|
152
|
-
#policy;
|
|
153
|
-
#cachedGeolocation = getUnknownGeolocationData();
|
|
154
|
-
#lastFetchedAt = null;
|
|
155
|
-
#fetchPromise = null;
|
|
156
150
|
/**
|
|
157
151
|
* Constructs a new {@link GeolocationApiService}.
|
|
158
152
|
*
|
|
@@ -162,61 +156,25 @@ export class GeolocationApiService {
|
|
|
162
156
|
* Defaults to PRD.
|
|
163
157
|
* @param args.fetch - A function that can be used to make an HTTP request.
|
|
164
158
|
* Defaults to the global fetch.
|
|
165
|
-
* @param args.ttlMs -
|
|
159
|
+
* @param args.ttlMs - How long a fetched result is served from cache, in
|
|
160
|
+
* milliseconds. Defaults to 5 minutes.
|
|
166
161
|
* @param args.policyOptions - Options to pass to `createServicePolicy`, which
|
|
167
162
|
* is used to wrap each request. See {@link CreateServicePolicyOptions}.
|
|
168
163
|
*/
|
|
169
164
|
constructor({ messenger, env = Env.PRD, fetch: fetchFunction = globalThis.fetch, ttlMs, policyOptions = {}, }) {
|
|
170
|
-
|
|
171
|
-
this.#messenger = messenger;
|
|
165
|
+
super({ name: serviceName, messenger, policyOptions });
|
|
172
166
|
this.#url = getGeolocationUrl(env);
|
|
173
167
|
this.#fetch = fetchFunction;
|
|
174
168
|
this.#ttlMs = ttlMs ?? DEFAULT_TTL_MS;
|
|
175
|
-
this
|
|
176
|
-
this.#messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
177
|
-
}
|
|
178
|
-
/**
|
|
179
|
-
* Registers a handler that will be called after a request returns a 5xx
|
|
180
|
-
* response, causing a retry.
|
|
181
|
-
*
|
|
182
|
-
* @param listener - The handler to be called.
|
|
183
|
-
* @returns An object that can be used to unregister the handler.
|
|
184
|
-
* @see {@link createServicePolicy}
|
|
185
|
-
*/
|
|
186
|
-
onRetry(listener) {
|
|
187
|
-
return this.#policy.onRetry(listener);
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
|
-
* Registers a handler that will be called after a set number of retry rounds
|
|
191
|
-
* prove that requests to the API endpoint consistently return a 5xx response.
|
|
192
|
-
*
|
|
193
|
-
* @param listener - The handler to be called.
|
|
194
|
-
* @returns An object that can be used to unregister the handler.
|
|
195
|
-
* @see {@link createServicePolicy}
|
|
196
|
-
*/
|
|
197
|
-
onBreak(listener) {
|
|
198
|
-
return this.#policy.onBreak(listener);
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Registers a handler that will be called when requests are consistently
|
|
202
|
-
* failing or when a successful request takes longer than the degraded
|
|
203
|
-
* threshold.
|
|
204
|
-
*
|
|
205
|
-
* @param listener - The handler to be called.
|
|
206
|
-
* @returns An object that can be used to unregister the handler.
|
|
207
|
-
*/
|
|
208
|
-
onDegraded(listener) {
|
|
209
|
-
return this.#policy.onDegraded(listener);
|
|
169
|
+
this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
210
170
|
}
|
|
211
171
|
/**
|
|
212
172
|
* Returns the geolocation code. Serves from cache when the TTL has not
|
|
213
|
-
* expired, otherwise performs a network fetch.
|
|
214
|
-
* deduplicated to a single in-flight request.
|
|
173
|
+
* expired, otherwise performs a network fetch.
|
|
215
174
|
*
|
|
216
175
|
* @param options - Optional fetch options.
|
|
217
|
-
* @param options.bypassCache - When true,
|
|
218
|
-
*
|
|
219
|
-
* applies).
|
|
176
|
+
* @param options.bypassCache - When true, ignores any cached result and
|
|
177
|
+
* fetches fresh data.
|
|
220
178
|
* @returns An ISO 3166-2 location code (e.g. `US`, `US-NY`, `CA-ON`), or
|
|
221
179
|
* {@link UNKNOWN_LOCATION} when the API returns an empty or invalid body.
|
|
222
180
|
*/
|
|
@@ -226,68 +184,38 @@ export class GeolocationApiService {
|
|
|
226
184
|
/**
|
|
227
185
|
* Returns the country, region, and timezone for the current client. Serves
|
|
228
186
|
* from cache when the TTL has not expired, otherwise performs a network
|
|
229
|
-
* fetch.
|
|
187
|
+
* fetch.
|
|
230
188
|
*
|
|
231
189
|
* @param options - Optional fetch options.
|
|
232
|
-
* @param options.bypassCache - When true,
|
|
233
|
-
*
|
|
234
|
-
* applies).
|
|
190
|
+
* @param options.bypassCache - When true, ignores any cached result and
|
|
191
|
+
* fetches fresh data.
|
|
235
192
|
* @returns The geolocation data, where each field is `null` when the API
|
|
236
193
|
* omits it or returns a value that fails validation.
|
|
237
194
|
*/
|
|
238
195
|
async fetchGeolocationData(options) {
|
|
196
|
+
const queryKey = [`${this.name}:fetchGeolocationData`];
|
|
239
197
|
if (options?.bypassCache) {
|
|
240
|
-
this
|
|
241
|
-
}
|
|
242
|
-
if (this.#isCacheValid()) {
|
|
243
|
-
return this.#cachedGeolocation;
|
|
198
|
+
await this.invalidateQueries({ queryKey, refetchType: 'none' });
|
|
244
199
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Checks whether the cached geolocation is still within the TTL window.
|
|
259
|
-
*
|
|
260
|
-
* @returns True if the cache is valid.
|
|
261
|
-
*/
|
|
262
|
-
#isCacheValid() {
|
|
263
|
-
return (this.#lastFetchedAt !== null &&
|
|
264
|
-
Date.now() - this.#lastFetchedAt < this.#ttlMs);
|
|
265
|
-
}
|
|
266
|
-
/**
|
|
267
|
-
* Performs the actual HTTP fetch, wrapped in the service policy for automatic
|
|
268
|
-
* retry and circuit-breaking, and validates the response.
|
|
269
|
-
*
|
|
270
|
-
* @returns The validated geolocation data.
|
|
271
|
-
*/
|
|
272
|
-
async #performFetch() {
|
|
273
|
-
const response = await this.#policy.execute(async () => {
|
|
274
|
-
const localResponse = await this.#fetch(this.#url);
|
|
275
|
-
if (!localResponse.ok) {
|
|
276
|
-
throw new HttpError(localResponse.status, `Geolocation fetch failed: ${localResponse.status}`);
|
|
277
|
-
}
|
|
278
|
-
return localResponse;
|
|
200
|
+
const geolocation = await this.fetchQuery({
|
|
201
|
+
queryKey,
|
|
202
|
+
staleTime: this.#ttlMs,
|
|
203
|
+
responseStruct: GeolocationDataStruct,
|
|
204
|
+
gcTime: this.#ttlMs,
|
|
205
|
+
queryFn: async () => {
|
|
206
|
+
const response = await this.#fetch(this.#url);
|
|
207
|
+
if (!response.ok) {
|
|
208
|
+
throw new HttpError(response.status, `Geolocation fetch failed: ${response.status}`);
|
|
209
|
+
}
|
|
210
|
+
return parseGeolocationResponse((await response.text()).trim());
|
|
211
|
+
},
|
|
279
212
|
});
|
|
280
|
-
|
|
281
|
-
//
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
geolocation.region !== null ||
|
|
287
|
-
geolocation.timezone !== null;
|
|
288
|
-
if (hasKnownField) {
|
|
289
|
-
this.#cachedGeolocation = geolocation;
|
|
290
|
-
this.#lastFetchedAt = Date.now();
|
|
213
|
+
// A partially-known result is worth keeping for the whole TTL. A
|
|
214
|
+
// fully-unknown one is marked stale so the next call retries it.
|
|
215
|
+
if (geolocation.country === null &&
|
|
216
|
+
geolocation.region === null &&
|
|
217
|
+
geolocation.timezone === null) {
|
|
218
|
+
await this.invalidateQueries({ queryKey, refetchType: 'none' });
|
|
291
219
|
}
|
|
292
220
|
return geolocation;
|
|
293
221
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"geolocation-api-service.js","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAI5E,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;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,IA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CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;CACF","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.js","sourceRoot":"","sources":["../../src/geolocation-api-service/geolocation-api-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAO9D,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAEvD,OAAO,EACL,QAAQ,EACR,MAAM,EACN,OAAO,IAAI,OAAO,EAClB,MAAM,GACP,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAGlC,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAErC,MAAM,aAAa,GAAG,iBAAiB,CAAC;AAExC,MAAM,eA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AC,UAAU,CAAC;YACxC,QAAQ;YACR,SAAS,EAAE,IAAI,CAAC,MAAM;YACtB,cAAc,EAAE,qBAAqB;YACrC,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBAC9C,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;oBACjB,MAAM,IAAI,SAAS,CACjB,QAAQ,CAAC,MAAM,EACf,6BAA6B,QAAQ,CAAC,MAAM,EAAE,CAC/C,CAAC;gBACJ,CAAC;gBACD,OAAO,wBAAwB,CAAC,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;YAClE,CAAC;SACF,CAAC,CAAC;QAEH,iEAAiE;QACjE,iEAAiE;QACjE,IACE,WAAW,CAAC,OAAO,KAAK,IAAI;YAC5B,WAAW,CAAC,MAAM,KAAK,IAAI;YAC3B,WAAW,CAAC,QAAQ,KAAK,IAAI,EAC7B,CAAC;YACD,MAAM,IAAI,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC;QAClE,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { BaseDataService } from '@metamask/base-data-service';\nimport type {\n CreateServicePolicyOptions,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport { HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport {\n nullable,\n object,\n pattern as matches,\n string,\n} from '@metamask/superstruct';\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 */\n/**\n * Describes the validated shape of {@link GeolocationData}.\n */\nconst GeolocationDataStruct = object({\n country: nullable(matches(string(), COUNTRY_PATTERN)),\n region: nullable(matches(string(), REGION_PATTERN)),\n timezone: nullable(matches(string(), TIMEZONE_PATTERN)),\n});\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 * Invalidates cached queries for {@link GeolocationApiService}.\n */\nexport type GeolocationApiServiceInvalidateQueriesAction =\n DataServiceInvalidateQueriesAction<typeof serviceName>;\n\n/**\n * Actions that {@link GeolocationApiService} exposes to other consumers.\n */\nexport type GeolocationApiServiceActions =\n | GeolocationApiServiceMethodActions\n | GeolocationApiServiceInvalidateQueriesAction;\n\n/**\n * Actions from other messengers that {@link GeolocationApiServiceMessenger}\n * calls.\n */\ntype AllowedActions = never;\n\n/**\n * Published when {@link GeolocationApiService}'s cache is updated.\n */\nexport type GeolocationApiServiceCacheUpdatedEvent =\n DataServiceCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Published when a key within {@link GeolocationApiService}'s cache is\n * updated.\n */\nexport type GeolocationApiServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Events that {@link GeolocationApiService} exposes to other consumers.\n */\nexport type GeolocationApiServiceEvents =\n | GeolocationApiServiceCacheUpdatedEvent\n | GeolocationApiServiceGranularCacheUpdatedEvent;\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, ignores any cached result and 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 *\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 extends BaseDataService<\n typeof serviceName,\n GeolocationApiServiceMessenger\n> {\n readonly #fetch: typeof globalThis.fetch;\n\n readonly #url: string;\n\n readonly #ttlMs: number;\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 - How long a fetched result is served from cache, in\n * 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 super({ name: serviceName, messenger, policyOptions });\n this.#url = getGeolocationUrl(env);\n this.#fetch = fetchFunction;\n this.#ttlMs = ttlMs ?? DEFAULT_TTL_MS;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Returns the geolocation code. Serves from cache when the TTL has not\n * expired, otherwise performs a network fetch.\n *\n * @param options - Optional fetch options.\n * @param options.bypassCache - When true, ignores any cached result and\n * fetches fresh data.\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.\n *\n * @param options - Optional fetch options.\n * @param options.bypassCache - When true, ignores any cached result and\n * fetches fresh data.\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 const queryKey = [`${this.name}:fetchGeolocationData`] as const;\n\n if (options?.bypassCache) {\n await this.invalidateQueries({ queryKey, refetchType: 'none' });\n }\n\n const geolocation = await this.fetchQuery({\n queryKey,\n staleTime: this.#ttlMs,\n responseStruct: GeolocationDataStruct,\n gcTime: this.#ttlMs,\n queryFn: async () => {\n const response = await this.#fetch(this.#url);\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Geolocation fetch failed: ${response.status}`,\n );\n }\n return parseGeolocationResponse((await response.text()).trim());\n },\n });\n\n // A partially-known result is worth keeping for the whole TTL. A\n // fully-unknown one is marked stale so the next call retries it.\n if (\n geolocation.country === null &&\n geolocation.region === null &&\n geolocation.timezone === null\n ) {\n await this.invalidateQueries({ queryKey, refetchType: 'none' });\n }\n\n return geolocation;\n }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,6 @@ export type { GeolocationRequestStatus } from './types.js';
|
|
|
4
4
|
export { Env } from './types.js';
|
|
5
5
|
export { GeolocationController, getDefaultGeolocationControllerState, } from './GeolocationController.js';
|
|
6
6
|
export { GeolocationApiService, getUnknownGeolocationData, toLocationCode, UNKNOWN_LOCATION, } from './geolocation-api-service/geolocation-api-service.js';
|
|
7
|
-
export type { GeolocationApiServiceMessenger, GeolocationApiServiceActions, GeolocationApiServiceEvents, FetchGeolocationOptions, GeolocationData, } from './geolocation-api-service/geolocation-api-service.js';
|
|
7
|
+
export type { GeolocationApiServiceMessenger, GeolocationApiServiceActions, GeolocationApiServiceEvents, GeolocationApiServiceCacheUpdatedEvent, GeolocationApiServiceGranularCacheUpdatedEvent, GeolocationApiServiceInvalidateQueriesAction, FetchGeolocationOptions, GeolocationData, } from './geolocation-api-service/geolocation-api-service.js';
|
|
8
8
|
export type { GeolocationApiServiceFetchGeolocationAction, GeolocationApiServiceFetchGeolocationDataAction, } from './geolocation-api-service/geolocation-api-service-method-action-types.js';
|
|
9
9
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,0BAA0B,EAC1B,mCAAmC,EACnC,4BAA4B,EAC5B,qCAAqC,EACrC,2BAA2B,EAC3B,8BAA8B,EAC9B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC;AACpC,YAAY,EACV,yCAAyC,EACzC,6CAA6C,EAC7C,6CAA6C,GAC9C,MAAM,gDAAgD,CAAC;AACxD,YAAY,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAC3D,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EACzB,cAAc,EACd,gBAAgB,GACjB,MAAM,sDAAsD,CAAC;AAC9D,YAAY,EACV,8BAA8B,EAC9B,4BAA4B,EAC5B,2BAA2B,EAC3B,uBAAuB,EACvB,eAAe,GAChB,MAAM,sDAAsD,CAAC;AAC9D,YAAY,EACV,2CAA2C,EAC3C,+CAA+C,GAChD,MAAM,0EAA0E,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,0BAA0B,EAC1B,mCAAmC,EACnC,4BAA4B,EAC5B,qCAAqC,EACrC,2BAA2B,EAC3B,8BAA8B,EAC9B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC;AACpC,YAAY,EACV,yCAAyC,EACzC,6CAA6C,EAC7C,6CAA6C,GAC9C,MAAM,gDAAgD,CAAC;AACxD,YAAY,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAC3D,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EACzB,cAAc,EACd,gBAAgB,GACjB,MAAM,sDAAsD,CAAC;AAC9D,YAAY,EACV,8BAA8B,EAC9B,4BAA4B,EAC5B,2BAA2B,EAC3B,sCAAsC,EACtC,8CAA8C,EAC9C,4CAA4C,EAC5C,uBAAuB,EACvB,eAAe,GAChB,MAAM,sDAAsD,CAAC;AAC9D,YAAY,EACV,2CAA2C,EAC3C,+CAA+C,GAChD,MAAM,0EAA0E,CAAC"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EACzB,cAAc,EACd,gBAAgB,GACjB,MAAM,sDAAsD,CAAC","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 GeolocationControllerGetGeolocationDataAction,\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 getUnknownGeolocationData,\n toLocationCode,\n UNKNOWN_LOCATION,\n} from './geolocation-api-service/geolocation-api-service.js';\nexport type {\n GeolocationApiServiceMessenger,\n GeolocationApiServiceActions,\n GeolocationApiServiceEvents,\n FetchGeolocationOptions,\n GeolocationData,\n} from './geolocation-api-service/geolocation-api-service.js';\nexport type {\n GeolocationApiServiceFetchGeolocationAction,\n GeolocationApiServiceFetchGeolocationDataAction,\n} from './geolocation-api-service/geolocation-api-service-method-action-types.js';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACjC,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EACzB,cAAc,EACd,gBAAgB,GACjB,MAAM,sDAAsD,CAAC","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 GeolocationControllerGetGeolocationDataAction,\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 getUnknownGeolocationData,\n toLocationCode,\n UNKNOWN_LOCATION,\n} from './geolocation-api-service/geolocation-api-service.js';\nexport type {\n GeolocationApiServiceMessenger,\n GeolocationApiServiceActions,\n GeolocationApiServiceEvents,\n GeolocationApiServiceCacheUpdatedEvent,\n GeolocationApiServiceGranularCacheUpdatedEvent,\n GeolocationApiServiceInvalidateQueriesAction,\n FetchGeolocationOptions,\n GeolocationData,\n} from './geolocation-api-service/geolocation-api-service.js';\nexport type {\n GeolocationApiServiceFetchGeolocationAction,\n GeolocationApiServiceFetchGeolocationDataAction,\n} from './geolocation-api-service/geolocation-api-service-method-action-types.js';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/geolocation-controller",
|
|
3
|
-
"version": "2.0.0-preview-
|
|
3
|
+
"version": "2.0.0-preview-01e391e",
|
|
4
4
|
"description": "Centralised geolocation controller with TTL caching and request deduplication",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -51,8 +51,10 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@metamask/base-controller": "^10.1.0",
|
|
54
|
+
"@metamask/base-data-service": "^2.1.0",
|
|
54
55
|
"@metamask/controller-utils": "^13.0.0",
|
|
55
|
-
"@metamask/messenger": "^3.0.0"
|
|
56
|
+
"@metamask/messenger": "^3.0.0",
|
|
57
|
+
"@metamask/superstruct": "^3.4.1"
|
|
56
58
|
},
|
|
57
59
|
"devDependencies": {
|
|
58
60
|
"@metamask/auto-changelog": "^6.2.1",
|