@carto/api-client 0.5.0-alpha.4 → 0.5.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/build/api-client.cjs +2803 -2697
  2. package/build/api-client.d.cts +1384 -0
  3. package/build/api-client.d.ts +1384 -0
  4. package/build/api-client.js +1722 -0
  5. package/build/chunk-LEI5PI5X.js +2063 -0
  6. package/build/worker.d.ts +2 -0
  7. package/build/worker.js +23 -0
  8. package/package.json +18 -18
  9. package/src/constants-internal.ts +0 -6
  10. package/src/filters/tileFeatures.ts +10 -26
  11. package/src/global.d.ts +3 -8
  12. package/src/sources/h3-tileset-source.ts +8 -1
  13. package/src/sources/quadbin-tileset-source.ts +8 -1
  14. package/src/sources/raster-source.ts +5 -18
  15. package/src/sources/types.ts +7 -1
  16. package/src/sources/vector-tileset-source.ts +8 -1
  17. package/src/types.ts +0 -6
  18. package/src/widget-sources/index.ts +1 -1
  19. package/src/widget-sources/widget-remote-source.ts +35 -2
  20. package/src/widget-sources/widget-source.ts +1 -38
  21. package/src/widget-sources/widget-tileset-source.ts +9 -20
  22. package/src/widget-sources/widget-tileset-worker-source.ts +268 -0
  23. package/src/workers/constants.ts +13 -0
  24. package/src/workers/types.ts +19 -0
  25. package/src/workers/utils.ts +33 -0
  26. package/src/workers/widget-tileset-worker.ts +39 -0
  27. package/build/api/carto-api-error.d.ts +0 -26
  28. package/build/api/endpoints.d.ts +0 -24
  29. package/build/api/index.d.ts +0 -5
  30. package/build/api/query.d.ts +0 -3
  31. package/build/api/request-with-parameters.d.ts +0 -10
  32. package/build/api-client.cjs.map +0 -1
  33. package/build/api-client.modern.js +0 -3445
  34. package/build/api-client.modern.js.map +0 -1
  35. package/build/client.d.ts +0 -14
  36. package/build/constants-internal.d.ts +0 -26
  37. package/build/constants.d.ts +0 -53
  38. package/build/deck/get-data-filter-extension-props.d.ts +0 -18
  39. package/build/deck/index.d.ts +0 -1
  40. package/build/filters/Filter.d.ts +0 -25
  41. package/build/filters/FilterTypes.d.ts +0 -3
  42. package/build/filters/geosjonFeatures.d.ts +0 -8
  43. package/build/filters/index.d.ts +0 -6
  44. package/build/filters/tileFeatures.d.ts +0 -21
  45. package/build/filters/tileFeaturesGeometries.d.ts +0 -13
  46. package/build/filters/tileFeaturesRaster.d.ts +0 -16
  47. package/build/filters/tileFeaturesSpatialIndex.d.ts +0 -10
  48. package/build/filters.d.ts +0 -39
  49. package/build/geo.d.ts +0 -19
  50. package/build/index.d.ts +0 -16
  51. package/build/models/common.d.ts +0 -28
  52. package/build/models/index.d.ts +0 -3
  53. package/build/models/model.d.ts +0 -37
  54. package/build/operations/aggregation.d.ts +0 -8
  55. package/build/operations/applySorting.d.ts +0 -20
  56. package/build/operations/groupBy.d.ts +0 -15
  57. package/build/operations/groupByDate.d.ts +0 -11
  58. package/build/operations/histogram.d.ts +0 -13
  59. package/build/operations/index.d.ts +0 -6
  60. package/build/operations/scatterPlot.d.ts +0 -14
  61. package/build/sources/base-source.d.ts +0 -4
  62. package/build/sources/boundary-query-source.d.ts +0 -10
  63. package/build/sources/boundary-table-source.d.ts +0 -8
  64. package/build/sources/h3-query-source.d.ts +0 -5
  65. package/build/sources/h3-table-source.d.ts +0 -5
  66. package/build/sources/h3-tileset-source.d.ts +0 -5
  67. package/build/sources/index.d.ts +0 -26
  68. package/build/sources/quadbin-query-source.d.ts +0 -5
  69. package/build/sources/quadbin-table-source.d.ts +0 -5
  70. package/build/sources/quadbin-tileset-source.d.ts +0 -5
  71. package/build/sources/raster-source.d.ts +0 -5
  72. package/build/sources/types.d.ts +0 -366
  73. package/build/sources/vector-query-source.d.ts +0 -5
  74. package/build/sources/vector-table-source.d.ts +0 -5
  75. package/build/sources/vector-tileset-source.d.ts +0 -5
  76. package/build/spatial-index.d.ts +0 -14
  77. package/build/types-internal.d.ts +0 -56
  78. package/build/types.d.ts +0 -148
  79. package/build/utils/dateUtils.d.ts +0 -10
  80. package/build/utils/getTileFormat.d.ts +0 -3
  81. package/build/utils/makeIntervalComplete.d.ts +0 -2
  82. package/build/utils/transformTileCoordsToWGS84.d.ts +0 -8
  83. package/build/utils/transformToTileCoords.d.ts +0 -9
  84. package/build/utils.d.ts +0 -32
  85. package/build/widget-sources/index.d.ts +0 -7
  86. package/build/widget-sources/types.d.ts +0 -160
  87. package/build/widget-sources/widget-query-source.d.ts +0 -34
  88. package/build/widget-sources/widget-raster-source.d.ts +0 -11
  89. package/build/widget-sources/widget-remote-source.d.ts +0 -21
  90. package/build/widget-sources/widget-source.d.ts +0 -74
  91. package/build/widget-sources/widget-table-source.d.ts +0 -34
  92. package/build/widget-sources/widget-tileset-source.d.ts +0 -75
  93. package/src/filters/tileFeaturesRaster.ts +0 -111
  94. package/src/widget-sources/widget-raster-source.ts +0 -14
@@ -0,0 +1,268 @@
1
+ import {
2
+ CategoryRequestOptions,
3
+ CategoryResponse,
4
+ FeaturesResponse,
5
+ FormulaRequestOptions,
6
+ FormulaResponse,
7
+ HistogramRequestOptions,
8
+ HistogramResponse,
9
+ RangeRequestOptions,
10
+ RangeResponse,
11
+ ScatterRequestOptions,
12
+ ScatterResponse,
13
+ TableRequestOptions,
14
+ TableResponse,
15
+ TimeSeriesRequestOptions,
16
+ TimeSeriesResponse,
17
+ } from './types.js';
18
+ import {SpatialFilter, Tile} from '../types.js';
19
+ import {TileFeatureExtractOptions} from '../filters/index.js';
20
+ import {FeatureCollection} from 'geojson';
21
+ import {WidgetSource} from './widget-source.js';
22
+ import {WidgetTilesetSourceProps} from './widget-tileset-source.js';
23
+ import {Method} from '../workers/constants.js';
24
+ import {WorkerRequest, WorkerResponse} from '../workers/types.js';
25
+
26
+ /**
27
+ * Wrapper for {@link WidgetTilesetSource}, moving calculations to Web Workers.
28
+ * When supported, use of both classes is identical.
29
+ *
30
+ * To use this wrapper, the application and environment must support ESM Web
31
+ * Workers. For older build systems based on CommonJS, or in environments like
32
+ * Node.js, it may be necessary to use {@link WidgetTilesetSource} directly,
33
+ * and to (optionally) create workers manually in the application.
34
+ */
35
+ export class WidgetTilesetWorkerSource extends WidgetSource<WidgetTilesetSourceProps> {
36
+ constructor(props: WidgetTilesetSourceProps) {
37
+ super(props);
38
+ }
39
+
40
+ /////////////////////////////////////////////////////////////////////////////
41
+ // WEB WORKER MANAGEMENT
42
+
43
+ protected _worker: Worker | null = null;
44
+ protected _workerNextRequestId = 1;
45
+
46
+ /**
47
+ * Returns an initialized Worker, to be reused for the lifecycle of this
48
+ * source instance.
49
+ */
50
+ _getWorker() {
51
+ if (this._worker) {
52
+ return this._worker;
53
+ }
54
+
55
+ this._worker = new Worker(
56
+ new URL('@carto/api-client/worker', import.meta.url),
57
+ {
58
+ type: 'module',
59
+ name: 'cartowidgettileset',
60
+ }
61
+ );
62
+
63
+ this._worker.postMessage({
64
+ method: Method.INIT,
65
+ params: [this.props],
66
+ } as WorkerRequest);
67
+
68
+ return this._worker;
69
+ }
70
+
71
+ /** Executes a given method on the worker. */
72
+ _executeWorkerMethod<T>(
73
+ method: Method,
74
+ params: unknown[],
75
+ signal?: AbortSignal
76
+ ): Promise<T> {
77
+ const worker = this._getWorker();
78
+ const requestId = this._workerNextRequestId++;
79
+
80
+ // TODO: ViewState may contain non-serializable data, which we do not need.
81
+ // Remove this sanitization after sc-469614 is fixed.
82
+ const options = params[0] as any;
83
+ if (options?.spatialIndexReferenceViewState) {
84
+ const {zoom, latitude, longitude} =
85
+ options.spatialIndexReferenceViewState;
86
+ options.spatialIndexReferenceViewState = {zoom, latitude, longitude};
87
+ }
88
+
89
+ let resolve: ((value: T) => void) | null = null;
90
+ let reject: ((reason: any) => void) | null = null;
91
+
92
+ // If worker sends message to main process, check whether it's a response
93
+ // to this request, and whether the request can been aborted. Then resolve
94
+ // or reject the Promise.
95
+ function onMessage(e: MessageEvent) {
96
+ const response = e.data as WorkerResponse;
97
+ if (response.requestId !== requestId) return;
98
+
99
+ if (signal?.aborted) {
100
+ reject!(new Error(signal.reason));
101
+ } else if (response.ok) {
102
+ resolve!(response.result as T);
103
+ } else {
104
+ reject!(new Error(response.error));
105
+ }
106
+ }
107
+
108
+ // If request is aborted by user, immediately reject the Promise.
109
+ function onAbort() {
110
+ reject!(new Error(signal!.reason));
111
+ }
112
+
113
+ worker.addEventListener('message', onMessage);
114
+ signal?.addEventListener('abort', onAbort);
115
+
116
+ // Send the task to the worker, creating a Promise to resolve/reject later.
117
+ const promise = new Promise<T>((_resolve, _reject) => {
118
+ resolve = _resolve;
119
+ reject = _reject;
120
+
121
+ worker.postMessage({
122
+ requestId,
123
+ method,
124
+ params,
125
+ } as WorkerRequest);
126
+ });
127
+
128
+ // Whether the task completes, fails, or aborts: clean up afterward.
129
+ void promise.finally(() => {
130
+ worker.removeEventListener('message', onMessage);
131
+ signal?.removeEventListener('abort', onAbort);
132
+ });
133
+
134
+ return promise;
135
+ }
136
+
137
+ /////////////////////////////////////////////////////////////////////////////
138
+ // DATA LOADING
139
+
140
+ /**
141
+ * Loads features as a list of tiles (typically provided by deck.gl).
142
+ * After tiles are loaded, {@link extractTileFeatures} must be called
143
+ * before computing statistics on the tiles.
144
+ */
145
+ loadTiles(tiles: unknown[]) {
146
+ tiles = (tiles as Tile[]).map(({id, bbox, data}) => ({
147
+ id,
148
+ bbox,
149
+ data,
150
+ }));
151
+
152
+ this._getWorker().postMessage({
153
+ method: Method.LOAD_TILES,
154
+ params: [tiles],
155
+ } as WorkerRequest);
156
+ }
157
+
158
+ /** Configures options used to extract features from tiles. */
159
+ setTileFeatureExtractOptions(options: TileFeatureExtractOptions) {
160
+ this._getWorker().postMessage({
161
+ type: Method.SET_TILE_FEATURE_EXTRACT_OPTIONS,
162
+ params: [options],
163
+ });
164
+ }
165
+
166
+ /**
167
+ * Loads features as GeoJSON (used for testing).
168
+ * @experimental
169
+ * @internal Not for public use. Spatial filters in other method calls will be ignored.
170
+ */
171
+ loadGeoJSON({
172
+ geojson,
173
+ spatialFilter,
174
+ }: {
175
+ geojson: FeatureCollection;
176
+ spatialFilter: SpatialFilter;
177
+ }) {
178
+ this._getWorker().postMessage({
179
+ method: Method.LOAD_GEOJSON,
180
+ params: [{geojson, spatialFilter}],
181
+ } as WorkerRequest);
182
+ }
183
+
184
+ /////////////////////////////////////////////////////////////////////////////
185
+ // WIDGETS API
186
+
187
+ // eslint-disable-next-line @typescript-eslint/require-await
188
+ override async getFeatures(): Promise<FeaturesResponse> {
189
+ throw new Error('getFeatures not supported for tilesets');
190
+ }
191
+
192
+ async getFormula({
193
+ abortController,
194
+ ...options
195
+ }: FormulaRequestOptions): Promise<FormulaResponse> {
196
+ return this._executeWorkerMethod(
197
+ Method.GET_FORMULA,
198
+ [options],
199
+ abortController?.signal
200
+ );
201
+ }
202
+
203
+ override async getHistogram({
204
+ abortController,
205
+ ...options
206
+ }: HistogramRequestOptions): Promise<HistogramResponse> {
207
+ return this._executeWorkerMethod(
208
+ Method.GET_HISTOGRAM,
209
+ [options],
210
+ abortController?.signal
211
+ );
212
+ }
213
+
214
+ override async getCategories({
215
+ abortController,
216
+ ...options
217
+ }: CategoryRequestOptions): Promise<CategoryResponse> {
218
+ return this._executeWorkerMethod(
219
+ Method.GET_CATEGORIES,
220
+ [options],
221
+ abortController?.signal
222
+ );
223
+ }
224
+
225
+ override async getScatter({
226
+ abortController,
227
+ ...options
228
+ }: ScatterRequestOptions): Promise<ScatterResponse> {
229
+ return this._executeWorkerMethod(
230
+ Method.GET_SCATTER,
231
+ [options],
232
+ abortController?.signal
233
+ );
234
+ }
235
+
236
+ override async getTable({
237
+ abortController,
238
+ ...options
239
+ }: TableRequestOptions): Promise<TableResponse> {
240
+ return this._executeWorkerMethod(
241
+ Method.GET_TABLE,
242
+ [options],
243
+ abortController?.signal
244
+ );
245
+ }
246
+
247
+ override async getTimeSeries({
248
+ abortController,
249
+ ...options
250
+ }: TimeSeriesRequestOptions): Promise<TimeSeriesResponse> {
251
+ return this._executeWorkerMethod(
252
+ Method.GET_TIME_SERIES,
253
+ [options],
254
+ abortController?.signal
255
+ );
256
+ }
257
+
258
+ override async getRange({
259
+ abortController,
260
+ ...options
261
+ }: RangeRequestOptions): Promise<RangeResponse> {
262
+ return this._executeWorkerMethod(
263
+ Method.GET_RANGE,
264
+ [options],
265
+ abortController?.signal
266
+ );
267
+ }
268
+ }
@@ -0,0 +1,13 @@
1
+ export enum Method {
2
+ INIT = 'init',
3
+ LOAD_TILES = 'loadTiles',
4
+ SET_TILE_FEATURE_EXTRACT_OPTIONS = 'setTileFeatureExtractOptions',
5
+ LOAD_GEOJSON = 'loadGeoJSON',
6
+ GET_FORMULA = 'getFormula',
7
+ GET_HISTOGRAM = 'getHistogram',
8
+ GET_CATEGORIES = 'getCategories',
9
+ GET_SCATTER = 'getScatter',
10
+ GET_TABLE = 'getTable',
11
+ GET_TIME_SERIES = 'getTimeSeries',
12
+ GET_RANGE = 'getRange',
13
+ }
@@ -0,0 +1,19 @@
1
+ import type {Method} from './constants.js';
2
+
3
+ export type WorkerRequest = {
4
+ requestId?: number;
5
+ method: Method;
6
+ params: unknown[];
7
+ };
8
+
9
+ export type WorkerResponse =
10
+ | {
11
+ requestId: number;
12
+ ok: true;
13
+ result: unknown;
14
+ }
15
+ | {
16
+ requestId: number;
17
+ ok: false;
18
+ error: string;
19
+ };
@@ -0,0 +1,33 @@
1
+ let _isModuleWorkerSupported: boolean | null =
2
+ TSUP_FORMAT === 'cjs' ? false : null;
3
+
4
+ /**
5
+ * Checks whether current environment supports ES Module Workers, by way of a
6
+ * two-part check:
7
+ * (1) If this is a CJS build, return false.
8
+ * (2) If this is an ESM build, return true if the runtime supports ESM Workers.
9
+ */
10
+ export function isModuleWorkerSupported(): boolean {
11
+ if (_isModuleWorkerSupported !== null) {
12
+ return _isModuleWorkerSupported;
13
+ }
14
+
15
+ try {
16
+ // https://stackoverflow.com/a/62963963
17
+ new Worker('blob://', {
18
+ get type() {
19
+ _isModuleWorkerSupported = true;
20
+ return 'module' as const;
21
+ },
22
+ });
23
+ } catch {
24
+ // Do nothing. 'blob://' should always throw an error to prevent the
25
+ // browser from creating an (expensive) worker. We care whether the
26
+ // 'type' getter was called, not about the error.
27
+ } finally {
28
+ // If 'type' getter wasn't called, modules are unsupported.
29
+ _isModuleWorkerSupported ||= false;
30
+ }
31
+
32
+ return _isModuleWorkerSupported;
33
+ }
@@ -0,0 +1,39 @@
1
+ import {
2
+ WidgetTilesetSource,
3
+ type WidgetTilesetSourceProps,
4
+ } from '../widget-sources/widget-tileset-source.js';
5
+ import {Method} from './constants.js';
6
+ import type {WorkerRequest, WorkerResponse} from './types.js';
7
+
8
+ /*
9
+ * Web Worker, compiled as a separate `@carto/api-client/worker` entrypoint.
10
+ *
11
+ * Workers are scoped to the lifecycle of a single WidgetTilesetWorkerSource
12
+ * instance, representing and executing calculations on a single datasource.
13
+ */
14
+
15
+ let source: WidgetTilesetSource;
16
+
17
+ addEventListener('message', (e) => {
18
+ const {method, params, requestId} = e.data as WorkerRequest;
19
+
20
+ if (method === Method.INIT) {
21
+ source = new WidgetTilesetSource(params[0] as WidgetTilesetSourceProps);
22
+ return;
23
+ }
24
+
25
+ if (!source) {
26
+ const error = `Cannot execute "${method}" on uninitialized source.`;
27
+ postMessage({ok: false, error, requestId} as WorkerResponse);
28
+ return;
29
+ }
30
+
31
+ // @ts-expect-error No type-checking dynamic method name.
32
+ Promise.resolve(source[method](...params))
33
+ .then((result) => {
34
+ postMessage({ok: true, result, requestId} as WorkerResponse);
35
+ })
36
+ .catch((error) => {
37
+ postMessage({ok: false, error, requestId} as WorkerResponse);
38
+ });
39
+ });
@@ -1,26 +0,0 @@
1
- import { MapType } from '../types.js';
2
- export type APIRequestType = 'Map data' | 'Map instantiation' | 'Public map' | 'Tile stats' | 'SQL' | 'Basemap style';
3
- export type APIErrorContext = {
4
- requestType: APIRequestType;
5
- mapId?: string;
6
- connection?: string;
7
- source?: string;
8
- type?: MapType;
9
- };
10
- /**
11
- *
12
- * Custom error for reported errors in CARTO Maps API.
13
- * Provides useful debugging information in console and context for applications.
14
- *
15
- */
16
- export declare class CartoAPIError extends Error {
17
- /** Source error from server */
18
- error: Error;
19
- /** Context (API call & parameters) in which error occured */
20
- errorContext: APIErrorContext;
21
- /** Response from server */
22
- response?: Response;
23
- /** JSON Response from server */
24
- responseJson?: any;
25
- constructor(error: Error, errorContext: APIErrorContext, response?: Response, responseJson?: any);
26
- }
@@ -1,24 +0,0 @@
1
- import { MapType } from '../types.js';
2
- export type V3Endpoint = 'maps' | 'stats' | 'sql';
3
- /** @internal Required by fetchMap(). */
4
- export declare function buildPublicMapUrl({ apiBaseUrl, cartoMapId, }: {
5
- apiBaseUrl: string;
6
- cartoMapId: string;
7
- }): string;
8
- /** @internal Required by fetchMap(). */
9
- export declare function buildStatsUrl({ attribute, apiBaseUrl, connectionName, source, type, }: {
10
- attribute: string;
11
- apiBaseUrl: string;
12
- connectionName: string;
13
- source: string;
14
- type: MapType;
15
- }): string;
16
- export declare function buildSourceUrl({ apiBaseUrl, connectionName, endpoint, }: {
17
- apiBaseUrl: string;
18
- connectionName: string;
19
- endpoint: MapType;
20
- }): string;
21
- export declare function buildQueryUrl({ apiBaseUrl, connectionName, }: {
22
- apiBaseUrl: string;
23
- connectionName: string;
24
- }): string;
@@ -1,5 +0,0 @@
1
- export { CartoAPIError, APIErrorContext, APIRequestType, } from './carto-api-error.js';
2
- export { buildPublicMapUrl, buildStatsUrl } from './endpoints.js';
3
- export { query } from './query.js';
4
- export type { QueryOptions } from './query.js';
5
- export { requestWithParameters } from './request-with-parameters.js';
@@ -1,3 +0,0 @@
1
- import type { SourceOptions, QuerySourceOptions, QueryResult } from '../sources/types.js';
2
- export type QueryOptions = SourceOptions & QuerySourceOptions;
3
- export declare const query: (options: QueryOptions) => Promise<QueryResult>;
@@ -1,10 +0,0 @@
1
- import { APIErrorContext } from './carto-api-error.js';
2
- import { LocalCacheOptions } from '../sources/types.js';
3
- export declare function requestWithParameters<T = any>({ baseUrl, parameters, headers: customHeaders, errorContext, maxLengthURL, localCache, }: {
4
- baseUrl: string;
5
- parameters?: Record<string, unknown>;
6
- headers?: Record<string, string>;
7
- errorContext: APIErrorContext;
8
- maxLengthURL?: number;
9
- localCache?: LocalCacheOptions;
10
- }): Promise<T>;