@carto/api-client 0.4.6 → 0.4.7-0

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 (114) hide show
  1. package/build/api-client.cjs +3473 -1556
  2. package/build/api-client.cjs.map +1 -1
  3. package/build/api-client.d.cts +1389 -0
  4. package/build/api-client.d.ts +1389 -0
  5. package/build/api-client.js +3676 -0
  6. package/build/api-client.js.map +1 -0
  7. package/build/worker.d.ts +2 -0
  8. package/build/worker.js +1949 -0
  9. package/build/worker.js.map +1 -0
  10. package/package.json +58 -40
  11. package/src/api/carto-api-error.ts +1 -1
  12. package/src/api/query.ts +5 -5
  13. package/src/api/request-with-parameters.ts +6 -6
  14. package/src/client.ts +3 -3
  15. package/src/constants-internal.ts +5 -11
  16. package/src/constants.ts +28 -3
  17. package/src/deck/get-data-filter-extension-props.ts +146 -0
  18. package/src/deck/index.ts +1 -0
  19. package/src/filters/Filter.ts +179 -0
  20. package/src/filters/FilterTypes.ts +109 -0
  21. package/src/filters/geosjonFeatures.ts +32 -0
  22. package/src/filters/index.ts +6 -0
  23. package/src/filters/tileFeatures.ts +51 -0
  24. package/src/filters/tileFeaturesGeometries.ts +444 -0
  25. package/src/filters/tileFeaturesSpatialIndex.ts +119 -0
  26. package/src/filters.ts +4 -4
  27. package/src/geo.ts +12 -14
  28. package/src/global.d.ts +3 -8
  29. package/src/index.ts +7 -0
  30. package/src/models/common.ts +11 -9
  31. package/src/models/index.ts +1 -1
  32. package/src/models/model.ts +3 -4
  33. package/src/operations/aggregation.ts +154 -0
  34. package/src/operations/applySorting.ts +109 -0
  35. package/src/operations/groupBy.ts +59 -0
  36. package/src/operations/groupByDate.ts +98 -0
  37. package/src/operations/histogram.ts +66 -0
  38. package/src/operations/index.ts +6 -0
  39. package/src/operations/scatterPlot.ts +50 -0
  40. package/src/sources/base-source.ts +8 -8
  41. package/src/sources/boundary-query-source.ts +2 -2
  42. package/src/sources/boundary-table-source.ts +2 -2
  43. package/src/sources/h3-query-source.ts +7 -5
  44. package/src/sources/h3-table-source.ts +7 -5
  45. package/src/sources/h3-tileset-source.ts +20 -8
  46. package/src/sources/index.ts +26 -26
  47. package/src/sources/quadbin-query-source.ts +7 -5
  48. package/src/sources/quadbin-table-source.ts +7 -5
  49. package/src/sources/quadbin-tileset-source.ts +20 -8
  50. package/src/sources/raster-source.ts +3 -2
  51. package/src/sources/types.ts +9 -3
  52. package/src/sources/vector-query-source.ts +7 -5
  53. package/src/sources/vector-table-source.ts +7 -5
  54. package/src/sources/vector-tileset-source.ts +21 -8
  55. package/src/spatial-index.ts +4 -5
  56. package/src/types-internal.ts +11 -5
  57. package/src/types.ts +73 -15
  58. package/src/utils/dateUtils.ts +28 -0
  59. package/src/utils/getTileFormat.ts +9 -0
  60. package/src/utils/makeIntervalComplete.ts +17 -0
  61. package/src/utils/transformTileCoordsToWGS84.ts +77 -0
  62. package/src/utils/transformToTileCoords.ts +85 -0
  63. package/src/utils.ts +3 -3
  64. package/src/widget-sources/index.ts +3 -1
  65. package/src/widget-sources/types.ts +37 -25
  66. package/src/widget-sources/widget-query-source.ts +12 -5
  67. package/src/widget-sources/{widget-base-source.ts → widget-remote-source.ts} +55 -149
  68. package/src/widget-sources/widget-source.ts +145 -0
  69. package/src/widget-sources/widget-table-source.ts +12 -5
  70. package/src/widget-sources/widget-tileset-source-impl.ts +417 -0
  71. package/src/widget-sources/widget-tileset-source.ts +311 -0
  72. package/src/workers/constants.ts +13 -0
  73. package/src/workers/types.ts +19 -0
  74. package/src/workers/widget-tileset-worker.ts +40 -0
  75. package/build/api/carto-api-error.d.ts +0 -26
  76. package/build/api/endpoints.d.ts +0 -24
  77. package/build/api/index.d.ts +0 -5
  78. package/build/api/query.d.ts +0 -3
  79. package/build/api/request-with-parameters.d.ts +0 -10
  80. package/build/api-client.modern.js +0 -1742
  81. package/build/api-client.modern.js.map +0 -1
  82. package/build/client.d.ts +0 -14
  83. package/build/constants-internal.d.ts +0 -26
  84. package/build/constants.d.ts +0 -31
  85. package/build/filters.d.ts +0 -39
  86. package/build/geo.d.ts +0 -19
  87. package/build/index.d.ts +0 -11
  88. package/build/models/common.d.ts +0 -27
  89. package/build/models/index.d.ts +0 -3
  90. package/build/models/model.d.ts +0 -37
  91. package/build/sources/base-source.d.ts +0 -4
  92. package/build/sources/boundary-query-source.d.ts +0 -10
  93. package/build/sources/boundary-table-source.d.ts +0 -8
  94. package/build/sources/h3-query-source.d.ts +0 -5
  95. package/build/sources/h3-table-source.d.ts +0 -5
  96. package/build/sources/h3-tileset-source.d.ts +0 -4
  97. package/build/sources/index.d.ts +0 -26
  98. package/build/sources/quadbin-query-source.d.ts +0 -5
  99. package/build/sources/quadbin-table-source.d.ts +0 -5
  100. package/build/sources/quadbin-tileset-source.d.ts +0 -4
  101. package/build/sources/raster-source.d.ts +0 -4
  102. package/build/sources/types.d.ts +0 -366
  103. package/build/sources/vector-query-source.d.ts +0 -5
  104. package/build/sources/vector-table-source.d.ts +0 -5
  105. package/build/sources/vector-tileset-source.d.ts +0 -4
  106. package/build/spatial-index.d.ts +0 -14
  107. package/build/types-internal.d.ts +0 -52
  108. package/build/types.d.ts +0 -80
  109. package/build/utils.d.ts +0 -32
  110. package/build/widget-sources/index.d.ts +0 -4
  111. package/build/widget-sources/types.d.ts +0 -149
  112. package/build/widget-sources/widget-base-source.d.ts +0 -99
  113. package/build/widget-sources/widget-query-source.d.ts +0 -33
  114. package/build/widget-sources/widget-table-source.d.ts +0 -33
@@ -1,1742 +0,0 @@
1
- import bboxClip from '@turf/bbox-clip';
2
- import bboxPolygon from '@turf/bbox-polygon';
3
- import union from '@turf/union';
4
- import { getType } from '@turf/invariant';
5
- import { featureCollection, feature, polygon, multiPolygon } from '@turf/helpers';
6
-
7
- /**
8
- * @internal
9
- * @internalRemarks Source: @carto/react-core, @carto/constants, @deck.gl/carto
10
- */
11
- let client = 'deck-gl-carto';
12
- /**
13
- * Returns current client ID, used to categorize API requests. For internal use only.
14
- *
15
- * @internal
16
- * @internalRemarks Source: @carto/react-core
17
- */
18
- function getClient() {
19
- return client;
20
- }
21
- /**
22
- * Sets current client ID, used to categorize API requests. For internal use only.
23
- *
24
- * @internal
25
- * @internalRemarks Source: @carto/react-core
26
- */
27
- function setClient(c) {
28
- client = c;
29
- }
30
-
31
- /**
32
- * Defines a comparator used when matching a column's values against given filter values.
33
- *
34
- * Example:
35
- *
36
- * ```javascript
37
- * import { FilterType } from '@carto/api-client';
38
- * const filters = {
39
- * column_name: { [FilterType.IN]: { values: ['a', 'b', 'c'] } }
40
- * };
41
- * ```
42
- *
43
- * @internalRemarks Source: @carto/react-api, @deck.gl/carto
44
- */
45
- var FilterType;
46
- (function (FilterType) {
47
- FilterType["IN"] = "in";
48
- /** [a, b] both are included. */
49
- FilterType["BETWEEN"] = "between";
50
- /** [a, b) a is included, b is not. */
51
- FilterType["CLOSED_OPEN"] = "closed_open";
52
- FilterType["TIME"] = "time";
53
- FilterType["STRING_SEARCH"] = "stringSearch";
54
- })(FilterType || (FilterType = {}));
55
- /** @internalRemarks Source: @carto/constants */
56
- var ApiVersion;
57
- (function (ApiVersion) {
58
- ApiVersion["V1"] = "v1";
59
- ApiVersion["V2"] = "v2";
60
- ApiVersion["V3"] = "v3";
61
- })(ApiVersion || (ApiVersion = {}));
62
- /** @internalRemarks Source: @carto/constants, @deck.gl/carto */
63
- const DEFAULT_API_BASE_URL = 'https://gcp-us-east1.api.carto.com';
64
-
65
- const FILTER_TYPES = new Set(Object.values(FilterType));
66
- const isFilterType = type => FILTER_TYPES.has(type);
67
- /**
68
- * @privateRemarks Source: @carto/react-widgets
69
- * @internal
70
- */
71
- function getApplicableFilters(owner, filters) {
72
- if (!filters) return {};
73
- const applicableFilters = {};
74
- for (const column in filters) {
75
- for (const type in filters[column]) {
76
- if (!isFilterType(type)) continue;
77
- const filter = filters[column][type];
78
- const isApplicable = !owner || !(filter != null && filter.owner) || (filter == null ? void 0 : filter.owner) !== owner;
79
- if (filter && isApplicable) {
80
- applicableFilters[column] || (applicableFilters[column] = {});
81
- applicableFilters[column][type] = filter;
82
- }
83
- }
84
- }
85
- return applicableFilters;
86
- }
87
- /**
88
- * Due to each data warehouse having its own behavior with columns,
89
- * we need to normalize them and transform every key to lowercase.
90
- *
91
- * @internalRemarks Source: @carto/react-widgets
92
- * @internal
93
- */
94
- function normalizeObjectKeys(el) {
95
- if (Array.isArray(el)) {
96
- return el.map(value => normalizeObjectKeys(value));
97
- } else if (typeof el !== 'object') {
98
- return el;
99
- }
100
- return Object.entries(el).reduce((acc, [key, value]) => {
101
- acc[key.toLowerCase()] = typeof value === 'object' && value ? normalizeObjectKeys(value) : value;
102
- return acc;
103
- }, {});
104
- }
105
- /** @internalRemarks Source: @carto/react-core */
106
- function assert(condition, message) {
107
- if (!condition) {
108
- throw new Error(message);
109
- }
110
- }
111
- /**
112
- * @internalRemarks Source: @carto/react-core
113
- * @internal
114
- */
115
- class InvalidColumnError extends Error {
116
- constructor(message) {
117
- super(`${InvalidColumnError.NAME}: ${message}`);
118
- this.name = InvalidColumnError.NAME;
119
- }
120
- static is(error) {
121
- var _error$message;
122
- return error instanceof InvalidColumnError || ((_error$message = error.message) == null ? void 0 : _error$message.includes(InvalidColumnError.NAME));
123
- }
124
- }
125
- InvalidColumnError.NAME = 'InvalidColumnError';
126
- function isEmptyObject(object) {
127
- for (const _ in object) {
128
- return false;
129
- }
130
- return true;
131
- }
132
- /** @internal */
133
- const isObject = x => x !== null && typeof x === 'object';
134
- /** @internal */
135
- const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
136
-
137
- /**
138
- * Adds a {@link Filter} to the filter set. Any previous filters with the same
139
- * `column` and `type` will be replaced.
140
- */
141
- function addFilter(filters, {
142
- column,
143
- type,
144
- values,
145
- owner
146
- }) {
147
- if (!filters[column]) {
148
- filters[column] = {};
149
- }
150
- const filter = {
151
- values,
152
- owner
153
- };
154
- filters[column][type] = filter;
155
- return filters;
156
- }
157
- /**
158
- * Removes one or more {@link Filter filters} from the filter set. If only
159
- * `column` is specified, then all filters on that column are removed. If both
160
- * `column` and `owner` are specified, then only filters for that column
161
- * associated with the owner are removed.
162
- */
163
- function removeFilter(filters, {
164
- column,
165
- owner
166
- }) {
167
- const filter = filters[column];
168
- if (!filter) {
169
- return filters;
170
- }
171
- if (owner) {
172
- for (const type of Object.values(FilterType)) {
173
- var _filter$type;
174
- if (owner === ((_filter$type = filter[type]) == null ? void 0 : _filter$type.owner)) {
175
- delete filter[type];
176
- }
177
- }
178
- }
179
- if (!owner || isEmptyObject(filter)) {
180
- delete filters[column];
181
- }
182
- return filters;
183
- }
184
- /**
185
- * Clears all {@link Filter filters} from the filter set.
186
- */
187
- function clearFilters(filters) {
188
- for (const column of Object.keys(filters)) {
189
- delete filters[column];
190
- }
191
- return filters;
192
- }
193
- function hasFilter(filters, {
194
- column,
195
- owner
196
- }) {
197
- const filter = filters[column];
198
- if (!filter) {
199
- return false;
200
- }
201
- if (!owner) {
202
- return true;
203
- }
204
- for (const type of Object.values(FilterType)) {
205
- var _filter$type2;
206
- if (owner === ((_filter$type2 = filter[type]) == null ? void 0 : _filter$type2.owner)) {
207
- return true;
208
- }
209
- }
210
- return false;
211
- }
212
- function getFilter(filters, {
213
- column,
214
- type,
215
- owner
216
- }) {
217
- var _filter$type3;
218
- const filter = filters[column];
219
- if (!filter) {
220
- return null;
221
- }
222
- if (!owner || owner === ((_filter$type3 = filter[type]) == null ? void 0 : _filter$type3.owner)) {
223
- return filter[type] || null;
224
- }
225
- return null;
226
- }
227
-
228
- /**
229
- * Returns a {@link SpatialFilter} for a given viewport, typically obtained
230
- * from deck.gl's `viewport.getBounds()` method ([west, south, east, north]).
231
- * If the viewport covers the entire world (to some margin of error in Web
232
- * Mercator space), `undefined` is returned instead.
233
- *
234
- * If the viewport extends beyond longitude range [-180, +180], the polygon
235
- * may be reformatted for compatibility with CARTO APIs.
236
- */
237
- function createViewportSpatialFilter(viewport) {
238
- if (_isGlobalViewport(viewport)) {
239
- return;
240
- }
241
- return createPolygonSpatialFilter(bboxPolygon(viewport).geometry);
242
- }
243
- /**
244
- * Returns a {@link SpatialFilter} for a given {@link Polygon} or
245
- * {@link MultiPolygon}. If the polygon(s) extend outside longitude
246
- * range [-180, +180], the result may be reformatted for compatibility
247
- * with CARTO APIs.
248
- */
249
- function createPolygonSpatialFilter(spatialFilter) {
250
- return spatialFilter && _normalizeGeometry(spatialFilter) || undefined;
251
- }
252
- /**
253
- * Check if a viewport is large enough to represent a global coverage.
254
- * In this case the spatial filter parameter for widget calculation is removed.
255
- *
256
- * @internalRemarks Source: @carto/react-core
257
- */
258
- function _isGlobalViewport(viewport) {
259
- const [minx, miny, maxx, maxy] = viewport;
260
- return maxx - minx > 179.5 * 2 && maxy - miny > 85.05 * 2;
261
- }
262
- /**
263
- * Normalized a geometry, coming from a mask or a viewport. The parts
264
- * spanning outside longitude range [-180, +180] are clipped and "folded"
265
- * back to the valid range and unioned to the polygons inide that range.
266
- *
267
- * It results in a Polygon or MultiPolygon strictly inside the validity range.
268
- *
269
- * @internalRemarks Source: @carto/react-core
270
- */
271
- function _normalizeGeometry(geometry) {
272
- const WORLD = [-180, -90, +180, +90];
273
- const worldClip = _clean(bboxClip(geometry, WORLD).geometry);
274
- const geometryTxWest = _tx(geometry, 360);
275
- const geometryTxEast = _tx(geometry, -360);
276
- let result = worldClip;
277
- if (result && geometryTxWest) {
278
- const worldWestClip = _clean(bboxClip(geometryTxWest, WORLD).geometry);
279
- if (worldWestClip) {
280
- const collection = featureCollection([feature(result), feature(worldWestClip)]);
281
- const merged = union(collection);
282
- result = merged ? _clean(merged.geometry) : result;
283
- }
284
- }
285
- if (result && geometryTxEast) {
286
- const worldEastClip = _clean(bboxClip(geometryTxEast, WORLD).geometry);
287
- if (worldEastClip) {
288
- const collection = featureCollection([feature(result), feature(worldEastClip)]);
289
- const merged = union(collection);
290
- result = merged ? _clean(merged.geometry) : result;
291
- }
292
- }
293
- return result;
294
- }
295
- /** @internalRemarks Source: @carto/react-core */
296
- function _cleanPolygonCoords(cc) {
297
- const coords = cc.filter(c => c.length > 0);
298
- return coords.length > 0 ? coords : null;
299
- }
300
- /** @internalRemarks Source: @carto/react-core */
301
- function _cleanMultiPolygonCoords(ccc) {
302
- const coords = ccc.map(_cleanPolygonCoords).filter(cc => cc);
303
- return coords.length > 0 ? coords : null;
304
- }
305
- /** @internalRemarks Source: @carto/react-core */
306
- function _clean(geometry) {
307
- if (!geometry) {
308
- return null;
309
- }
310
- if (_isPolygon(geometry)) {
311
- const coords = _cleanPolygonCoords(geometry.coordinates);
312
- return coords ? polygon(coords).geometry : null;
313
- }
314
- if (_isMultiPolygon(geometry)) {
315
- const coords = _cleanMultiPolygonCoords(geometry.coordinates);
316
- return coords ? multiPolygon(coords).geometry : null;
317
- }
318
- return null;
319
- }
320
- /** @internalRemarks Source: @carto/react-core */
321
- function _txContourCoords(cc, distance) {
322
- return cc.map(c => [c[0] + distance, c[1]]);
323
- }
324
- /** @internalRemarks Source: @carto/react-core */
325
- function _txPolygonCoords(ccc, distance) {
326
- return ccc.map(cc => _txContourCoords(cc, distance));
327
- }
328
- /** @internalRemarks Source: @carto/react-core */
329
- function _txMultiPolygonCoords(cccc, distance) {
330
- return cccc.map(ccc => _txPolygonCoords(ccc, distance));
331
- }
332
- /** @internalRemarks Source: @carto/react-core */
333
- function _tx(geometry, distance) {
334
- if (geometry && getType(geometry) === 'Polygon') {
335
- const coords = _txPolygonCoords(geometry.coordinates, distance);
336
- return polygon(coords).geometry;
337
- } else if (geometry && getType(geometry) === 'MultiPolygon') {
338
- const coords = _txMultiPolygonCoords(geometry.coordinates, distance);
339
- return multiPolygon(coords).geometry;
340
- } else {
341
- return null;
342
- }
343
- }
344
- function _isPolygon(geometry) {
345
- return getType(geometry) === 'Polygon';
346
- }
347
- function _isMultiPolygon(geometry) {
348
- return getType(geometry) === 'MultiPolygon';
349
- }
350
-
351
- function _extends() {
352
- return _extends = Object.assign ? Object.assign.bind() : function (n) {
353
- for (var e = 1; e < arguments.length; e++) {
354
- var t = arguments[e];
355
- for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
356
- }
357
- return n;
358
- }, _extends.apply(null, arguments);
359
- }
360
- function _objectWithoutPropertiesLoose(r, e) {
361
- if (null == r) return {};
362
- var t = {};
363
- for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
364
- if (e.includes(n)) continue;
365
- t[n] = r[n];
366
- }
367
- return t;
368
- }
369
-
370
- /**
371
- * Current version of @carto/api-client.
372
- * @internal
373
- */
374
- /** @internal */
375
- const V3_MINOR_VERSION = '3.4';
376
- /** @internalRemarks Source: @carto/constants, @deck.gl/carto */
377
- const DEFAULT_GEO_COLUMN = 'geom';
378
- /**
379
- * Fastly default limit is 8192; leave some padding.
380
- * @internalRemarks Source: @deck.gl/carto
381
- */
382
- const DEFAULT_MAX_LENGTH_URL = 7000;
383
- /** @internalRemarks Source: @deck.gl/carto */
384
- const DEFAULT_TILE_RESOLUTION = 0.5;
385
- /**
386
- * @internalRemarks Source: @deck.gl/carto
387
- * @internal
388
- */
389
- const DEFAULT_AGGREGATION_RES_LEVEL_H3 = 4;
390
- /**
391
- * @internalRemarks Source: @deck.gl/carto
392
- * @internal
393
- */
394
- const DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN = 6;
395
-
396
- // deck.gl
397
- // SPDX-License-Identifier: MIT
398
- // Copyright (c) vis.gl contributors
399
- function joinPath(...args) {
400
- return args.map(part => part.endsWith('/') ? part.slice(0, -1) : part).join('/');
401
- }
402
- function buildV3Path(apiBaseUrl, version, endpoint, ...rest) {
403
- return joinPath(apiBaseUrl, version, endpoint, ...rest);
404
- }
405
- /** @internal Required by fetchMap(). */
406
- function buildPublicMapUrl({
407
- apiBaseUrl,
408
- cartoMapId
409
- }) {
410
- return buildV3Path(apiBaseUrl, 'v3', 'maps', 'public', cartoMapId);
411
- }
412
- /** @internal Required by fetchMap(). */
413
- function buildStatsUrl({
414
- attribute,
415
- apiBaseUrl,
416
- connectionName,
417
- source,
418
- type
419
- }) {
420
- if (type === 'query') {
421
- return buildV3Path(apiBaseUrl, 'v3', 'stats', connectionName, attribute);
422
- }
423
- // type === 'table'
424
- return buildV3Path(apiBaseUrl, 'v3', 'stats', connectionName, source, attribute);
425
- }
426
- function buildSourceUrl({
427
- apiBaseUrl,
428
- connectionName,
429
- endpoint
430
- }) {
431
- return buildV3Path(apiBaseUrl, 'v3', 'maps', connectionName, endpoint);
432
- }
433
- function buildQueryUrl({
434
- apiBaseUrl,
435
- connectionName
436
- }) {
437
- return buildV3Path(apiBaseUrl, 'v3', 'sql', connectionName, 'query');
438
- }
439
-
440
- // deck.gl
441
- // SPDX-License-Identifier: MIT
442
- // Copyright (c) vis.gl contributors
443
- /**
444
- *
445
- * Custom error for reported errors in CARTO Maps API.
446
- * Provides useful debugging information in console and context for applications.
447
- *
448
- */
449
- class CartoAPIError extends Error {
450
- constructor(error, errorContext, response, responseJson) {
451
- let responseString = 'Failed to connect';
452
- if (response) {
453
- responseString = 'Server returned: ';
454
- if (response.status === 400) {
455
- responseString += 'Bad request';
456
- } else if (response.status === 401 || response.status === 403) {
457
- responseString += 'Unauthorized access';
458
- } else if (response.status === 404) {
459
- responseString += 'Not found';
460
- } else {
461
- responseString += 'Error';
462
- }
463
- responseString += ` (${response.status}):`;
464
- }
465
- responseString += ` ${error.message || error}`;
466
- let message = `${errorContext.requestType} API request failed`;
467
- message += `\n${responseString}`;
468
- for (const key of Object.keys(errorContext)) {
469
- if (key === 'requestType') continue;
470
- message += `\n${formatErrorKey(key)}: ${errorContext[key]}`;
471
- }
472
- message += '\n';
473
- super(message);
474
- /** Source error from server */
475
- this.error = void 0;
476
- /** Context (API call & parameters) in which error occured */
477
- this.errorContext = void 0;
478
- /** Response from server */
479
- this.response = void 0;
480
- /** JSON Response from server */
481
- this.responseJson = void 0;
482
- this.name = 'CartoAPIError';
483
- this.response = response;
484
- this.responseJson = responseJson;
485
- this.error = error;
486
- this.errorContext = errorContext;
487
- }
488
- }
489
- /**
490
- * Converts camelCase to Camel Case
491
- */
492
- function formatErrorKey(key) {
493
- return key.replace(/([A-Z])/g, ' $1').replace(/^./, s => s.toUpperCase());
494
- }
495
-
496
- const DEFAULT_HEADERS = {
497
- Accept: 'application/json',
498
- 'Content-Type': 'application/json'
499
- };
500
- const DEFAULT_REQUEST_CACHE = new Map();
501
- async function requestWithParameters({
502
- baseUrl,
503
- parameters = {},
504
- headers: customHeaders = {},
505
- errorContext,
506
- maxLengthURL = DEFAULT_MAX_LENGTH_URL,
507
- localCache
508
- }) {
509
- // Parameters added to all requests issued with `requestWithParameters()`.
510
- // These parameters override parameters already in the base URL, but not
511
- // user-provided parameters.
512
- parameters = _extends({
513
- v: V3_MINOR_VERSION,
514
- client: getClient()
515
- }, typeof deck !== 'undefined' && deck.VERSION && {
516
- deckglVersion: deck.VERSION
517
- }, parameters);
518
- baseUrl = excludeURLParameters(baseUrl, Object.keys(parameters));
519
- const key = createCacheKey(baseUrl, parameters, customHeaders);
520
- const {
521
- cache: REQUEST_CACHE,
522
- canReadCache,
523
- canStoreInCache
524
- } = getCacheSettings(localCache);
525
- if (canReadCache && REQUEST_CACHE.has(key)) {
526
- return REQUEST_CACHE.get(key);
527
- }
528
- const url = createURLWithParameters(baseUrl, parameters);
529
- const headers = _extends({}, DEFAULT_HEADERS, customHeaders);
530
- /* global fetch */
531
- const fetchPromise = url.length > maxLengthURL ? fetch(baseUrl, {
532
- method: 'POST',
533
- body: JSON.stringify(parameters),
534
- headers
535
- }) : fetch(url, {
536
- headers
537
- });
538
- let response;
539
- let responseJson;
540
- const jsonPromise = fetchPromise.then(_response => {
541
- response = _response;
542
- return response.json();
543
- }).then(json => {
544
- responseJson = json;
545
- if (!response || !response.ok) {
546
- throw new Error(json.error);
547
- }
548
- return json;
549
- }).catch(error => {
550
- if (canStoreInCache) {
551
- REQUEST_CACHE.delete(key);
552
- }
553
- throw new CartoAPIError(error, errorContext, response, responseJson);
554
- });
555
- if (canStoreInCache) {
556
- REQUEST_CACHE.set(key, jsonPromise);
557
- }
558
- return jsonPromise;
559
- }
560
- function getCacheSettings(localCache) {
561
- var _localCache$cacheCont, _localCache$cacheCont2;
562
- const canReadCache = localCache != null && (_localCache$cacheCont = localCache.cacheControl) != null && _localCache$cacheCont.includes('no-cache') ? false : true;
563
- const canStoreInCache = localCache != null && (_localCache$cacheCont2 = localCache.cacheControl) != null && _localCache$cacheCont2.includes('no-store') ? false : true;
564
- const cache = (localCache == null ? void 0 : localCache.cache) || DEFAULT_REQUEST_CACHE;
565
- return {
566
- cache,
567
- canReadCache,
568
- canStoreInCache
569
- };
570
- }
571
- function createCacheKey(baseUrl, parameters, headers) {
572
- const parameterEntries = Object.entries(parameters).sort(([a], [b]) => a > b ? 1 : -1);
573
- const headerEntries = Object.entries(headers).sort(([a], [b]) => a > b ? 1 : -1);
574
- return JSON.stringify({
575
- baseUrl,
576
- parameters: parameterEntries,
577
- headers: headerEntries
578
- });
579
- }
580
- /**
581
- * Appends query string parameters to a URL. Existing URL parameters are kept,
582
- * unless there is a conflict, in which case the new parameters override
583
- * those already in the URL.
584
- */
585
- function createURLWithParameters(baseUrlString, parameters) {
586
- const baseUrl = new URL(baseUrlString);
587
- for (const [key, value] of Object.entries(parameters)) {
588
- if (isPureObject(value) || Array.isArray(value)) {
589
- baseUrl.searchParams.set(key, JSON.stringify(value));
590
- } else {
591
- baseUrl.searchParams.set(key, value.toString());
592
- }
593
- }
594
- return baseUrl.toString();
595
- }
596
- /**
597
- * Deletes query string parameters from a URL.
598
- */
599
- function excludeURLParameters(baseUrlString, parameters) {
600
- const baseUrl = new URL(baseUrlString);
601
- for (const param of parameters) {
602
- if (baseUrl.searchParams.has(param)) {
603
- baseUrl.searchParams.delete(param);
604
- }
605
- }
606
- return baseUrl.toString();
607
- }
608
-
609
- const _excluded$1 = ["accessToken", "connectionName", "cache"];
610
- const SOURCE_DEFAULTS = {
611
- apiBaseUrl: DEFAULT_API_BASE_URL,
612
- clientId: getClient(),
613
- format: 'tilejson',
614
- headers: {},
615
- maxLengthURL: DEFAULT_MAX_LENGTH_URL
616
- };
617
- async function baseSource(endpoint, options, urlParameters) {
618
- const {
619
- accessToken,
620
- connectionName,
621
- cache
622
- } = options,
623
- optionalOptions = _objectWithoutPropertiesLoose(options, _excluded$1);
624
- const mergedOptions = _extends({}, SOURCE_DEFAULTS, {
625
- accessToken,
626
- connectionName,
627
- endpoint
628
- });
629
- for (const key in optionalOptions) {
630
- if (optionalOptions[key]) {
631
- mergedOptions[key] = optionalOptions[key];
632
- }
633
- }
634
- const baseUrl = buildSourceUrl(mergedOptions);
635
- const {
636
- clientId,
637
- maxLengthURL,
638
- format,
639
- localCache
640
- } = mergedOptions;
641
- const headers = _extends({
642
- Authorization: `Bearer ${options.accessToken}`
643
- }, options.headers);
644
- const parameters = _extends({
645
- client: clientId
646
- }, urlParameters);
647
- const errorContext = {
648
- requestType: 'Map instantiation',
649
- connection: options.connectionName,
650
- type: endpoint,
651
- source: JSON.stringify(parameters, undefined, 2)
652
- };
653
- const mapInstantiation = await requestWithParameters({
654
- baseUrl,
655
- parameters,
656
- headers,
657
- errorContext,
658
- maxLengthURL,
659
- localCache
660
- });
661
- const dataUrl = mapInstantiation[format].url[0];
662
- if (cache) {
663
- cache.value = parseInt(new URL(dataUrl).searchParams.get('cache') || '', 10);
664
- }
665
- errorContext.requestType = 'Map data';
666
- if (format === 'tilejson') {
667
- const json = await requestWithParameters({
668
- baseUrl: dataUrl,
669
- headers,
670
- errorContext,
671
- maxLengthURL,
672
- localCache
673
- });
674
- if (accessToken) {
675
- json.accessToken = accessToken;
676
- }
677
- return json;
678
- }
679
- return await requestWithParameters({
680
- baseUrl: dataUrl,
681
- headers,
682
- errorContext,
683
- maxLengthURL,
684
- localCache
685
- });
686
- }
687
-
688
- // deck.gl
689
- // SPDX-License-Identifier: MIT
690
- // Copyright (c) vis.gl contributors
691
- const boundaryQuerySource = async function boundaryQuerySource(options) {
692
- const {
693
- columns,
694
- filters,
695
- tilesetTableName,
696
- propertiesSqlQuery,
697
- queryParameters
698
- } = options;
699
- const urlParameters = {
700
- tilesetTableName,
701
- propertiesSqlQuery
702
- };
703
- if (columns) {
704
- urlParameters.columns = columns.join(',');
705
- }
706
- if (filters) {
707
- urlParameters.filters = filters;
708
- }
709
- if (queryParameters) {
710
- urlParameters.queryParameters = queryParameters;
711
- }
712
- return baseSource('boundary', options, urlParameters);
713
- };
714
-
715
- // deck.gl
716
- // SPDX-License-Identifier: MIT
717
- // Copyright (c) vis.gl contributors
718
- const boundaryTableSource = async function boundaryTableSource(options) {
719
- const {
720
- filters,
721
- tilesetTableName,
722
- columns,
723
- propertiesTableName
724
- } = options;
725
- const urlParameters = {
726
- tilesetTableName,
727
- propertiesTableName
728
- };
729
- if (columns) {
730
- urlParameters.columns = columns.join(',');
731
- }
732
- if (filters) {
733
- urlParameters.filters = filters;
734
- }
735
- return baseSource('boundary', options, urlParameters);
736
- };
737
-
738
- /**
739
- * Return more descriptive error from API
740
- * @internalRemarks Source: @carto/react-api
741
- */
742
- function dealWithApiError({
743
- response,
744
- data
745
- }) {
746
- var _data$error, _data$error2;
747
- if (data.error === 'Column not found') {
748
- throw new InvalidColumnError(`${data.error} ${data.column_name}`);
749
- }
750
- if (typeof data.error === 'string' && (_data$error = data.error) != null && _data$error.includes('Missing columns')) {
751
- throw new InvalidColumnError(data.error);
752
- }
753
- switch (response.status) {
754
- case 401:
755
- throw new Error('Unauthorized access. Invalid credentials');
756
- case 403:
757
- throw new Error('Forbidden access to the requested data');
758
- default:
759
- const msg = data && data.error && typeof data.error === 'string' ? data.error : JSON.stringify((data == null ? void 0 : data.hint) || ((_data$error2 = data.error) == null ? void 0 : _data$error2[0]));
760
- throw new Error(msg);
761
- }
762
- }
763
- /** @internalRemarks Source: @carto/react-api */
764
- async function makeCall({
765
- url,
766
- accessToken,
767
- opts
768
- }) {
769
- let response;
770
- let data;
771
- const isPost = (opts == null ? void 0 : opts.method) === 'POST';
772
- try {
773
- var _opts$abortController;
774
- response = await fetch(url.toString(), _extends({
775
- headers: _extends({
776
- Authorization: `Bearer ${accessToken}`
777
- }, isPost && {
778
- 'Content-Type': 'application/json'
779
- })
780
- }, isPost && {
781
- method: opts == null ? void 0 : opts.method,
782
- body: opts == null ? void 0 : opts.body
783
- }, {
784
- signal: opts == null || (_opts$abortController = opts.abortController) == null ? void 0 : _opts$abortController.signal
785
- }, opts == null ? void 0 : opts.otherOptions));
786
- data = await response.json();
787
- } catch (error) {
788
- if (error.name === 'AbortError') throw error;
789
- throw new Error(`Failed request: ${error}`);
790
- }
791
- if (!response.ok) {
792
- dealWithApiError({
793
- response,
794
- data
795
- });
796
- }
797
- return data;
798
- }
799
-
800
- /** @internalRemarks Source: @carto/react-api */
801
- const AVAILABLE_MODELS = ['category', 'histogram', 'formula', 'pick', 'timeseries', 'range', 'scatterplot', 'table'];
802
- const {
803
- V3
804
- } = ApiVersion;
805
- const REQUEST_GET_MAX_URL_LENGTH = 2048;
806
- /**
807
- * Execute a SQL model request.
808
- * @internalRemarks Source: @carto/react-api
809
- */
810
- function executeModel(props) {
811
- assert(props.source, 'executeModel: missing source');
812
- assert(props.model, 'executeModel: missing model');
813
- assert(props.params, 'executeModel: missing params');
814
- assert(AVAILABLE_MODELS.includes(props.model), `executeModel: model provided isn't valid. Available models: ${AVAILABLE_MODELS.join(', ')}`);
815
- const {
816
- model,
817
- source,
818
- params,
819
- opts
820
- } = props;
821
- const {
822
- type,
823
- apiVersion,
824
- apiBaseUrl,
825
- accessToken,
826
- connectionName,
827
- clientId
828
- } = source;
829
- assert(apiBaseUrl, 'executeModel: missing apiBaseUrl');
830
- assert(accessToken, 'executeModel: missing accessToken');
831
- assert(apiVersion === V3, 'executeModel: SQL Model API requires CARTO 3+');
832
- assert(type !== 'tileset', 'executeModel: Tilesets not supported');
833
- let url = `${apiBaseUrl}/v3/sql/${connectionName}/model/${model}`;
834
- const {
835
- data,
836
- filters,
837
- filtersLogicalOperator = 'and',
838
- spatialDataType = 'geo',
839
- spatialFiltersMode = 'intersects',
840
- spatialFiltersResolution = 0
841
- } = source;
842
- const queryParams = {
843
- type,
844
- client: clientId,
845
- source: data,
846
- params,
847
- queryParameters: source.queryParameters || '',
848
- filters,
849
- filtersLogicalOperator
850
- };
851
- const spatialDataColumn = source.spatialDataColumn || DEFAULT_GEO_COLUMN;
852
- // Picking Model API requires 'spatialDataColumn'.
853
- if (model === 'pick') {
854
- queryParams.spatialDataColumn = spatialDataColumn;
855
- }
856
- // API supports multiple filters, we apply it only to spatialDataColumn
857
- const spatialFilters = source.spatialFilter ? {
858
- [spatialDataColumn]: source.spatialFilter
859
- } : undefined;
860
- if (spatialFilters) {
861
- queryParams.spatialFilters = spatialFilters;
862
- queryParams.spatialDataColumn = spatialDataColumn;
863
- queryParams.spatialDataType = spatialDataType;
864
- }
865
- if (spatialDataType !== 'geo') {
866
- if (spatialFiltersResolution > 0) {
867
- queryParams.spatialFiltersResolution = spatialFiltersResolution;
868
- }
869
- queryParams.spatialFiltersMode = spatialFiltersMode;
870
- }
871
- const urlWithSearchParams = url + '?' + objectToURLSearchParams(queryParams).toString();
872
- const isGet = urlWithSearchParams.length <= REQUEST_GET_MAX_URL_LENGTH;
873
- if (isGet) {
874
- url = urlWithSearchParams;
875
- }
876
- return makeCall({
877
- url,
878
- accessToken: source.accessToken,
879
- opts: _extends({}, opts, {
880
- method: isGet ? 'GET' : 'POST'
881
- }, !isGet && {
882
- body: JSON.stringify(queryParams)
883
- })
884
- });
885
- }
886
- function objectToURLSearchParams(object) {
887
- const params = new URLSearchParams();
888
- for (const key in object) {
889
- if (isPureObject(object[key])) {
890
- params.append(key, JSON.stringify(object[key]));
891
- } else if (Array.isArray(object[key])) {
892
- params.append(key, JSON.stringify(object[key]));
893
- } else if (object[key] === null) {
894
- params.append(key, 'null');
895
- } else if (object[key] !== undefined) {
896
- params.append(key, String(object[key]));
897
- }
898
- }
899
- return params;
900
- }
901
-
902
- const DEFAULT_TILE_SIZE = 512;
903
- const QUADBIN_ZOOM_MAX_OFFSET = 4;
904
- function getSpatialFiltersResolution(source, viewState) {
905
- var _source$dataResolutio, _source$aggregationRe;
906
- const dataResolution = (_source$dataResolutio = source.dataResolution) != null ? _source$dataResolutio : Number.MAX_VALUE;
907
- const aggregationResLevel = (_source$aggregationRe = source.aggregationResLevel) != null ? _source$aggregationRe : source.spatialDataType === 'h3' ? DEFAULT_AGGREGATION_RES_LEVEL_H3 : DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN;
908
- const aggregationResLevelOffset = Math.max(0, Math.floor(aggregationResLevel));
909
- const currentZoomInt = Math.ceil(viewState.zoom);
910
- if (source.spatialDataType === 'h3') {
911
- var _maxH3SpatialFiltersR, _maxH3SpatialFiltersR2;
912
- const tileSize = DEFAULT_TILE_SIZE;
913
- const maxResolutionForZoom = (_maxH3SpatialFiltersR = (_maxH3SpatialFiltersR2 = maxH3SpatialFiltersResolutions.find(([zoom]) => zoom === currentZoomInt)) == null ? void 0 : _maxH3SpatialFiltersR2[1]) != null ? _maxH3SpatialFiltersR : Math.max(0, currentZoomInt - 3);
914
- const maxSpatialFiltersResolution = maxResolutionForZoom ? Math.min(dataResolution, maxResolutionForZoom) : dataResolution;
915
- const hexagonResolution = _getHexagonResolution(viewState, tileSize) + aggregationResLevelOffset;
916
- return Math.min(hexagonResolution, maxSpatialFiltersResolution);
917
- }
918
- if (source.spatialDataType === 'quadbin') {
919
- const maxResolutionForZoom = currentZoomInt + QUADBIN_ZOOM_MAX_OFFSET;
920
- const maxSpatialFiltersResolution = Math.min(dataResolution, maxResolutionForZoom);
921
- const quadsResolution = Math.floor(viewState.zoom) + aggregationResLevelOffset;
922
- return Math.min(quadsResolution, maxSpatialFiltersResolution);
923
- }
924
- return undefined;
925
- }
926
- const maxH3SpatialFiltersResolutions = [[20, 14], [19, 13], [18, 12], [17, 11], [16, 10], [15, 9], [14, 8], [13, 7], [12, 7], [11, 7], [10, 6], [9, 6], [8, 5], [7, 4], [6, 4], [5, 3], [4, 2], [3, 1], [2, 1], [1, 0]];
927
- // stolen from https://github.com/visgl/deck.gl/blob/master/modules/carto/src/layers/h3-tileset-2d.ts
928
- // Relative scale factor (0 = no biasing, 2 = a few hexagons cover view)
929
- const BIAS = 2;
930
- /**
931
- * Resolution conversion function. Takes a WebMercatorViewport and returns
932
- * a H3 resolution such that the screen space size of the hexagons is
933
- * "similar" to the given tileSize on screen. Intended for use with deck.gl.
934
- * @internal
935
- */
936
- function _getHexagonResolution(viewport, tileSize) {
937
- // Difference in given tile size compared to deck's internal 512px tile size,
938
- // expressed as an offset to the viewport zoom.
939
- const zoomOffset = Math.log2(tileSize / DEFAULT_TILE_SIZE);
940
- const hexagonScaleFactor = 2 / 3 * (viewport.zoom - zoomOffset);
941
- const latitudeScaleFactor = Math.log(1 / Math.cos(Math.PI * viewport.latitude / 180));
942
- // Clip and bias
943
- return Math.max(0, Math.floor(hexagonScaleFactor + latitudeScaleFactor - BIAS));
944
- }
945
-
946
- const _excluded = ["filterOwner", "spatialFilter", "spatialFiltersMode", "spatialIndexReferenceViewState", "abortController"],
947
- _excluded2 = ["filterOwner", "spatialFilter", "spatialFiltersMode", "spatialIndexReferenceViewState", "abortController"],
948
- _excluded3 = ["filterOwner", "spatialFilter", "spatialFiltersMode", "spatialIndexReferenceViewState", "abortController", "operationExp"],
949
- _excluded4 = ["filterOwner", "spatialFilter", "spatialFiltersMode", "spatialIndexReferenceViewState", "abortController"],
950
- _excluded5 = ["filterOwner", "spatialFilter", "spatialFiltersMode", "spatialIndexReferenceViewState", "abortController"],
951
- _excluded6 = ["filterOwner", "spatialFilter", "spatialFiltersMode", "spatialIndexReferenceViewState", "abortController"],
952
- _excluded7 = ["filterOwner", "spatialFilter", "spatialFiltersMode", "spatialIndexReferenceViewState", "abortController"],
953
- _excluded8 = ["filterOwner", "abortController", "spatialFilter", "spatialFiltersMode", "spatialIndexReferenceViewState"];
954
- /**
955
- * Source for Widget API requests on a data source defined by a SQL query.
956
- *
957
- * Abstract class. Use {@link WidgetQuerySource} or {@link WidgetTableSource}.
958
- */
959
- class WidgetBaseSource {
960
- constructor(props) {
961
- this.props = void 0;
962
- this.props = _extends({}, WidgetBaseSource.defaultProps, props);
963
- }
964
- _getModelSource(owner) {
965
- const props = this.props;
966
- return {
967
- apiVersion: props.apiVersion,
968
- apiBaseUrl: props.apiBaseUrl,
969
- clientId: props.clientId,
970
- accessToken: props.accessToken,
971
- connectionName: props.connectionName,
972
- filters: getApplicableFilters(owner, props.filters),
973
- filtersLogicalOperator: props.filtersLogicalOperator,
974
- spatialDataType: props.spatialDataType,
975
- spatialDataColumn: props.spatialDataColumn,
976
- dataResolution: props.dataResolution
977
- };
978
- }
979
- _getSpatialFiltersResolution(source, spatialFilter, referenceViewState) {
980
- // spatialFiltersResolution applies only to spatial index sources.
981
- if (!spatialFilter || source.spatialDataType === 'geo') {
982
- return;
983
- }
984
- if (!referenceViewState) {
985
- throw new Error('Missing required option, "spatialIndexReferenceViewState".');
986
- }
987
- return getSpatialFiltersResolution(source, referenceViewState);
988
- }
989
- /****************************************************************************
990
- * CATEGORIES
991
- */
992
- /**
993
- * Returns a list of labeled datapoints for categorical data. Suitable for
994
- * charts including grouped bar charts, pie charts, and tree charts.
995
- */
996
- async getCategories(options) {
997
- const {
998
- filterOwner,
999
- spatialFilter,
1000
- spatialFiltersMode,
1001
- spatialIndexReferenceViewState,
1002
- abortController
1003
- } = options,
1004
- params = _objectWithoutPropertiesLoose(options, _excluded);
1005
- const {
1006
- column,
1007
- operation,
1008
- operationColumn
1009
- } = params;
1010
- const source = this.getModelSource(filterOwner);
1011
- const spatialFiltersResolution = this._getSpatialFiltersResolution(source, spatialFilter, spatialIndexReferenceViewState);
1012
- return executeModel({
1013
- model: 'category',
1014
- source: _extends({}, source, {
1015
- spatialFiltersResolution,
1016
- spatialFiltersMode,
1017
- spatialFilter
1018
- }),
1019
- params: {
1020
- column,
1021
- operation,
1022
- operationColumn: operationColumn || column
1023
- },
1024
- opts: {
1025
- abortController
1026
- }
1027
- }).then(res => normalizeObjectKeys(res.rows));
1028
- }
1029
- /****************************************************************************
1030
- * FEATURES
1031
- */
1032
- /**
1033
- * Given a list of feature IDs (as found in `_carto_feature_id`) returns all
1034
- * matching features. In datasets containing features with duplicate geometries,
1035
- * feature IDs may be duplicated (IDs are a hash of geometry) and so more
1036
- * results may be returned than IDs in the request.
1037
- * @internal
1038
- * @experimental
1039
- */
1040
- async getFeatures(options) {
1041
- const {
1042
- filterOwner,
1043
- spatialFilter,
1044
- spatialFiltersMode,
1045
- spatialIndexReferenceViewState,
1046
- abortController
1047
- } = options,
1048
- params = _objectWithoutPropertiesLoose(options, _excluded2);
1049
- const {
1050
- columns,
1051
- dataType,
1052
- featureIds,
1053
- z,
1054
- limit,
1055
- tileResolution
1056
- } = params;
1057
- const source = this.getModelSource(filterOwner);
1058
- const spatialFiltersResolution = this._getSpatialFiltersResolution(source, spatialFilter, spatialIndexReferenceViewState);
1059
- return executeModel({
1060
- model: 'pick',
1061
- source: _extends({}, source, {
1062
- spatialFiltersResolution,
1063
- spatialFiltersMode,
1064
- spatialFilter
1065
- }),
1066
- params: {
1067
- columns,
1068
- dataType,
1069
- featureIds,
1070
- z,
1071
- limit: limit || 1000,
1072
- tileResolution: tileResolution || DEFAULT_TILE_RESOLUTION
1073
- },
1074
- opts: {
1075
- abortController
1076
- }
1077
- // Avoid `normalizeObjectKeys()`, which changes column names.
1078
- }).then(({
1079
- rows
1080
- }) => ({
1081
- rows
1082
- }));
1083
- }
1084
- /****************************************************************************
1085
- * FORMULA
1086
- */
1087
- /**
1088
- * Returns a scalar numerical statistic over all matching data. Suitable
1089
- * for 'headline' or 'scorecard' figures such as counts and sums.
1090
- */
1091
- async getFormula(options) {
1092
- const {
1093
- filterOwner,
1094
- spatialFilter,
1095
- spatialFiltersMode,
1096
- spatialIndexReferenceViewState,
1097
- abortController,
1098
- operationExp
1099
- } = options,
1100
- params = _objectWithoutPropertiesLoose(options, _excluded3);
1101
- const {
1102
- column,
1103
- operation
1104
- } = params;
1105
- const source = this.getModelSource(filterOwner);
1106
- const spatialFiltersResolution = this._getSpatialFiltersResolution(source, spatialFilter, spatialIndexReferenceViewState);
1107
- return executeModel({
1108
- model: 'formula',
1109
- source: _extends({}, source, {
1110
- spatialFiltersResolution,
1111
- spatialFiltersMode,
1112
- spatialFilter
1113
- }),
1114
- params: {
1115
- column: column != null ? column : '*',
1116
- operation,
1117
- operationExp
1118
- },
1119
- opts: {
1120
- abortController
1121
- }
1122
- }).then(res => normalizeObjectKeys(res.rows[0]));
1123
- }
1124
- /****************************************************************************
1125
- * HISTOGRAM
1126
- */
1127
- /**
1128
- * Returns a list of labeled datapoints for 'bins' of data defined as ticks
1129
- * over a numerical range. Suitable for histogram charts.
1130
- */
1131
- async getHistogram(options) {
1132
- const {
1133
- filterOwner,
1134
- spatialFilter,
1135
- spatialFiltersMode,
1136
- spatialIndexReferenceViewState,
1137
- abortController
1138
- } = options,
1139
- params = _objectWithoutPropertiesLoose(options, _excluded4);
1140
- const {
1141
- column,
1142
- operation,
1143
- ticks
1144
- } = params;
1145
- const source = this.getModelSource(filterOwner);
1146
- const spatialFiltersResolution = this._getSpatialFiltersResolution(source, spatialFilter, spatialIndexReferenceViewState);
1147
- const data = await executeModel({
1148
- model: 'histogram',
1149
- source: _extends({}, source, {
1150
- spatialFiltersResolution,
1151
- spatialFiltersMode,
1152
- spatialFilter
1153
- }),
1154
- params: {
1155
- column,
1156
- operation,
1157
- ticks
1158
- },
1159
- opts: {
1160
- abortController
1161
- }
1162
- }).then(res => normalizeObjectKeys(res.rows));
1163
- if (data.length) {
1164
- // Given N ticks the API returns up to N+1 bins, omitting any empty bins. Bins
1165
- // include 1 bin below the lowest tick, N-1 between ticks, and 1 bin above the highest tick.
1166
- const result = Array(ticks.length + 1).fill(0);
1167
- data.forEach(({
1168
- tick,
1169
- value
1170
- }) => result[tick] = value);
1171
- return result;
1172
- }
1173
- return [];
1174
- }
1175
- /****************************************************************************
1176
- * RANGE
1177
- */
1178
- /**
1179
- * Returns a range (min and max) for a numerical column of matching rows.
1180
- * Suitable for displaying certain 'headline' or 'scorecard' statistics,
1181
- * or rendering a range slider UI for filtering.
1182
- */
1183
- async getRange(options) {
1184
- const {
1185
- filterOwner,
1186
- spatialFilter,
1187
- spatialFiltersMode,
1188
- spatialIndexReferenceViewState,
1189
- abortController
1190
- } = options,
1191
- params = _objectWithoutPropertiesLoose(options, _excluded5);
1192
- const {
1193
- column
1194
- } = params;
1195
- const source = this.getModelSource(filterOwner);
1196
- const spatialFiltersResolution = this._getSpatialFiltersResolution(source, spatialFilter, spatialIndexReferenceViewState);
1197
- return executeModel({
1198
- model: 'range',
1199
- source: _extends({}, source, {
1200
- spatialFiltersResolution,
1201
- spatialFiltersMode,
1202
- spatialFilter
1203
- }),
1204
- params: {
1205
- column
1206
- },
1207
- opts: {
1208
- abortController
1209
- }
1210
- }).then(res => normalizeObjectKeys(res.rows[0]));
1211
- }
1212
- /****************************************************************************
1213
- * SCATTER
1214
- */
1215
- /**
1216
- * Returns a list of bivariate datapoints defined as numerical 'x' and 'y'
1217
- * values. Suitable for rendering scatter plots.
1218
- */
1219
- async getScatter(options) {
1220
- const {
1221
- filterOwner,
1222
- spatialFilter,
1223
- spatialFiltersMode,
1224
- spatialIndexReferenceViewState,
1225
- abortController
1226
- } = options,
1227
- params = _objectWithoutPropertiesLoose(options, _excluded6);
1228
- const {
1229
- xAxisColumn,
1230
- xAxisJoinOperation,
1231
- yAxisColumn,
1232
- yAxisJoinOperation
1233
- } = params;
1234
- const source = this.getModelSource(filterOwner);
1235
- const spatialFiltersResolution = this._getSpatialFiltersResolution(source, spatialFilter, spatialIndexReferenceViewState);
1236
- // Make sure this is sync with the same constant in cloud-native/maps-api
1237
- const HARD_LIMIT = 500;
1238
- return executeModel({
1239
- model: 'scatterplot',
1240
- source: _extends({}, source, {
1241
- spatialFiltersResolution,
1242
- spatialFiltersMode,
1243
- spatialFilter
1244
- }),
1245
- params: {
1246
- xAxisColumn,
1247
- xAxisJoinOperation,
1248
- yAxisColumn,
1249
- yAxisJoinOperation,
1250
- limit: HARD_LIMIT
1251
- },
1252
- opts: {
1253
- abortController
1254
- }
1255
- }).then(res => normalizeObjectKeys(res.rows)).then(res => res.map(({
1256
- x,
1257
- y
1258
- }) => [x, y]));
1259
- }
1260
- /****************************************************************************
1261
- * TABLE
1262
- */
1263
- /**
1264
- * Returns a list of arbitrary data rows, with support for pagination and
1265
- * sorting. Suitable for displaying tables and lists.
1266
- */
1267
- async getTable(options) {
1268
- const {
1269
- filterOwner,
1270
- spatialFilter,
1271
- spatialFiltersMode,
1272
- spatialIndexReferenceViewState,
1273
- abortController
1274
- } = options,
1275
- params = _objectWithoutPropertiesLoose(options, _excluded7);
1276
- const {
1277
- columns,
1278
- sortBy,
1279
- sortDirection,
1280
- offset = 0,
1281
- limit = 10
1282
- } = params;
1283
- const source = this.getModelSource(filterOwner);
1284
- const spatialFiltersResolution = this._getSpatialFiltersResolution(source, spatialFilter, spatialIndexReferenceViewState);
1285
- return executeModel({
1286
- model: 'table',
1287
- source: _extends({}, source, {
1288
- spatialFiltersResolution,
1289
- spatialFiltersMode,
1290
- spatialFilter
1291
- }),
1292
- params: {
1293
- column: columns,
1294
- sortBy,
1295
- sortDirection,
1296
- limit,
1297
- offset
1298
- },
1299
- opts: {
1300
- abortController
1301
- }
1302
- }).then(res => {
1303
- var _res$rows, _res$metadata$total, _res$metadata, _res$METADATA;
1304
- return {
1305
- // Avoid `normalizeObjectKeys()`, which changes column names.
1306
- rows: (_res$rows = res.rows) != null ? _res$rows : res.ROWS,
1307
- totalCount: (_res$metadata$total = (_res$metadata = res.metadata) == null ? void 0 : _res$metadata.total) != null ? _res$metadata$total : (_res$METADATA = res.METADATA) == null ? void 0 : _res$METADATA.TOTAL
1308
- };
1309
- });
1310
- }
1311
- /****************************************************************************
1312
- * TIME SERIES
1313
- */
1314
- /**
1315
- * Returns a series of labeled numerical values, grouped into equally-sized
1316
- * time intervals. Suitable for rendering time series charts.
1317
- */
1318
- async getTimeSeries(options) {
1319
- const {
1320
- filterOwner,
1321
- abortController,
1322
- spatialFilter,
1323
- spatialFiltersMode,
1324
- spatialIndexReferenceViewState
1325
- } = options,
1326
- params = _objectWithoutPropertiesLoose(options, _excluded8);
1327
- const {
1328
- column,
1329
- operationColumn,
1330
- joinOperation,
1331
- operation,
1332
- stepSize,
1333
- stepMultiplier,
1334
- splitByCategory,
1335
- splitByCategoryLimit,
1336
- splitByCategoryValues
1337
- } = params;
1338
- const source = this.getModelSource(filterOwner);
1339
- const spatialFiltersResolution = this._getSpatialFiltersResolution(source, spatialFilter, spatialIndexReferenceViewState);
1340
- return executeModel({
1341
- model: 'timeseries',
1342
- source: _extends({}, source, {
1343
- spatialFiltersResolution,
1344
- spatialFiltersMode,
1345
- spatialFilter
1346
- }),
1347
- params: {
1348
- column,
1349
- stepSize,
1350
- stepMultiplier,
1351
- operationColumn: operationColumn || column,
1352
- joinOperation,
1353
- operation,
1354
- splitByCategory,
1355
- splitByCategoryLimit,
1356
- splitByCategoryValues
1357
- },
1358
- opts: {
1359
- abortController
1360
- }
1361
- }).then(res => {
1362
- var _res$metadata2;
1363
- return {
1364
- rows: normalizeObjectKeys(res.rows),
1365
- categories: (_res$metadata2 = res.metadata) == null ? void 0 : _res$metadata2.categories
1366
- };
1367
- });
1368
- }
1369
- }
1370
- WidgetBaseSource.defaultProps = {
1371
- apiVersion: ApiVersion.V3,
1372
- apiBaseUrl: DEFAULT_API_BASE_URL,
1373
- clientId: getClient(),
1374
- filters: {},
1375
- filtersLogicalOperator: 'and'
1376
- };
1377
-
1378
- /**
1379
- * Source for Widget API requests on a data source defined by a SQL query.
1380
- *
1381
- * Generally not intended to be constructed directly. Instead, call
1382
- * {@link vectorQuerySource}, {@link h3QuerySource}, or {@link quadbinQuerySource},
1383
- * which can be shared with map layers. Sources contain a `widgetSource` property,
1384
- * for use by widget implementations.
1385
- *
1386
- * Example:
1387
- *
1388
- * ```javascript
1389
- * import { vectorQuerySource } from '@carto/api-client';
1390
- *
1391
- * const data = vectorQuerySource({
1392
- * accessToken: '••••',
1393
- * connectionName: 'carto_dw',
1394
- * sqlQuery: 'SELECT * FROM carto-demo-data.demo_tables.retail_stores'
1395
- * });
1396
- *
1397
- * const { widgetSource } = await data;
1398
- * ```
1399
- */
1400
- class WidgetQuerySource extends WidgetBaseSource {
1401
- getModelSource(owner) {
1402
- return _extends({}, super._getModelSource(owner), {
1403
- type: 'query',
1404
- data: this.props.sqlQuery,
1405
- queryParameters: this.props.queryParameters
1406
- });
1407
- }
1408
- }
1409
-
1410
- /**
1411
- * Source for Widget API requests on a data source defined as a table.
1412
- *
1413
- * Generally not intended to be constructed directly. Instead, call
1414
- * {@link vectorTableSource}, {@link h3TableSource}, or {@link quadbinTableSource},
1415
- * which can be shared with map layers. Sources contain a `widgetSource` property,
1416
- * for use by widget implementations.
1417
- *
1418
- * Example:
1419
- *
1420
- * ```javascript
1421
- * import { vectorTableSource } from '@carto/api-client';
1422
- *
1423
- * const data = vectorTableSource({
1424
- * accessToken: '••••',
1425
- * connectionName: 'carto_dw',
1426
- * tableName: 'carto-demo-data.demo_tables.retail_stores'
1427
- * });
1428
- *
1429
- * const { widgetSource } = await data;
1430
- * ```
1431
- */
1432
- class WidgetTableSource extends WidgetBaseSource {
1433
- getModelSource(owner) {
1434
- return _extends({}, super._getModelSource(owner), {
1435
- type: 'table',
1436
- data: this.props.tableName
1437
- });
1438
- }
1439
- }
1440
-
1441
- const h3QuerySource = async function h3QuerySource(options) {
1442
- const {
1443
- aggregationExp,
1444
- aggregationResLevel = DEFAULT_AGGREGATION_RES_LEVEL_H3,
1445
- sqlQuery,
1446
- spatialDataColumn = 'h3',
1447
- queryParameters,
1448
- filters
1449
- } = options;
1450
- const spatialDataType = 'h3';
1451
- const urlParameters = {
1452
- aggregationExp,
1453
- spatialDataColumn,
1454
- spatialDataType,
1455
- q: sqlQuery
1456
- };
1457
- if (aggregationResLevel) {
1458
- urlParameters.aggregationResLevel = String(aggregationResLevel);
1459
- }
1460
- if (queryParameters) {
1461
- urlParameters.queryParameters = queryParameters;
1462
- }
1463
- if (filters) {
1464
- urlParameters.filters = filters;
1465
- }
1466
- return baseSource('query', options, urlParameters).then(result => _extends({}, result, {
1467
- widgetSource: new WidgetQuerySource(_extends({}, options, {
1468
- // NOTE: Parameters with default values above must be explicitly passed here.
1469
- spatialDataColumn,
1470
- spatialDataType
1471
- }))
1472
- }));
1473
- };
1474
-
1475
- const h3TableSource = async function h3TableSource(options) {
1476
- const {
1477
- aggregationExp,
1478
- aggregationResLevel = DEFAULT_AGGREGATION_RES_LEVEL_H3,
1479
- spatialDataColumn = 'h3',
1480
- tableName,
1481
- filters
1482
- } = options;
1483
- const spatialDataType = 'h3';
1484
- const urlParameters = {
1485
- aggregationExp,
1486
- name: tableName,
1487
- spatialDataColumn,
1488
- spatialDataType
1489
- };
1490
- if (aggregationResLevel) {
1491
- urlParameters.aggregationResLevel = String(aggregationResLevel);
1492
- }
1493
- if (filters) {
1494
- urlParameters.filters = filters;
1495
- }
1496
- return baseSource('table', options, urlParameters).then(result => _extends({}, result, {
1497
- widgetSource: new WidgetTableSource(_extends({}, options, {
1498
- // NOTE: Parameters with default values above must be explicitly passed here.
1499
- spatialDataColumn,
1500
- spatialDataType
1501
- }))
1502
- }));
1503
- };
1504
-
1505
- // deck.gl
1506
- // SPDX-License-Identifier: MIT
1507
- // Copyright (c) vis.gl contributors
1508
- const h3TilesetSource = async function h3TilesetSource(options) {
1509
- const {
1510
- tableName
1511
- } = options;
1512
- const urlParameters = {
1513
- name: tableName
1514
- };
1515
- return baseSource('tileset', options, urlParameters);
1516
- };
1517
-
1518
- // deck.gl
1519
- // SPDX-License-Identifier: MIT
1520
- // Copyright (c) vis.gl contributors
1521
- const rasterSource = async function rasterSource(options) {
1522
- const {
1523
- tableName,
1524
- filters
1525
- } = options;
1526
- const urlParameters = {
1527
- name: tableName
1528
- };
1529
- if (filters) {
1530
- urlParameters.filters = filters;
1531
- }
1532
- return baseSource('raster', options, urlParameters);
1533
- };
1534
-
1535
- const quadbinQuerySource = async function quadbinQuerySource(options) {
1536
- const {
1537
- aggregationExp,
1538
- aggregationResLevel = DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN,
1539
- sqlQuery,
1540
- spatialDataColumn = 'quadbin',
1541
- queryParameters,
1542
- filters
1543
- } = options;
1544
- const spatialDataType = 'quadbin';
1545
- const urlParameters = {
1546
- aggregationExp,
1547
- q: sqlQuery,
1548
- spatialDataColumn,
1549
- spatialDataType
1550
- };
1551
- if (aggregationResLevel) {
1552
- urlParameters.aggregationResLevel = String(aggregationResLevel);
1553
- }
1554
- if (queryParameters) {
1555
- urlParameters.queryParameters = queryParameters;
1556
- }
1557
- if (filters) {
1558
- urlParameters.filters = filters;
1559
- }
1560
- return baseSource('query', options, urlParameters).then(result => _extends({}, result, {
1561
- widgetSource: new WidgetQuerySource(_extends({}, options, {
1562
- // NOTE: Parameters with default values above must be explicitly passed here.
1563
- spatialDataColumn,
1564
- spatialDataType
1565
- }))
1566
- }));
1567
- };
1568
-
1569
- const quadbinTableSource = async function quadbinTableSource(options) {
1570
- const {
1571
- aggregationExp,
1572
- aggregationResLevel = DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN,
1573
- spatialDataColumn = 'quadbin',
1574
- tableName,
1575
- filters
1576
- } = options;
1577
- const spatialDataType = 'quadbin';
1578
- const urlParameters = {
1579
- aggregationExp,
1580
- name: tableName,
1581
- spatialDataColumn,
1582
- spatialDataType
1583
- };
1584
- if (aggregationResLevel) {
1585
- urlParameters.aggregationResLevel = String(aggregationResLevel);
1586
- }
1587
- if (filters) {
1588
- urlParameters.filters = filters;
1589
- }
1590
- return baseSource('table', options, urlParameters).then(result => _extends({}, result, {
1591
- widgetSource: new WidgetTableSource(_extends({}, options, {
1592
- // NOTE: Parameters with default values above must be explicitly passed here.
1593
- spatialDataColumn,
1594
- spatialDataType
1595
- }))
1596
- }));
1597
- };
1598
-
1599
- // deck.gl
1600
- // SPDX-License-Identifier: MIT
1601
- // Copyright (c) vis.gl contributors
1602
- const quadbinTilesetSource = async function quadbinTilesetSource(options) {
1603
- const {
1604
- tableName
1605
- } = options;
1606
- const urlParameters = {
1607
- name: tableName
1608
- };
1609
- return baseSource('tileset', options, urlParameters);
1610
- };
1611
-
1612
- const vectorQuerySource = async function vectorQuerySource(options) {
1613
- const {
1614
- columns,
1615
- filters,
1616
- spatialDataColumn = 'geom',
1617
- sqlQuery,
1618
- tileResolution = DEFAULT_TILE_RESOLUTION,
1619
- queryParameters,
1620
- aggregationExp
1621
- } = options;
1622
- const spatialDataType = 'geo';
1623
- const urlParameters = {
1624
- spatialDataColumn,
1625
- spatialDataType,
1626
- tileResolution: tileResolution.toString(),
1627
- q: sqlQuery
1628
- };
1629
- if (columns) {
1630
- urlParameters.columns = columns.join(',');
1631
- }
1632
- if (filters) {
1633
- urlParameters.filters = filters;
1634
- }
1635
- if (queryParameters) {
1636
- urlParameters.queryParameters = queryParameters;
1637
- }
1638
- if (aggregationExp) {
1639
- urlParameters.aggregationExp = aggregationExp;
1640
- }
1641
- return baseSource('query', options, urlParameters).then(result => _extends({}, result, {
1642
- widgetSource: new WidgetQuerySource(_extends({}, options, {
1643
- // NOTE: Parameters with default values above must be explicitly passed here.
1644
- spatialDataColumn,
1645
- spatialDataType,
1646
- tileResolution
1647
- }))
1648
- }));
1649
- };
1650
-
1651
- const vectorTableSource = async function vectorTableSource(options) {
1652
- const {
1653
- columns,
1654
- filters,
1655
- spatialDataColumn = 'geom',
1656
- tableName,
1657
- tileResolution = DEFAULT_TILE_RESOLUTION,
1658
- aggregationExp
1659
- } = options;
1660
- const spatialDataType = 'geo';
1661
- const urlParameters = {
1662
- name: tableName,
1663
- spatialDataColumn,
1664
- spatialDataType,
1665
- tileResolution: tileResolution.toString()
1666
- };
1667
- if (columns) {
1668
- urlParameters.columns = columns.join(',');
1669
- }
1670
- if (filters) {
1671
- urlParameters.filters = filters;
1672
- }
1673
- if (aggregationExp) {
1674
- urlParameters.aggregationExp = aggregationExp;
1675
- }
1676
- return baseSource('table', options, urlParameters).then(result => _extends({}, result, {
1677
- widgetSource: new WidgetTableSource(_extends({}, options, {
1678
- // NOTE: Parameters with default values above must be explicitly passed here.
1679
- spatialDataColumn,
1680
- spatialDataType,
1681
- tileResolution
1682
- }))
1683
- }));
1684
- };
1685
-
1686
- // deck.gl
1687
- // SPDX-License-Identifier: MIT
1688
- // Copyright (c) vis.gl contributors
1689
- const vectorTilesetSource = async function vectorTilesetSource(options) {
1690
- const {
1691
- tableName
1692
- } = options;
1693
- const urlParameters = {
1694
- name: tableName
1695
- };
1696
- return baseSource('tileset', options, urlParameters);
1697
- };
1698
-
1699
- const query = async function query(options) {
1700
- const {
1701
- apiBaseUrl = SOURCE_DEFAULTS.apiBaseUrl,
1702
- clientId = SOURCE_DEFAULTS.clientId,
1703
- maxLengthURL = SOURCE_DEFAULTS.maxLengthURL,
1704
- localCache,
1705
- connectionName,
1706
- sqlQuery,
1707
- queryParameters
1708
- } = options;
1709
- const urlParameters = {
1710
- q: sqlQuery
1711
- };
1712
- if (queryParameters) {
1713
- urlParameters.queryParameters = JSON.stringify(queryParameters);
1714
- }
1715
- const baseUrl = buildQueryUrl({
1716
- apiBaseUrl,
1717
- connectionName
1718
- });
1719
- const headers = _extends({
1720
- Authorization: `Bearer ${options.accessToken}`
1721
- }, options.headers);
1722
- const parameters = _extends({
1723
- client: clientId
1724
- }, urlParameters);
1725
- const errorContext = {
1726
- requestType: 'SQL',
1727
- connection: options.connectionName,
1728
- type: 'query',
1729
- source: JSON.stringify(parameters, undefined, 2)
1730
- };
1731
- return await requestWithParameters({
1732
- baseUrl,
1733
- parameters,
1734
- headers,
1735
- errorContext,
1736
- maxLengthURL,
1737
- localCache
1738
- });
1739
- };
1740
-
1741
- export { ApiVersion, CartoAPIError, DEFAULT_API_BASE_URL, FilterType, SOURCE_DEFAULTS, WidgetBaseSource, WidgetQuerySource, WidgetTableSource, _getHexagonResolution, addFilter, boundaryQuerySource, boundaryTableSource, buildPublicMapUrl, buildStatsUrl, clearFilters, createPolygonSpatialFilter, createViewportSpatialFilter, getClient, getFilter, h3QuerySource, h3TableSource, h3TilesetSource, hasFilter, quadbinQuerySource, quadbinTableSource, quadbinTilesetSource, query, rasterSource, removeFilter, requestWithParameters, setClient, vectorQuerySource, vectorTableSource, vectorTilesetSource };
1742
- //# sourceMappingURL=api-client.modern.js.map