@carto/api-client 0.2.2 → 0.3.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.
@@ -3,6 +3,7 @@ var bboxPolygon = require('@turf/bbox-polygon');
3
3
  var union = require('@turf/union');
4
4
  var invariant = require('@turf/invariant');
5
5
  var helpers = require('@turf/helpers');
6
+ var carto = require('@deck.gl/carto');
6
7
 
7
8
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
9
 
@@ -35,7 +36,7 @@ function setClient(c) {
35
36
  }
36
37
 
37
38
  /** Current version of @carto/api-client. */
38
- const API_CLIENT_VERSION = "0.2.2";
39
+ const API_CLIENT_VERSION = "0.3.0";
39
40
  /**
40
41
  * Defines a comparator used when matching a column's values against given filter values.
41
42
  *
@@ -103,7 +104,7 @@ function normalizeObjectKeys(el) {
103
104
  }, {});
104
105
  }
105
106
  /** @internalRemarks Source: @carto/react-core */
106
- function assert$2(condition, message) {
107
+ function assert(condition, message) {
107
108
  if (!condition) {
108
109
  throw new Error(message);
109
110
  }
@@ -122,7 +123,7 @@ class InvalidColumnError extends Error {
122
123
  }
123
124
  }
124
125
  InvalidColumnError.NAME = 'InvalidColumnError';
125
- function isEmptyObject$1(object) {
126
+ function isEmptyObject(object) {
126
127
  for (const _ in object) {
127
128
  return false;
128
129
  }
@@ -172,7 +173,7 @@ function removeFilter(filters, _ref2) {
172
173
  }
173
174
  }
174
175
  }
175
- if (!owner || isEmptyObject$1(filter)) {
176
+ if (!owner || isEmptyObject(filter)) {
176
177
  delete filters[column];
177
178
  }
178
179
  return filters;
@@ -351,7 +352,7 @@ function _isMultiPolygon(geometry) {
351
352
  * @internalRemarks Source: @carto/constants
352
353
  * @internal
353
354
  */
354
- const DEFAULT_API_BASE_URL$1 = 'https://gcp-us-east1.api.carto.com';
355
+ const DEFAULT_API_BASE_URL = 'https://gcp-us-east1.api.carto.com';
355
356
  /**
356
357
  * @internalRemarks Source: @carto/react-api
357
358
  * @internal
@@ -482,10 +483,10 @@ const REQUEST_GET_MAX_URL_LENGTH = 2048;
482
483
  * @internalRemarks Source: @carto/react-api
483
484
  */
484
485
  function executeModel(props) {
485
- assert$2(props.source, 'executeModel: missing source');
486
- assert$2(props.model, 'executeModel: missing model');
487
- assert$2(props.params, 'executeModel: missing params');
488
- assert$2(AVAILABLE_MODELS.includes(props.model), `executeModel: model provided isn't valid. Available models: ${AVAILABLE_MODELS.join(', ')}`);
486
+ assert(props.source, 'executeModel: missing source');
487
+ assert(props.model, 'executeModel: missing model');
488
+ assert(props.params, 'executeModel: missing params');
489
+ assert(AVAILABLE_MODELS.includes(props.model), `executeModel: model provided isn't valid. Available models: ${AVAILABLE_MODELS.join(', ')}`);
489
490
  const {
490
491
  model,
491
492
  source,
@@ -500,10 +501,10 @@ function executeModel(props) {
500
501
  connectionName,
501
502
  clientId
502
503
  } = source;
503
- assert$2(apiBaseUrl, 'executeModel: missing apiBaseUrl');
504
- assert$2(accessToken, 'executeModel: missing accessToken');
505
- assert$2(apiVersion === V3, 'executeModel: SQL Model API requires CARTO 3+');
506
- assert$2(type !== MapType.TILESET, 'executeModel: Tilesets not supported');
504
+ assert(apiBaseUrl, 'executeModel: missing apiBaseUrl');
505
+ assert(accessToken, 'executeModel: missing accessToken');
506
+ assert(apiVersion === V3, 'executeModel: SQL Model API requires CARTO 3+');
507
+ assert(type !== MapType.TILESET, 'executeModel: Tilesets not supported');
507
508
  let url = `${apiBaseUrl}/v3/sql/${connectionName}/model/${model}`;
508
509
  const {
509
510
  filters,
@@ -907,7 +908,7 @@ class WidgetBaseSource {
907
908
  }
908
909
  WidgetBaseSource.defaultProps = {
909
910
  apiVersion: ApiVersion.V3,
910
- apiBaseUrl: DEFAULT_API_BASE_URL$1,
911
+ apiBaseUrl: DEFAULT_API_BASE_URL,
911
912
  clientId: getClient(),
912
913
  filters: {},
913
914
  filtersLogicalOperator: 'and',
@@ -979,1888 +980,13 @@ class WidgetTableSource extends WidgetBaseSource {
979
980
  }
980
981
  }
981
982
 
982
- /**
983
- * Throws an `Error` with the optional `message` if `condition` is falsy
984
- * @note Replacement for the external assert method to reduce bundle size
985
- */
986
- function assert$1(condition, message) {
987
- if (!condition) {
988
- throw new Error(message || 'loader assertion failed.');
989
- }
990
- }
991
-
992
- // Purpose: include this in your module to avoid
993
- /** true if running in a browser */
994
- const isBrowser$1 =
995
- // @ts-ignore process does not exist on browser
996
- Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
997
- // Extract node major version
998
- typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
999
-
1000
- // Do not name these variables the same as the global objects - will break bundling
1001
- const window_ = globalThis;
1002
- const process_ = globalThis.process || {};
1003
-
1004
- // based on https://github.com/cheton/is-electron
1005
- // https://github.com/electron/electron/issues/2288
1006
- /* eslint-disable complexity */
1007
- function isElectron(mockUserAgent) {
1008
- // Renderer process
1009
- // @ts-expect-error
1010
- if (typeof window !== 'undefined' && window.process?.type === 'renderer') {
1011
- return true;
1012
- }
1013
- // Main process
1014
- // eslint-disable-next-line
1015
- if (typeof process !== 'undefined' && Boolean(process.versions?.['electron'])) {
1016
- return true;
1017
- }
1018
- // Detect the user agent when the `nodeIntegration` option is set to true
1019
- const realUserAgent = typeof navigator !== 'undefined' && navigator.userAgent;
1020
- const userAgent = mockUserAgent || realUserAgent;
1021
- return Boolean(userAgent && userAgent.indexOf('Electron') >= 0);
1022
- }
1023
-
1024
- // This function is needed in initialization stages,
1025
- /** Check if in browser by duck-typing Node context */
1026
- function isBrowser() {
1027
- const isNode =
1028
- // @ts-expect-error
1029
- typeof process === 'object' && String(process) === '[object process]' && !process?.browser;
1030
- return !isNode || isElectron();
1031
- }
1032
-
1033
- // Extract injected version from package.json (injected by babel plugin)
1034
- // @ts-expect-error
1035
- const VERSION$2 = "4.0.7" ;
1036
- // TODO - wish we could just export a constant
1037
- // export const isBrowser = checkIfBrowser();
1038
-
1039
- // probe.gl, MIT license
1040
- function getStorage(type) {
1041
- try {
1042
- const storage = window[type];
1043
- const x = '__storage_test__';
1044
- storage.setItem(x, x);
1045
- storage.removeItem(x);
1046
- return storage;
1047
- } catch (e) {
1048
- return null;
1049
- }
1050
- }
1051
- // Store keys in local storage via simple interface
1052
- class LocalStorage {
1053
- constructor(id, defaultConfig, type = 'sessionStorage') {
1054
- this.storage = getStorage(type);
1055
- this.id = id;
1056
- this.config = defaultConfig;
1057
- this._loadConfiguration();
1058
- }
1059
- getConfiguration() {
1060
- return this.config;
1061
- }
1062
- setConfiguration(configuration) {
1063
- Object.assign(this.config, configuration);
1064
- if (this.storage) {
1065
- const serialized = JSON.stringify(this.config);
1066
- this.storage.setItem(this.id, serialized);
1067
- }
1068
- }
1069
- // Get config from persistent store, if available
1070
- _loadConfiguration() {
1071
- let configuration = {};
1072
- if (this.storage) {
1073
- const serializedConfiguration = this.storage.getItem(this.id);
1074
- configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
1075
- }
1076
- Object.assign(this.config, configuration);
1077
- return this;
1078
- }
1079
- }
1080
-
1081
- // probe.gl, MIT license
1082
- /**
1083
- * Format time
1084
- */
1085
- function formatTime(ms) {
1086
- let formatted;
1087
- if (ms < 10) {
1088
- formatted = `${ms.toFixed(2)}ms`;
1089
- } else if (ms < 100) {
1090
- formatted = `${ms.toFixed(1)}ms`;
1091
- } else if (ms < 1000) {
1092
- formatted = `${ms.toFixed(0)}ms`;
1093
- } else {
1094
- formatted = `${(ms / 1000).toFixed(2)}s`;
1095
- }
1096
- return formatted;
1097
- }
1098
- function leftPad(string, length = 8) {
1099
- const padLength = Math.max(length - string.length, 0);
1100
- return `${' '.repeat(padLength)}${string}`;
1101
- }
1102
-
1103
- var COLOR;
1104
- (function (COLOR) {
1105
- COLOR[COLOR["BLACK"] = 30] = "BLACK";
1106
- COLOR[COLOR["RED"] = 31] = "RED";
1107
- COLOR[COLOR["GREEN"] = 32] = "GREEN";
1108
- COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
1109
- COLOR[COLOR["BLUE"] = 34] = "BLUE";
1110
- COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
1111
- COLOR[COLOR["CYAN"] = 36] = "CYAN";
1112
- COLOR[COLOR["WHITE"] = 37] = "WHITE";
1113
- COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
1114
- COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
1115
- COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
1116
- COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
1117
- COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
1118
- COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
1119
- COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
1120
- COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
1121
- })(COLOR || (COLOR = {}));
1122
- const BACKGROUND_INCREMENT = 10;
1123
- function getColor(color) {
1124
- if (typeof color !== 'string') {
1125
- return color;
1126
- }
1127
- color = color.toUpperCase();
1128
- return COLOR[color] || COLOR.WHITE;
1129
- }
1130
- function addColor(string, color, background) {
1131
- if (!isBrowser && typeof string === 'string') {
1132
- if (color) {
1133
- const colorCode = getColor(color);
1134
- string = `\u001b[${colorCode}m${string}\u001b[39m`;
1135
- }
1136
- if (background) {
1137
- // background colors values are +10
1138
- const colorCode = getColor(background);
1139
- string = `\u001b[${colorCode + BACKGROUND_INCREMENT}m${string}\u001b[49m`;
1140
- }
1141
- }
1142
- return string;
1143
- }
1144
-
1145
- // Copyright (c) 2015 - 2017 Uber Technologies, Inc.
1146
- //
1147
- // Permission is hereby granted, free of charge, to any person obtaining a copy
1148
- // of this software and associated documentation files (the "Software"), to deal
1149
- // in the Software without restriction, including without limitation the rights
1150
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1151
- // copies of the Software, and to permit persons to whom the Software is
1152
- // furnished to do so, subject to the following conditions:
1153
- //
1154
- // The above copyright notice and this permission notice shall be included in
1155
- // all copies or substantial portions of the Software.
1156
- //
1157
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1158
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1159
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1160
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1161
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1162
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1163
- // THE SOFTWARE.
1164
- /**
1165
- * Binds the "this" argument of all functions on a class instance to the instance
1166
- * @param obj - class instance (typically a react component)
1167
- */
1168
- function autobind(obj, predefined = ['constructor']) {
1169
- const proto = Object.getPrototypeOf(obj);
1170
- const propNames = Object.getOwnPropertyNames(proto);
1171
- const object = obj;
1172
- for (const key of propNames) {
1173
- const value = object[key];
1174
- if (typeof value === 'function') {
1175
- if (!predefined.find(name => key === name)) {
1176
- object[key] = value.bind(obj);
1177
- }
1178
- }
1179
- }
1180
- }
1181
-
1182
- function assert(condition, message) {
1183
- if (!condition) {
1184
- throw new Error(message || 'Assertion failed');
1185
- }
1186
- }
1187
-
1188
- // probe.gl, MIT license
1189
- /** Get best timer available. */
1190
- function getHiResTimestamp() {
1191
- let timestamp;
1192
- if (isBrowser() && window_.performance) {
1193
- timestamp = window_?.performance?.now?.();
1194
- } else if ('hrtime' in process_) {
1195
- // @ts-ignore
1196
- const timeParts = process_?.hrtime?.();
1197
- timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
1198
- } else {
1199
- timestamp = Date.now();
1200
- }
1201
- return timestamp;
1202
- }
1203
-
1204
- // probe.gl, MIT license
1205
- // Instrumentation in other packages may override console methods, so preserve them here
1206
- const originalConsole = {
1207
- debug: isBrowser() ? console.debug || console.log : console.log,
1208
- log: console.log,
1209
- info: console.info,
1210
- warn: console.warn,
1211
- error: console.error
1212
- };
1213
- const DEFAULT_LOG_CONFIGURATION = {
1214
- enabled: true,
1215
- level: 0
1216
- };
1217
- function noop() {} // eslint-disable-line @typescript-eslint/no-empty-function
1218
- const cache = {};
1219
- const ONCE = {
1220
- once: true
1221
- };
1222
- /** A console wrapper */
1223
- class Log {
1224
- constructor({
1225
- id
1226
- } = {
1227
- id: ''
1228
- }) {
1229
- this.VERSION = VERSION$2;
1230
- this._startTs = getHiResTimestamp();
1231
- this._deltaTs = getHiResTimestamp();
1232
- this.userData = {};
1233
- // TODO - fix support from throttling groups
1234
- this.LOG_THROTTLE_TIMEOUT = 0; // Time before throttled messages are logged again
1235
- this.id = id;
1236
- this.userData = {};
1237
- this._storage = new LocalStorage(`__probe-${this.id}__`, DEFAULT_LOG_CONFIGURATION);
1238
- this.timeStamp(`${this.id} started`);
1239
- autobind(this);
1240
- Object.seal(this);
1241
- }
1242
- set level(newLevel) {
1243
- this.setLevel(newLevel);
1244
- }
1245
- get level() {
1246
- return this.getLevel();
1247
- }
1248
- isEnabled() {
1249
- return this._storage.config.enabled;
1250
- }
1251
- getLevel() {
1252
- return this._storage.config.level;
1253
- }
1254
- /** @return milliseconds, with fractions */
1255
- getTotal() {
1256
- return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
1257
- }
1258
- /** @return milliseconds, with fractions */
1259
- getDelta() {
1260
- return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
1261
- }
1262
- /** @deprecated use logLevel */
1263
- set priority(newPriority) {
1264
- this.level = newPriority;
1265
- }
1266
- /** @deprecated use logLevel */
1267
- get priority() {
1268
- return this.level;
1269
- }
1270
- /** @deprecated use logLevel */
1271
- getPriority() {
1272
- return this.level;
1273
- }
1274
- // Configure
1275
- enable(enabled = true) {
1276
- this._storage.setConfiguration({
1277
- enabled
1278
- });
1279
- return this;
1280
- }
1281
- setLevel(level) {
1282
- this._storage.setConfiguration({
1283
- level
1284
- });
1285
- return this;
1286
- }
1287
- /** return the current status of the setting */
1288
- get(setting) {
1289
- return this._storage.config[setting];
1290
- }
1291
- // update the status of the setting
1292
- set(setting, value) {
1293
- this._storage.setConfiguration({
1294
- [setting]: value
1295
- });
1296
- }
1297
- /** Logs the current settings as a table */
1298
- settings() {
1299
- if (console.table) {
1300
- console.table(this._storage.config);
1301
- } else {
1302
- console.log(this._storage.config);
1303
- }
1304
- }
1305
- // Unconditional logging
1306
- assert(condition, message) {
1307
- if (!condition) {
1308
- throw new Error(message || 'Assertion failed');
1309
- }
1310
- }
1311
- warn(message) {
1312
- return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
1313
- }
1314
- error(message) {
1315
- return this._getLogFunction(0, message, originalConsole.error, arguments);
1316
- }
1317
- /** Print a deprecation warning */
1318
- deprecated(oldUsage, newUsage) {
1319
- return this.warn(`\`${oldUsage}\` is deprecated and will be removed \
1320
- in a later version. Use \`${newUsage}\` instead`);
1321
- }
1322
- /** Print a removal warning */
1323
- removed(oldUsage, newUsage) {
1324
- return this.error(`\`${oldUsage}\` has been removed. Use \`${newUsage}\` instead`);
1325
- }
1326
- probe(logLevel, message) {
1327
- return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
1328
- time: true,
1329
- once: true
1330
- });
1331
- }
1332
- log(logLevel, message) {
1333
- return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
1334
- }
1335
- info(logLevel, message) {
1336
- return this._getLogFunction(logLevel, message, console.info, arguments);
1337
- }
1338
- once(logLevel, message) {
1339
- return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
1340
- }
1341
- /** Logs an object as a table */
1342
- table(logLevel, table, columns) {
1343
- if (table) {
1344
- return this._getLogFunction(logLevel, table, console.table || noop, columns && [columns], {
1345
- tag: getTableHeader(table)
1346
- });
1347
- }
1348
- return noop;
1349
- }
1350
- time(logLevel, message) {
1351
- return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
1352
- }
1353
- timeEnd(logLevel, message) {
1354
- return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
1355
- }
1356
- timeStamp(logLevel, message) {
1357
- return this._getLogFunction(logLevel, message, console.timeStamp || noop);
1358
- }
1359
- group(logLevel, message, opts = {
1360
- collapsed: false
1361
- }) {
1362
- const options = normalizeArguments({
1363
- logLevel,
1364
- message,
1365
- opts
1366
- });
1367
- const {
1368
- collapsed
1369
- } = opts;
1370
- // @ts-expect-error
1371
- options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
1372
- return this._getLogFunction(options);
1373
- }
1374
- groupCollapsed(logLevel, message, opts = {}) {
1375
- return this.group(logLevel, message, Object.assign({}, opts, {
1376
- collapsed: true
1377
- }));
1378
- }
1379
- groupEnd(logLevel) {
1380
- return this._getLogFunction(logLevel, '', console.groupEnd || noop);
1381
- }
1382
- // EXPERIMENTAL
1383
- withGroup(logLevel, message, func) {
1384
- this.group(logLevel, message)();
1385
- try {
1386
- func();
1387
- } finally {
1388
- this.groupEnd(logLevel)();
1389
- }
1390
- }
1391
- trace() {
1392
- if (console.trace) {
1393
- console.trace();
1394
- }
1395
- }
1396
- // PRIVATE METHODS
1397
- /** Deduces log level from a variety of arguments */
1398
- _shouldLog(logLevel) {
1399
- return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
1400
- }
1401
- _getLogFunction(logLevel, message, method, args, opts) {
1402
- if (this._shouldLog(logLevel)) {
1403
- // normalized opts + timings
1404
- opts = normalizeArguments({
1405
- logLevel,
1406
- message,
1407
- args,
1408
- opts
1409
- });
1410
- method = method || opts.method;
1411
- assert(method);
1412
- opts.total = this.getTotal();
1413
- opts.delta = this.getDelta();
1414
- // reset delta timer
1415
- this._deltaTs = getHiResTimestamp();
1416
- const tag = opts.tag || opts.message;
1417
- if (opts.once && tag) {
1418
- if (!cache[tag]) {
1419
- cache[tag] = getHiResTimestamp();
1420
- } else {
1421
- return noop;
1422
- }
1423
- }
1424
- // TODO - Make throttling work with groups
1425
- // if (opts.nothrottle || !throttle(tag, this.LOG_THROTTLE_TIMEOUT)) {
1426
- // return noop;
1427
- // }
1428
- message = decorateMessage(this.id, opts.message, opts);
1429
- // Bind console function so that it can be called after being returned
1430
- return method.bind(console, message, ...opts.args);
1431
- }
1432
- return noop;
1433
- }
1434
- }
1435
- Log.VERSION = VERSION$2;
1436
- /**
1437
- * Get logLevel from first argument:
1438
- * - log(logLevel, message, args) => logLevel
1439
- * - log(message, args) => 0
1440
- * - log({logLevel, ...}, message, args) => logLevel
1441
- * - log({logLevel, message, args}) => logLevel
1442
- */
1443
- function normalizeLogLevel(logLevel) {
1444
- if (!logLevel) {
1445
- return 0;
1446
- }
1447
- let resolvedLevel;
1448
- switch (typeof logLevel) {
1449
- case 'number':
1450
- resolvedLevel = logLevel;
1451
- break;
1452
- case 'object':
1453
- // Backward compatibility
1454
- // TODO - deprecate `priority`
1455
- // @ts-expect-error
1456
- resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
1457
- break;
1458
- default:
1459
- return 0;
1460
- }
1461
- // 'log level must be a number'
1462
- assert(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
1463
- return resolvedLevel;
1464
- }
1465
- /**
1466
- * "Normalizes" the various argument patterns into an object with known types
1467
- * - log(logLevel, message, args) => {logLevel, message, args}
1468
- * - log(message, args) => {logLevel: 0, message, args}
1469
- * - log({logLevel, ...}, message, args) => {logLevel, message, args}
1470
- * - log({logLevel, message, args}) => {logLevel, message, args}
1471
- */
1472
- function normalizeArguments(opts) {
1473
- const {
1474
- logLevel,
1475
- message
1476
- } = opts;
1477
- opts.logLevel = normalizeLogLevel(logLevel);
1478
- // We use `arguments` instead of rest parameters (...args) because IE
1479
- // does not support the syntax. Rest parameters is transpiled to code with
1480
- // perf impact. Doing it here instead avoids constructing args when logging is
1481
- // disabled.
1482
- // TODO - remove when/if IE support is dropped
1483
- const args = opts.args ? Array.from(opts.args) : [];
1484
- // args should only contain arguments that appear after `message`
1485
- // eslint-disable-next-line no-empty
1486
- while (args.length && args.shift() !== message) {}
1487
- switch (typeof logLevel) {
1488
- case 'string':
1489
- case 'function':
1490
- if (message !== undefined) {
1491
- args.unshift(message);
1492
- }
1493
- opts.message = logLevel;
1494
- break;
1495
- case 'object':
1496
- Object.assign(opts, logLevel);
1497
- break;
1498
- }
1499
- // Resolve functions into strings by calling them
1500
- if (typeof opts.message === 'function') {
1501
- opts.message = opts.message();
1502
- }
1503
- const messageType = typeof opts.message;
1504
- // 'log message must be a string' or object
1505
- assert(messageType === 'string' || messageType === 'object');
1506
- // original opts + normalized opts + opts arg + fixed up message
1507
- return Object.assign(opts, {
1508
- args
1509
- }, opts.opts);
1510
- }
1511
- function decorateMessage(id, message, opts) {
1512
- if (typeof message === 'string') {
1513
- const time = opts.time ? leftPad(formatTime(opts.total)) : '';
1514
- message = opts.time ? `${id}: ${time} ${message}` : `${id}: ${message}`;
1515
- message = addColor(message, opts.color, opts.background);
1516
- }
1517
- return message;
1518
- }
1519
- function getTableHeader(table) {
1520
- for (const key in table) {
1521
- for (const title in table[key]) {
1522
- return title || 'untitled';
1523
- }
1524
- }
1525
- return 'empty';
1526
- }
1527
-
1528
- // loaders.gl
1529
- /**
1530
- * Helper for safely accessing global loaders.gl variables
1531
- * Wraps initialization of global variable in function to defeat overly aggressive tree-shakers
1532
- */
1533
- function getGlobalLoaderState() {
1534
- // @ts-ignore
1535
- globalThis.loaders = globalThis.loaders || {};
1536
- // @ts-ignore
1537
- const {
1538
- loaders
1539
- } = globalThis;
1540
- // Add _state object to keep separate from modules added to globalThis.loaders
1541
- if (!loaders._state) {
1542
- loaders._state = {};
1543
- }
1544
- return loaders._state;
1545
- }
1546
-
1547
- // loaders.gl
1548
- function isLoaderObject(loader) {
1549
- if (!loader) {
1550
- return false;
1551
- }
1552
- if (Array.isArray(loader)) {
1553
- loader = loader[0];
1554
- }
1555
- const hasExtensions = Array.isArray(loader?.extensions);
1556
- /* Now handled by types and worker loaders do not have these
1557
- let hasParser =
1558
- loader.parseTextSync ||
1559
- loader.parseSync ||
1560
- loader.parse ||
1561
- loader.parseStream || // TODO Remove, Replace with parseInBatches
1562
- loader.parseInBatches;
1563
- */
1564
- return hasExtensions;
1565
- }
1566
- function normalizeLoader(loader) {
1567
- // This error is fairly easy to trigger by mixing up import statements etc
1568
- // So we make an exception and add a developer error message for this case
1569
- // To help new users from getting stuck here
1570
- assert$1(loader, 'null loader');
1571
- assert$1(isLoaderObject(loader), 'invalid loader');
1572
- // NORMALIZE [LOADER, OPTIONS] => LOADER
1573
- // If [loader, options], create a new loaders object with options merged in
1574
- let options;
1575
- if (Array.isArray(loader)) {
1576
- options = loader[1];
1577
- loader = loader[0];
1578
- loader = {
1579
- ...loader,
1580
- options: {
1581
- ...loader.options,
1582
- ...options
1583
- }
1584
- };
1585
- }
1586
- // NORMALIZE text and binary flags
1587
- // Ensure at least one of text/binary flags are properly set
1588
- // @ts-expect-error
1589
- if (loader?.parseTextSync || loader?.parseText) {
1590
- loader.text = true;
1591
- }
1592
- if (!loader.text) {
1593
- loader.binary = true;
1594
- }
1595
- return loader;
1596
- }
1597
-
1598
- // loaders.gl
1599
- /**
1600
- * Store global registered loaders on the global object to increase chances of cross loaders-version interoperability
1601
- * This use case is not reliable but can help when testing new versions of loaders.gl with existing frameworks
1602
- */
1603
- const getGlobalLoaderRegistry = () => {
1604
- const state = getGlobalLoaderState();
1605
- state.loaderRegistry = state.loaderRegistry || [];
1606
- return state.loaderRegistry;
1607
- };
1608
- /** Register a list of global loaders */
1609
- function registerLoaders(loaders) {
1610
- const loaderRegistry = getGlobalLoaderRegistry();
1611
- loaders = Array.isArray(loaders) ? loaders : [loaders];
1612
- for (const loader of loaders) {
1613
- const normalizedLoader = normalizeLoader(loader);
1614
- if (!loaderRegistry.find(registeredLoader => normalizedLoader === registeredLoader)) {
1615
- // add to the beginning of the loaderRegistry, so the last registeredLoader get picked
1616
- loaderRegistry.unshift(normalizedLoader);
1617
- }
1618
- }
1619
- }
1620
-
1621
- // Version constant cannot be imported, it needs to correspond to the build version of **this** module.
1622
- // __VERSION__ is injected by babel-plugin-version-inline
1623
- // @ts-ignore TS2304: Cannot find name '__VERSION__'.
1624
- const VERSION$1 = "4.2.3" ;
1625
-
1626
- // @ts-ignore TS2339: Property does not exist on type
1627
- const parseImageNode = globalThis.loaders?.parseImageNode;
1628
- const IMAGE_SUPPORTED = typeof Image !== 'undefined'; // NOTE: "false" positives if jsdom is installed
1629
- const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
1630
- const NODE_IMAGE_SUPPORTED = Boolean(parseImageNode);
1631
- const DATA_SUPPORTED = isBrowser$1 ? true : NODE_IMAGE_SUPPORTED;
1632
- /**
1633
- * Checks if a loaders.gl image type is supported
1634
- * @param type image type string
1635
- */
1636
- function isImageTypeSupported(type) {
1637
- switch (type) {
1638
- case 'auto':
1639
- // Should only ever be false in Node.js, if polyfills have not been installed...
1640
- return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
1641
- case 'imagebitmap':
1642
- return IMAGE_BITMAP_SUPPORTED;
1643
- case 'image':
1644
- return IMAGE_SUPPORTED;
1645
- case 'data':
1646
- return DATA_SUPPORTED;
1647
- default:
1648
- throw new Error(`@loaders.gl/images: image ${type} not supported in this environment`);
1649
- }
1650
- }
1651
- /**
1652
- * Returns the "most performant" supported image type on this platform
1653
- * @returns image type string
1654
- */
1655
- function getDefaultImageType() {
1656
- if (IMAGE_BITMAP_SUPPORTED) {
1657
- return 'imagebitmap';
1658
- }
1659
- if (IMAGE_SUPPORTED) {
1660
- return 'image';
1661
- }
1662
- if (DATA_SUPPORTED) {
1663
- return 'data';
1664
- }
1665
- // This should only happen in Node.js
1666
- throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
1667
- }
1668
-
1669
- function getImageType(image) {
1670
- const format = getImageTypeOrNull(image);
1671
- if (!format) {
1672
- throw new Error('Not an image');
1673
- }
1674
- return format;
1675
- }
1676
- function getImageData(image) {
1677
- switch (getImageType(image)) {
1678
- case 'data':
1679
- return image;
1680
- case 'image':
1681
- case 'imagebitmap':
1682
- // Extract the image data from the image via a canvas
1683
- const canvas = document.createElement('canvas');
1684
- // TODO - reuse the canvas?
1685
- const context = canvas.getContext('2d');
1686
- if (!context) {
1687
- throw new Error('getImageData');
1688
- }
1689
- // @ts-ignore
1690
- canvas.width = image.width;
1691
- // @ts-ignore
1692
- canvas.height = image.height;
1693
- // @ts-ignore
1694
- context.drawImage(image, 0, 0);
1695
- // @ts-ignore
1696
- return context.getImageData(0, 0, image.width, image.height);
1697
- default:
1698
- throw new Error('getImageData');
1699
- }
1700
- }
1701
- // PRIVATE
1702
- // eslint-disable-next-line complexity
1703
- function getImageTypeOrNull(image) {
1704
- if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
1705
- return 'imagebitmap';
1706
- }
1707
- if (typeof Image !== 'undefined' && image instanceof Image) {
1708
- return 'image';
1709
- }
1710
- if (image && typeof image === 'object' && image.data && image.width && image.height) {
1711
- return 'data';
1712
- }
1713
- return null;
1714
- }
1715
-
1716
- // SVG parsing has limitations, e.g:
1717
- // https://bugs.chromium.org/p/chromium/issues/detail?id=606319
1718
- const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
1719
- const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
1720
- function isSVG(url) {
1721
- return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
1722
- }
1723
- function getBlobOrSVGDataUrl(arrayBuffer, url) {
1724
- if (isSVG(url)) {
1725
- // Prepare a properly tagged data URL, and load using normal mechanism
1726
- const textDecoder = new TextDecoder();
1727
- let xmlText = textDecoder.decode(arrayBuffer);
1728
- // TODO Escape in browser to support e.g. Chinese characters
1729
- try {
1730
- if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
1731
- xmlText = unescape(encodeURIComponent(xmlText));
1732
- }
1733
- } catch (error) {
1734
- throw new Error(error.message);
1735
- }
1736
- // base64 encoding is safer. utf-8 fails in some browsers
1737
- const src = `data:image/svg+xml;base64,${btoa(xmlText)}`;
1738
- return src;
1739
- }
1740
- return getBlob(arrayBuffer, url);
1741
- }
1742
- function getBlob(arrayBuffer, url) {
1743
- if (isSVG(url)) {
1744
- // https://bugs.chromium.org/p/chromium/issues/detail?id=606319
1745
- // return new Blob([new Uint8Array(arrayBuffer)], {type: 'image/svg+xml'});
1746
- throw new Error('SVG cannot be parsed directly to imagebitmap');
1747
- }
1748
- // TODO - how to determine mime type? Param? Sniff here?
1749
- return new Blob([new Uint8Array(arrayBuffer)]); // MIME type not needed?
1750
- }
1751
-
1752
- // Parses html image from array buffer
1753
- async function parseToImage(arrayBuffer, options, url) {
1754
- // Note: image parsing requires conversion to Blob (for createObjectURL).
1755
- // Potentially inefficient for not using `response.blob()` (and for File / Blob inputs)...
1756
- // But presumably not worth adding 'blob' flag to loader objects?
1757
- const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
1758
- const URL = self.URL || self.webkitURL;
1759
- const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
1760
- try {
1761
- return await loadToImage(objectUrl || blobOrDataUrl, options);
1762
- } finally {
1763
- if (objectUrl) {
1764
- URL.revokeObjectURL(objectUrl);
1765
- }
1766
- }
1767
- }
1768
- async function loadToImage(url, options) {
1769
- const image = new Image();
1770
- image.src = url;
1771
- // The `image.onload()` callback does not guarantee that the image has been decoded
1772
- // so a main thread "freeze" can be incurred when using the image for the first time.
1773
- // `Image.decode()` returns a promise that completes when image is decoded.
1774
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/decode
1775
- // Note: When calling `img.decode()`, we do not need to wait for `img.onload()`
1776
- // Note: `HTMLImageElement.decode()` is not available in Edge and IE11
1777
- if (options.image && options.image.decode && image.decode) {
1778
- await image.decode();
1779
- return image;
1780
- }
1781
- // Create a promise that tracks onload/onerror callbacks
1782
- return await new Promise((resolve, reject) => {
1783
- try {
1784
- image.onload = () => resolve(image);
1785
- image.onerror = error => {
1786
- const message = error instanceof Error ? error.message : 'error';
1787
- reject(new Error(message));
1788
- };
1789
- } catch (error) {
1790
- reject(error);
1791
- }
1792
- });
1793
- }
1794
-
1795
- const EMPTY_OBJECT = {};
1796
- let imagebitmapOptionsSupported = true;
1797
- /**
1798
- * Asynchronously parses an array buffer into an ImageBitmap - this contains the decoded data
1799
- * ImageBitmaps are supported on worker threads, but not supported on Edge, IE11 and Safari
1800
- * https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap#Browser_compatibility
1801
- *
1802
- * TODO - createImageBitmap supports source rect (5 param overload), pass through?
1803
- */
1804
- async function parseToImageBitmap(arrayBuffer, options, url) {
1805
- let blob;
1806
- // Cannot parse SVG directly to ImageBitmap, parse to Image first
1807
- if (isSVG(url)) {
1808
- // Note: this only works on main thread
1809
- const image = await parseToImage(arrayBuffer, options, url);
1810
- blob = image;
1811
- } else {
1812
- // Create blob from the array buffer
1813
- blob = getBlob(arrayBuffer, url);
1814
- }
1815
- const imagebitmapOptions = options && options.imagebitmap;
1816
- return await safeCreateImageBitmap(blob, imagebitmapOptions);
1817
- }
1818
- /**
1819
- * Safely creates an imageBitmap with options
1820
- * *
1821
- * Firefox crashes if imagebitmapOptions is supplied
1822
- * Avoid supplying if not provided or supported, remember if not supported
1823
- */
1824
- async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
1825
- if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
1826
- imagebitmapOptions = null;
1827
- }
1828
- if (imagebitmapOptions) {
1829
- try {
1830
- // @ts-ignore Options
1831
- return await createImageBitmap(blob, imagebitmapOptions);
1832
- } catch (error) {
1833
- console.warn(error); // eslint-disable-line
1834
- imagebitmapOptionsSupported = false;
1835
- }
1836
- }
1837
- return await createImageBitmap(blob);
1838
- }
1839
- function isEmptyObject(object) {
1840
- // @ts-ignore
1841
- for (const key in object || EMPTY_OBJECT) {
1842
- return false;
1843
- }
1844
- return true;
1845
- }
1846
-
1847
- // loaders.gl
1848
- // SPDX-License-Identifier: MIT
1849
- // Copyright (c) vis.gl contributors
1850
- // code adapted from https://github.com/sindresorhus/file-type under MIT license
1851
- /**
1852
- * Tests if a buffer is in ISO base media file format (ISOBMFF) @see https://en.wikipedia.org/wiki/ISO_base_media_file_format
1853
- * (ISOBMFF is a media container standard based on the Apple QuickTime container format)
1854
- */
1855
- function getISOBMFFMediaType(buffer) {
1856
- // Almost all ISO base media files start with `ftyp` box. (It's not required to be first, but it's recommended to be.)
1857
- if (!checkString(buffer, 'ftyp', 4)) {
1858
- return null;
1859
- }
1860
- // Extra check: test for 8859-1 printable characters (for simplicity, it's a mask which also catches one non-printable character).
1861
- if ((buffer[8] & 0x60) === 0x00) {
1862
- return null;
1863
- }
1864
- // `ftyp` box must contain a brand major identifier, which must consist of ISO 8859-1 printable characters.
1865
- return decodeMajorBrand(buffer);
1866
- }
1867
- /**
1868
- * brands explained @see https://github.com/strukturag/libheif/issues/83
1869
- * code adapted from @see https://github.com/sindresorhus/file-type/blob/main/core.js#L489-L492
1870
- */
1871
- function decodeMajorBrand(buffer) {
1872
- const brandMajor = getUTF8String(buffer, 8, 12).replace('\0', ' ').trim();
1873
- switch (brandMajor) {
1874
- case 'avif':
1875
- case 'avis':
1876
- return {
1877
- extension: 'avif',
1878
- mimeType: 'image/avif'
1879
- };
1880
- default:
1881
- return null;
1882
- }
1883
- // We don't need these now, but they are easy to add
1884
- // case 'mif1':
1885
- // return {extension: 'heic', mimeType: 'image/heif'};
1886
- // case 'msf1':
1887
- // return {extension: 'heic', mimeType: 'image/heif-sequence'};
1888
- // case 'heic':
1889
- // case 'heix':
1890
- // return {extension: 'heic', mimeType: 'image/heic'};
1891
- // case 'hevc':
1892
- // case 'hevx':
1893
- // return {extension: 'heic', mimeType: 'image/heic-sequence'};
1894
- // case 'qt':
1895
- // return {ext: 'mov', mime: 'video/quicktime'};
1896
- // case 'M4V':
1897
- // case 'M4VH':
1898
- // case 'M4VP':
1899
- // return {ext: 'm4v', mime: 'video/x-m4v'};
1900
- // case 'M4P':
1901
- // return {ext: 'm4p', mime: 'video/mp4'};
1902
- // case 'M4B':
1903
- // return {ext: 'm4b', mime: 'audio/mp4'};
1904
- // case 'M4A':
1905
- // return {ext: 'm4a', mime: 'audio/x-m4a'};
1906
- // case 'F4V':
1907
- // return {ext: 'f4v', mime: 'video/mp4'};
1908
- // case 'F4P':
1909
- // return {ext: 'f4p', mime: 'video/mp4'};
1910
- // case 'F4A':
1911
- // return {ext: 'f4a', mime: 'audio/mp4'};
1912
- // case 'F4B':
1913
- // return {ext: 'f4b', mime: 'audio/mp4'};
1914
- // case 'crx':
1915
- // return {ext: 'cr3', mime: 'image/x-canon-cr3'};
1916
- // default:
1917
- // if (brandMajor.startsWith('3g')) {
1918
- // if (brandMajor.startsWith('3g2')) {
1919
- // return {ext: '3g2', mime: 'video/3gpp2'};
1920
- // }
1921
- // return {ext: '3gp', mime: 'video/3gpp'};
1922
- // }
1923
- // return {ext: 'mp4', mime: 'video/mp4'};
1924
- }
1925
- /** Interpret a chunk of bytes as a UTF8 string */
1926
- function getUTF8String(array, start, end) {
1927
- return String.fromCharCode(...array.slice(start, end));
1928
- }
1929
- function stringToBytes(string) {
1930
- return [...string].map(character => character.charCodeAt(0));
1931
- }
1932
- function checkString(buffer, header, offset = 0) {
1933
- const headerBytes = stringToBytes(header);
1934
- for (let i = 0; i < headerBytes.length; ++i) {
1935
- if (headerBytes[i] !== buffer[i + offset]) {
1936
- return false;
1937
- }
1938
- }
1939
- return true;
1940
- }
1941
-
1942
- // Attributions
1943
- const BIG_ENDIAN = false;
1944
- const LITTLE_ENDIAN = true;
1945
- /**
1946
- * Extracts `{mimeType, width and height}` from a memory buffer containing a known image format
1947
- * Currently supports `image/png`, `image/jpeg`, `image/bmp` and `image/gif`.
1948
- * @param binaryData: DataView | ArrayBuffer image file memory to parse
1949
- * @returns metadata or null if memory is not a valid image file format layout.
1950
- */
1951
- function getBinaryImageMetadata(binaryData) {
1952
- const dataView = toDataView(binaryData);
1953
- return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView) || getISOBMFFMetadata(dataView);
1954
- }
1955
- // ISOBMFF
1956
- function getISOBMFFMetadata(binaryData) {
1957
- const buffer = new Uint8Array(binaryData instanceof DataView ? binaryData.buffer : binaryData);
1958
- const mediaType = getISOBMFFMediaType(buffer);
1959
- if (!mediaType) {
1960
- return null;
1961
- }
1962
- return {
1963
- mimeType: mediaType.mimeType,
1964
- // TODO - decode width and height
1965
- width: 0,
1966
- height: 0
1967
- };
1968
- }
1969
- // PNG
1970
- function getPngMetadata(binaryData) {
1971
- const dataView = toDataView(binaryData);
1972
- // Check file contains the first 4 bytes of the PNG signature.
1973
- const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
1974
- if (!isPng) {
1975
- return null;
1976
- }
1977
- // Extract size from a binary PNG file
1978
- return {
1979
- mimeType: 'image/png',
1980
- width: dataView.getUint32(16, BIG_ENDIAN),
1981
- height: dataView.getUint32(20, BIG_ENDIAN)
1982
- };
1983
- }
1984
- // GIF
1985
- // Extract size from a binary GIF file
1986
- // TODO: GIF is not this simple
1987
- function getGifMetadata(binaryData) {
1988
- const dataView = toDataView(binaryData);
1989
- // Check first 4 bytes of the GIF signature ("GIF8").
1990
- const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
1991
- if (!isGif) {
1992
- return null;
1993
- }
1994
- // GIF is little endian.
1995
- return {
1996
- mimeType: 'image/gif',
1997
- width: dataView.getUint16(6, LITTLE_ENDIAN),
1998
- height: dataView.getUint16(8, LITTLE_ENDIAN)
1999
- };
2000
- }
2001
- // BMP
2002
- // TODO: BMP is not this simple
2003
- function getBmpMetadata(binaryData) {
2004
- const dataView = toDataView(binaryData);
2005
- // Check magic number is valid (first 2 characters should be "BM").
2006
- // The mandatory bitmap file header is 14 bytes long.
2007
- const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
2008
- if (!isBmp) {
2009
- return null;
2010
- }
2011
- // BMP is little endian.
2012
- return {
2013
- mimeType: 'image/bmp',
2014
- width: dataView.getUint32(18, LITTLE_ENDIAN),
2015
- height: dataView.getUint32(22, LITTLE_ENDIAN)
2016
- };
2017
- }
2018
- // JPEG
2019
- // Extract width and height from a binary JPEG file
2020
- function getJpegMetadata(binaryData) {
2021
- const dataView = toDataView(binaryData);
2022
- // Check file contains the JPEG "start of image" (SOI) marker
2023
- // followed by another marker.
2024
- const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
2025
- if (!isJpeg) {
2026
- return null;
2027
- }
2028
- const {
2029
- tableMarkers,
2030
- sofMarkers
2031
- } = getJpegMarkers();
2032
- // Exclude the two byte SOI marker.
2033
- let i = 2;
2034
- while (i + 9 < dataView.byteLength) {
2035
- const marker = dataView.getUint16(i, BIG_ENDIAN);
2036
- // The frame that contains the width and height of the JPEG image.
2037
- if (sofMarkers.has(marker)) {
2038
- return {
2039
- mimeType: 'image/jpeg',
2040
- height: dataView.getUint16(i + 5, BIG_ENDIAN),
2041
- // Number of lines
2042
- width: dataView.getUint16(i + 7, BIG_ENDIAN) // Number of pixels per line
2043
- };
2044
- }
2045
- // Miscellaneous tables/data preceding the frame header.
2046
- if (!tableMarkers.has(marker)) {
2047
- return null;
2048
- }
2049
- // Length includes size of length parameter but not the two byte header.
2050
- i += 2;
2051
- i += dataView.getUint16(i, BIG_ENDIAN);
2052
- }
2053
- return null;
2054
- }
2055
- function getJpegMarkers() {
2056
- // Tables/misc header markers.
2057
- // DQT, DHT, DAC, DRI, COM, APP_n
2058
- const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
2059
- for (let i = 0xffe0; i < 0xfff0; ++i) {
2060
- tableMarkers.add(i);
2061
- }
2062
- // SOF markers and DHP marker.
2063
- // These markers are after tables/misc data.
2064
- const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
2065
- return {
2066
- tableMarkers,
2067
- sofMarkers
2068
- };
2069
- }
2070
- // TODO - move into image module?
2071
- function toDataView(data) {
2072
- if (data instanceof DataView) {
2073
- return data;
2074
- }
2075
- if (ArrayBuffer.isView(data)) {
2076
- return new DataView(data.buffer);
2077
- }
2078
- // TODO: make these functions work for Node.js buffers?
2079
- // if (bufferToArrayBuffer) {
2080
- // data = bufferToArrayBuffer(data);
2081
- // }
2082
- // Careful - Node Buffers will look like ArrayBuffers (keep after isBuffer)
2083
- if (data instanceof ArrayBuffer) {
2084
- return new DataView(data);
2085
- }
2086
- throw new Error('toDataView');
2087
- }
2088
-
2089
- // Use polyfills if installed to parsed image using get-pixels
2090
- async function parseToNodeImage(arrayBuffer, options) {
2091
- const {
2092
- mimeType
2093
- } = getBinaryImageMetadata(arrayBuffer) || {};
2094
- // @ts-ignore
2095
- const parseImageNode = globalThis.loaders?.parseImageNode;
2096
- assert$1(parseImageNode); // '@loaders.gl/polyfills not installed'
2097
- // @ts-expect-error TODO should we throw error in this case?
2098
- return await parseImageNode(arrayBuffer, mimeType);
2099
- }
2100
-
2101
- // Parse to platform defined image type (data on node, ImageBitmap or HTMLImage on browser)
2102
- // eslint-disable-next-line complexity
2103
- async function parseImage(arrayBuffer, options, context) {
2104
- options = options || {};
2105
- const imageOptions = options.image || {};
2106
- // The user can request a specific output format via `options.image.type`
2107
- const imageType = imageOptions.type || 'auto';
2108
- const {
2109
- url
2110
- } = context || {};
2111
- // Note: For options.image.type === `data`, we may still need to load as `image` or `imagebitmap`
2112
- const loadType = getLoadableImageType(imageType);
2113
- let image;
2114
- switch (loadType) {
2115
- case 'imagebitmap':
2116
- image = await parseToImageBitmap(arrayBuffer, options, url);
2117
- break;
2118
- case 'image':
2119
- image = await parseToImage(arrayBuffer, options, url);
2120
- break;
2121
- case 'data':
2122
- // Node.js loads imagedata directly
2123
- image = await parseToNodeImage(arrayBuffer);
2124
- break;
2125
- default:
2126
- assert$1(false);
2127
- }
2128
- // Browser: if options.image.type === 'data', we can now extract data from the loaded image
2129
- if (imageType === 'data') {
2130
- image = getImageData(image);
2131
- }
2132
- return image;
2133
- }
2134
- // Get a loadable image type from image type
2135
- function getLoadableImageType(type) {
2136
- switch (type) {
2137
- case 'auto':
2138
- case 'data':
2139
- // Browser: For image data we need still need to load using an image format
2140
- // Node: the default image type is `data`.
2141
- return getDefaultImageType();
2142
- default:
2143
- // Throw an error if not supported
2144
- isImageTypeSupported(type);
2145
- return type;
2146
- }
2147
- }
2148
-
2149
- // import type { ImageType } from '@loaders.gl/schema';
2150
- const EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg', 'avif'];
2151
- const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
2152
- const DEFAULT_IMAGE_LOADER_OPTIONS = {
2153
- image: {
2154
- type: 'auto',
2155
- decode: true // if format is HTML
2156
- }
2157
- // imagebitmap: {} - passes (platform dependent) parameters to ImageBitmap constructor
2158
- };
2159
- /**
2160
- * Loads a platform-specific image type
2161
- * Note: This type can be used as input data to WebGL texture creation
2162
- */
2163
- const ImageLoader = {
2164
- dataType: null,
2165
- batchType: null,
2166
- id: 'image',
2167
- module: 'images',
2168
- name: 'Images',
2169
- version: VERSION$1,
2170
- mimeTypes: MIME_TYPES,
2171
- extensions: EXTENSIONS,
2172
- parse: parseImage,
2173
- // TODO: byteOffset, byteLength;
2174
- tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
2175
- options: DEFAULT_IMAGE_LOADER_OPTIONS
2176
- };
2177
-
2178
- const defaultLogger = new Log({
2179
- id: 'deck'
2180
- });
2181
- var log = defaultLogger;
2182
-
2183
- const logState = {
2184
- attributeUpdateStart: -1,
2185
- attributeManagerUpdateStart: -1,
2186
- attributeUpdateMessages: []
2187
- };
2188
- const LOG_LEVEL_MAJOR_UPDATE = 1; // Events with direct perf impact
2189
- const LOG_LEVEL_MINOR_UPDATE = 2; // Events that may affect perf
2190
- const LOG_LEVEL_UPDATE_DETAIL = 3;
2191
- const LOG_LEVEL_INFO = 4;
2192
- const LOG_LEVEL_DRAW = 2;
2193
- const getLoggers = log => ({
2194
- /* Layer events */
2195
- 'layer.changeFlag': (layer, key, flags) => {
2196
- log.log(LOG_LEVEL_UPDATE_DETAIL, `${layer.id} ${key}: `, flags[key])();
2197
- },
2198
- 'layer.initialize': layer => {
2199
- log.log(LOG_LEVEL_MAJOR_UPDATE, `Initializing ${layer}`)();
2200
- },
2201
- 'layer.update': (layer, needsUpdate) => {
2202
- if (needsUpdate) {
2203
- const flags = layer.getChangeFlags();
2204
- log.log(LOG_LEVEL_MINOR_UPDATE, `Updating ${layer} because: ${Object.keys(flags).filter(key => flags[key]).join(', ')}`)();
2205
- } else {
2206
- log.log(LOG_LEVEL_INFO, `${layer} does not need update`)();
2207
- }
2208
- },
2209
- 'layer.matched': (layer, changed) => {
2210
- if (changed) {
2211
- log.log(LOG_LEVEL_INFO, `Matched ${layer}, state transfered`)();
2212
- }
2213
- },
2214
- 'layer.finalize': layer => {
2215
- log.log(LOG_LEVEL_MAJOR_UPDATE, `Finalizing ${layer}`)();
2216
- },
2217
- /* CompositeLayer events */
2218
- 'compositeLayer.renderLayers': (layer, updated, subLayers) => {
2219
- if (updated) {
2220
- log.log(LOG_LEVEL_MINOR_UPDATE, `Composite layer rendered new subLayers ${layer}`, subLayers)();
2221
- } else {
2222
- log.log(LOG_LEVEL_INFO, `Composite layer reused subLayers ${layer}`, subLayers)();
2223
- }
2224
- },
2225
- /* LayerManager events */
2226
- 'layerManager.setLayers': (layerManager, updated, layers) => {
2227
- if (updated) {
2228
- log.log(LOG_LEVEL_MINOR_UPDATE, `Updating ${layers.length} deck layers`)();
2229
- }
2230
- },
2231
- 'layerManager.activateViewport': (layerManager, viewport) => {
2232
- log.log(LOG_LEVEL_UPDATE_DETAIL, 'Viewport changed', viewport)();
2233
- },
2234
- /* AttributeManager events */
2235
- 'attributeManager.invalidate': (attributeManager, trigger, attributeNames) => {
2236
- log.log(LOG_LEVEL_MAJOR_UPDATE, attributeNames ? `invalidated attributes ${attributeNames} (${trigger}) for ${attributeManager.id}` : `invalidated all attributes for ${attributeManager.id}`)();
2237
- },
2238
- 'attributeManager.updateStart': attributeManager => {
2239
- logState.attributeUpdateMessages.length = 0;
2240
- logState.attributeManagerUpdateStart = Date.now();
2241
- },
2242
- 'attributeManager.updateEnd': (attributeManager, numInstances) => {
2243
- const timeMs = Math.round(Date.now() - logState.attributeManagerUpdateStart);
2244
- log.groupCollapsed(LOG_LEVEL_MINOR_UPDATE, `Updated attributes for ${numInstances} instances in ${attributeManager.id} in ${timeMs}ms`)();
2245
- for (const updateMessage of logState.attributeUpdateMessages) {
2246
- log.log(LOG_LEVEL_UPDATE_DETAIL, updateMessage)();
2247
- }
2248
- log.groupEnd(LOG_LEVEL_MINOR_UPDATE)();
2249
- },
2250
- /* Attribute events */
2251
- 'attribute.updateStart': attribute => {
2252
- logState.attributeUpdateStart = Date.now();
2253
- },
2254
- 'attribute.allocate': (attribute, numInstances) => {
2255
- const message = `${attribute.id} allocated ${numInstances}`;
2256
- logState.attributeUpdateMessages.push(message);
2257
- },
2258
- 'attribute.updateEnd': (attribute, numInstances) => {
2259
- const timeMs = Math.round(Date.now() - logState.attributeUpdateStart);
2260
- const message = `${attribute.id} updated ${numInstances} in ${timeMs}ms`;
2261
- logState.attributeUpdateMessages.push(message);
2262
- },
2263
- /* Render events */
2264
- 'deckRenderer.renderLayers': (deckRenderer, renderStats, opts) => {
2265
- const {
2266
- pass,
2267
- redrawReason,
2268
- stats
2269
- } = opts;
2270
- for (const status of renderStats) {
2271
- const {
2272
- totalCount,
2273
- visibleCount,
2274
- compositeCount,
2275
- pickableCount
2276
- } = status;
2277
- const primitiveCount = totalCount - compositeCount;
2278
- const hiddenCount = primitiveCount - visibleCount;
2279
- log.log(LOG_LEVEL_DRAW, `RENDER #${deckRenderer.renderCount} \
2280
- ${visibleCount} (of ${totalCount} layers) to ${pass} because ${redrawReason} \
2281
- (${hiddenCount} hidden, ${compositeCount} composite ${pickableCount} pickable)`)();
2282
- if (stats) {
2283
- stats.get('Redraw Layers').add(visibleCount);
2284
- }
2285
- }
2286
- }
2287
- });
2288
-
2289
- // Conditionally load default loggers in development mode
2290
- // eslint-disable-next-line
2291
- if (process.env.NODE_ENV !== 'production') {
2292
- getLoggers(log);
2293
- }
2294
- function register(handlers) {
2295
- }
2296
-
2297
- function isJSON(text) {
2298
- const firstChar = text[0];
2299
- const lastChar = text[text.length - 1];
2300
- return firstChar === '{' && lastChar === '}' || firstChar === '[' && lastChar === ']';
2301
- }
2302
- // A light weight version instead of @loaders.gl/json (stream processing etc.)
2303
- var jsonLoader = {
2304
- dataType: null,
2305
- batchType: null,
2306
- id: 'JSON',
2307
- name: 'JSON',
2308
- module: '',
2309
- version: '',
2310
- options: {},
2311
- extensions: ['json', 'geojson'],
2312
- mimeTypes: ['application/json', 'application/geo+json'],
2313
- testText: isJSON,
2314
- parseTextSync: JSON.parse
2315
- };
2316
-
2317
- // Copyright (c) 2015 - 2017 Uber Technologies, Inc.
2318
- function checkVersion() {
2319
- // Version detection using typescript plugin.
2320
- // Fallback for tests and SSR since global variable is defined by esbuild.
2321
- const version = "9.0.30" ;
2322
- // Note: a `deck` object not created by deck.gl may exist in the global scope
2323
- const existingVersion = globalThis.deck && globalThis.deck.VERSION;
2324
- if (existingVersion && existingVersion !== version) {
2325
- throw new Error(`deck.gl - multiple versions detected: ${existingVersion} vs ${version}`);
2326
- }
2327
- if (!existingVersion) {
2328
- log.log(1, `deck.gl ${version}`)();
2329
- globalThis.deck = {
2330
- ...globalThis.deck,
2331
- VERSION: version,
2332
- version,
2333
- log,
2334
- // experimental
2335
- _registerLoggers: register
2336
- };
2337
- registerLoaders([jsonLoader,
2338
- // @ts-expect-error non-standard Loader format
2339
- [ImageLoader, {
2340
- imagebitmap: {
2341
- premultiplyAlpha: 'none'
2342
- }
2343
- }]]);
2344
- }
2345
- return version;
2346
- }
2347
- const VERSION = checkVersion();
2348
-
2349
- const DEFAULT_TILE_RESOLUTION = 0.5;
2350
- const DEFAULT_AGGREGATION_RES_LEVEL_H3 = 4;
2351
- const DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN = 6;
2352
-
2353
- const isObject = x => x !== null && typeof x === 'object';
2354
- const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
2355
-
2356
- /**
2357
- *
2358
- * Custom error for reported errors in CARTO Maps API.
2359
- * Provides useful debugging information in console and context for applications.
2360
- *
2361
- */
2362
- class CartoAPIError extends Error {
2363
- constructor(error, errorContext, response, responseJson) {
2364
- let responseString = 'Failed to connect';
2365
- if (response) {
2366
- responseString = 'Server returned: ';
2367
- if (response.status === 400) {
2368
- responseString += 'Bad request';
2369
- } else if (response.status === 401 || response.status === 403) {
2370
- responseString += 'Unauthorized access';
2371
- } else if (response.status === 404) {
2372
- responseString += 'Not found';
2373
- } else {
2374
- responseString += 'Error';
2375
- }
2376
- responseString += ` (${response.status}):`;
2377
- }
2378
- responseString += ` ${error.message || error}`;
2379
- let message = `${errorContext.requestType} API request failed`;
2380
- message += `\n${responseString}`;
2381
- for (const key of Object.keys(errorContext)) {
2382
- if (key === 'requestType') continue; // eslint-disable-line no-continue
2383
- message += `\n${formatErrorKey(key)}: ${errorContext[key]}`;
2384
- }
2385
- message += '\n';
2386
- super(message);
2387
- this.name = 'CartoAPIError';
2388
- this.response = response;
2389
- this.responseJson = responseJson;
2390
- this.error = error;
2391
- this.errorContext = errorContext;
2392
- }
2393
- }
2394
- /**
2395
- * Converts camelCase to Camel Case
2396
- */
2397
- function formatErrorKey(key) {
2398
- return key.replace(/([A-Z])/g, ' $1').replace(/^./, s => s.toUpperCase());
2399
- }
2400
-
2401
- const DEFAULT_API_BASE_URL = 'https://gcp-us-east1.api.carto.com';
2402
- const DEFAULT_CLIENT = 'deck-gl-carto';
2403
- const V3_MINOR_VERSION = '3.4';
2404
- // Fastly default limit is 8192; leave some padding.
2405
- const DEFAULT_MAX_LENGTH_URL = 7000;
2406
-
2407
- function joinPath(...args) {
2408
- return args.map(part => part.endsWith('/') ? part.slice(0, -1) : part).join('/');
2409
- }
2410
- function buildV3Path(apiBaseUrl, version, endpoint, ...rest) {
2411
- return joinPath(apiBaseUrl, version, endpoint, ...rest);
2412
- }
2413
- function buildSourceUrl({
2414
- apiBaseUrl,
2415
- connectionName,
2416
- endpoint
2417
- }) {
2418
- return buildV3Path(apiBaseUrl, 'v3', 'maps', connectionName, endpoint);
2419
- }
2420
-
2421
- /**
2422
- * Parameters added to all requests issued with `requestWithParameters()`.
2423
- * These parameters override parameters already in the base URL, but not
2424
- * user-provided parameters.
2425
- */
2426
- const DEFAULT_PARAMETERS = {
2427
- v: V3_MINOR_VERSION,
2428
- deckglVersion: VERSION
2429
- };
2430
- const DEFAULT_HEADERS = {
2431
- Accept: 'application/json',
2432
- 'Content-Type': 'application/json'
2433
- };
2434
- const REQUEST_CACHE = new Map();
2435
- async function requestWithParameters({
2436
- baseUrl,
2437
- parameters = {},
2438
- headers: customHeaders = {},
2439
- errorContext,
2440
- maxLengthURL = DEFAULT_MAX_LENGTH_URL
2441
- }) {
2442
- parameters = {
2443
- ...DEFAULT_PARAMETERS,
2444
- ...parameters
2445
- };
2446
- baseUrl = excludeURLParameters(baseUrl, Object.keys(parameters));
2447
- const key = createCacheKey(baseUrl, parameters, customHeaders);
2448
- if (REQUEST_CACHE.has(key)) {
2449
- return REQUEST_CACHE.get(key);
2450
- }
2451
- const url = createURLWithParameters(baseUrl, parameters);
2452
- const headers = {
2453
- ...DEFAULT_HEADERS,
2454
- ...customHeaders
2455
- };
2456
- /* global fetch */
2457
- const fetchPromise = url.length > maxLengthURL ? fetch(baseUrl, {
2458
- method: 'POST',
2459
- body: JSON.stringify(parameters),
2460
- headers
2461
- }) : fetch(url, {
2462
- headers
2463
- });
2464
- let response;
2465
- let responseJson;
2466
- const jsonPromise = fetchPromise.then(_response => {
2467
- response = _response;
2468
- return response.json();
2469
- }).then(json => {
2470
- responseJson = json;
2471
- if (!response || !response.ok) {
2472
- throw new Error(json.error);
2473
- }
2474
- return json;
2475
- }).catch(error => {
2476
- REQUEST_CACHE.delete(key);
2477
- throw new CartoAPIError(error, errorContext, response, responseJson);
2478
- });
2479
- REQUEST_CACHE.set(key, jsonPromise);
2480
- return jsonPromise;
2481
- }
2482
- function createCacheKey(baseUrl, parameters, headers) {
2483
- const parameterEntries = Object.entries(parameters).sort(([a], [b]) => a > b ? 1 : -1);
2484
- const headerEntries = Object.entries(headers).sort(([a], [b]) => a > b ? 1 : -1);
2485
- return JSON.stringify({
2486
- baseUrl,
2487
- parameters: parameterEntries,
2488
- headers: headerEntries
2489
- });
2490
- }
2491
- /**
2492
- * Appends query string parameters to a URL. Existing URL parameters are kept,
2493
- * unless there is a conflict, in which case the new parameters override
2494
- * those already in the URL.
2495
- */
2496
- function createURLWithParameters(baseUrlString, parameters) {
2497
- const baseUrl = new URL(baseUrlString);
2498
- for (const [key, value] of Object.entries(parameters)) {
2499
- if (isPureObject(value) || Array.isArray(value)) {
2500
- baseUrl.searchParams.set(key, JSON.stringify(value));
2501
- } else {
2502
- baseUrl.searchParams.set(key, value.toString());
2503
- }
2504
- }
2505
- return baseUrl.toString();
2506
- }
2507
- /**
2508
- * Deletes query string parameters from a URL.
2509
- */
2510
- function excludeURLParameters(baseUrlString, parameters) {
2511
- const baseUrl = new URL(baseUrlString);
2512
- for (const param of parameters) {
2513
- if (baseUrl.searchParams.has(param)) {
2514
- baseUrl.searchParams.delete(param);
2515
- }
2516
- }
2517
- return baseUrl.toString();
2518
- }
2519
-
2520
- /* eslint-disable camelcase */
2521
- const SOURCE_DEFAULTS = {
2522
- apiBaseUrl: DEFAULT_API_BASE_URL,
2523
- clientId: DEFAULT_CLIENT,
2524
- format: 'tilejson',
2525
- headers: {},
2526
- maxLengthURL: DEFAULT_MAX_LENGTH_URL
2527
- };
2528
- async function baseSource(endpoint, options, urlParameters) {
2529
- const {
2530
- accessToken,
2531
- connectionName,
2532
- cache,
2533
- ...optionalOptions
2534
- } = options;
2535
- const mergedOptions = {
2536
- ...SOURCE_DEFAULTS,
2537
- accessToken,
2538
- connectionName,
2539
- endpoint
2540
- };
2541
- for (const key in optionalOptions) {
2542
- if (optionalOptions[key]) {
2543
- mergedOptions[key] = optionalOptions[key];
2544
- }
2545
- }
2546
- const baseUrl = buildSourceUrl(mergedOptions);
2547
- const {
2548
- clientId,
2549
- maxLengthURL,
2550
- format
2551
- } = mergedOptions;
2552
- const headers = {
2553
- Authorization: `Bearer ${options.accessToken}`,
2554
- ...options.headers
2555
- };
2556
- const parameters = {
2557
- client: clientId,
2558
- ...urlParameters
2559
- };
2560
- const errorContext = {
2561
- requestType: 'Map instantiation',
2562
- connection: options.connectionName,
2563
- type: endpoint,
2564
- source: JSON.stringify(parameters, undefined, 2)
2565
- };
2566
- const mapInstantiation = await requestWithParameters({
2567
- baseUrl,
2568
- parameters,
2569
- headers,
2570
- errorContext,
2571
- maxLengthURL
2572
- });
2573
- const dataUrl = mapInstantiation[format].url[0];
2574
- if (cache) {
2575
- cache.value = parseInt(new URL(dataUrl).searchParams.get('cache') || '', 10);
2576
- }
2577
- errorContext.requestType = 'Map data';
2578
- if (format === 'tilejson') {
2579
- const json = await requestWithParameters({
2580
- baseUrl: dataUrl,
2581
- headers,
2582
- errorContext,
2583
- maxLengthURL
2584
- });
2585
- if (accessToken) {
2586
- json.accessToken = accessToken;
2587
- }
2588
- return json;
2589
- }
2590
- return await requestWithParameters({
2591
- baseUrl: dataUrl,
2592
- headers,
2593
- errorContext,
2594
- maxLengthURL
2595
- });
2596
- }
2597
-
2598
- const boundaryQuerySource = async function (options) {
2599
- const {
2600
- columns,
2601
- filters,
2602
- tilesetTableName,
2603
- propertiesSqlQuery,
2604
- queryParameters
2605
- } = options;
2606
- const urlParameters = {
2607
- tilesetTableName,
2608
- propertiesSqlQuery
2609
- };
2610
- if (columns) {
2611
- urlParameters.columns = columns.join(',');
2612
- }
2613
- if (filters) {
2614
- urlParameters.filters = filters;
2615
- }
2616
- if (queryParameters) {
2617
- urlParameters.queryParameters = queryParameters;
2618
- }
2619
- return baseSource('boundary', options, urlParameters);
2620
- };
2621
-
2622
- const boundaryTableSource = async function (options) {
2623
- const {
2624
- filters,
2625
- tilesetTableName,
2626
- columns,
2627
- propertiesTableName
2628
- } = options;
2629
- const urlParameters = {
2630
- tilesetTableName,
2631
- propertiesTableName
2632
- };
2633
- if (columns) {
2634
- urlParameters.columns = columns.join(',');
2635
- }
2636
- if (filters) {
2637
- urlParameters.filters = filters;
2638
- }
2639
- return baseSource('boundary', options, urlParameters);
2640
- };
2641
-
2642
- /* eslint-disable camelcase */
2643
- const h3QuerySource$1 = async function (options) {
2644
- const {
2645
- aggregationExp,
2646
- aggregationResLevel = DEFAULT_AGGREGATION_RES_LEVEL_H3,
2647
- sqlQuery,
2648
- spatialDataColumn = 'h3',
2649
- queryParameters,
2650
- filters
2651
- } = options;
2652
- const urlParameters = {
2653
- aggregationExp,
2654
- spatialDataColumn,
2655
- spatialDataType: 'h3',
2656
- q: sqlQuery
2657
- };
2658
- if (aggregationResLevel) {
2659
- urlParameters.aggregationResLevel = String(aggregationResLevel);
2660
- }
2661
- if (queryParameters) {
2662
- urlParameters.queryParameters = queryParameters;
2663
- }
2664
- if (filters) {
2665
- urlParameters.filters = filters;
2666
- }
2667
- return baseSource('query', options, urlParameters);
2668
- };
2669
-
2670
- /* eslint-disable camelcase */
2671
- const h3TableSource$1 = async function (options) {
2672
- const {
2673
- aggregationExp,
2674
- aggregationResLevel = DEFAULT_AGGREGATION_RES_LEVEL_H3,
2675
- spatialDataColumn = 'h3',
2676
- tableName,
2677
- filters
2678
- } = options;
2679
- const urlParameters = {
2680
- aggregationExp,
2681
- name: tableName,
2682
- spatialDataColumn,
2683
- spatialDataType: 'h3'
2684
- };
2685
- if (aggregationResLevel) {
2686
- urlParameters.aggregationResLevel = String(aggregationResLevel);
2687
- }
2688
- if (filters) {
2689
- urlParameters.filters = filters;
2690
- }
2691
- return baseSource('table', options, urlParameters);
2692
- };
2693
-
2694
- const h3TilesetSource = async function (options) {
2695
- const {
2696
- tableName
2697
- } = options;
2698
- const urlParameters = {
2699
- name: tableName
2700
- };
2701
- return baseSource('tileset', options, urlParameters);
2702
- };
2703
-
2704
- const rasterSource = async function (options) {
2705
- const {
2706
- tableName,
2707
- filters
2708
- } = options;
2709
- const urlParameters = {
2710
- name: tableName
2711
- };
2712
- if (filters) {
2713
- urlParameters.filters = filters;
2714
- }
2715
- return baseSource('raster', options, urlParameters);
2716
- };
2717
-
2718
- /* eslint-disable camelcase */
2719
- const quadbinQuerySource$1 = async function (options) {
2720
- const {
2721
- aggregationExp,
2722
- aggregationResLevel = DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN,
2723
- sqlQuery,
2724
- spatialDataColumn = 'quadbin',
2725
- queryParameters,
2726
- filters
2727
- } = options;
2728
- const urlParameters = {
2729
- aggregationExp,
2730
- q: sqlQuery,
2731
- spatialDataColumn,
2732
- spatialDataType: 'quadbin'
2733
- };
2734
- if (aggregationResLevel) {
2735
- urlParameters.aggregationResLevel = String(aggregationResLevel);
2736
- }
2737
- if (queryParameters) {
2738
- urlParameters.queryParameters = queryParameters;
2739
- }
2740
- if (filters) {
2741
- urlParameters.filters = filters;
2742
- }
2743
- return baseSource('query', options, urlParameters);
2744
- };
2745
-
2746
- /* eslint-disable camelcase */
2747
- const quadbinTableSource$1 = async function (options) {
2748
- const {
2749
- aggregationExp,
2750
- aggregationResLevel = DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN,
2751
- spatialDataColumn = 'quadbin',
2752
- tableName,
2753
- filters
2754
- } = options;
2755
- const urlParameters = {
2756
- aggregationExp,
2757
- name: tableName,
2758
- spatialDataColumn,
2759
- spatialDataType: 'quadbin'
2760
- };
2761
- if (aggregationResLevel) {
2762
- urlParameters.aggregationResLevel = String(aggregationResLevel);
2763
- }
2764
- if (filters) {
2765
- urlParameters.filters = filters;
2766
- }
2767
- return baseSource('table', options, urlParameters);
2768
- };
2769
-
2770
- const quadbinTilesetSource = async function (options) {
2771
- const {
2772
- tableName
2773
- } = options;
2774
- const urlParameters = {
2775
- name: tableName
2776
- };
2777
- return baseSource('tileset', options, urlParameters);
2778
- };
2779
-
2780
- /* eslint-disable camelcase */
2781
- const vectorQuerySource$1 = async function (options) {
2782
- const {
2783
- columns,
2784
- filters,
2785
- spatialDataColumn = 'geom',
2786
- sqlQuery,
2787
- tileResolution = DEFAULT_TILE_RESOLUTION,
2788
- queryParameters
2789
- } = options;
2790
- const urlParameters = {
2791
- spatialDataColumn,
2792
- spatialDataType: 'geo',
2793
- tileResolution: tileResolution.toString(),
2794
- q: sqlQuery
2795
- };
2796
- if (columns) {
2797
- urlParameters.columns = columns.join(',');
2798
- }
2799
- if (filters) {
2800
- urlParameters.filters = filters;
2801
- }
2802
- if (queryParameters) {
2803
- urlParameters.queryParameters = queryParameters;
2804
- }
2805
- return baseSource('query', options, urlParameters);
2806
- };
2807
-
2808
- /* eslint-disable camelcase */
2809
- const vectorTableSource$1 = async function (options) {
2810
- const {
2811
- columns,
2812
- filters,
2813
- spatialDataColumn = 'geom',
2814
- tableName,
2815
- tileResolution = DEFAULT_TILE_RESOLUTION
2816
- } = options;
2817
- const urlParameters = {
2818
- name: tableName,
2819
- spatialDataColumn,
2820
- spatialDataType: 'geo',
2821
- tileResolution: tileResolution.toString()
2822
- };
2823
- if (columns) {
2824
- urlParameters.columns = columns.join(',');
2825
- }
2826
- if (filters) {
2827
- urlParameters.filters = filters;
2828
- }
2829
- return baseSource('table', options, urlParameters);
2830
- };
2831
-
2832
- const vectorTilesetSource = async function (options) {
2833
- const {
2834
- tableName
2835
- } = options;
2836
- const urlParameters = {
2837
- name: tableName
2838
- };
2839
- return baseSource('tileset', options, urlParameters);
2840
- };
2841
-
2842
- ({
2843
- boundaryQuerySource,
2844
- boundaryTableSource,
2845
- h3QuerySource: h3QuerySource$1,
2846
- h3TableSource: h3TableSource$1,
2847
- h3TilesetSource,
2848
- rasterSource,
2849
- quadbinQuerySource: quadbinQuerySource$1,
2850
- quadbinTableSource: quadbinTableSource$1,
2851
- quadbinTilesetSource,
2852
- vectorQuerySource: vectorQuerySource$1,
2853
- vectorTableSource: vectorTableSource$1,
2854
- vectorTilesetSource
2855
- });
2856
-
2857
983
  /** Wrapper adding Widget API support to [vectorTableSource](https://deck.gl/docs/api-reference/carto/data-sources). */
2858
984
 
2859
985
  /** Wrapper adding Widget API support to [quadbinQuerySource](https://deck.gl/docs/api-reference/carto/data-sources). */
2860
986
  const quadbinQuerySource = function (props) {
2861
987
  try {
2862
988
  assignDefaultProps(props);
2863
- return Promise.resolve(quadbinQuerySource$1(props)).then(function (response) {
989
+ return Promise.resolve(carto.quadbinQuerySource(props)).then(function (response) {
2864
990
  return {
2865
991
  ...response,
2866
992
  widgetSource: new WidgetQuerySource(props)
@@ -2874,7 +1000,7 @@ const quadbinQuerySource = function (props) {
2874
1000
  const quadbinTableSource = function (props) {
2875
1001
  try {
2876
1002
  assignDefaultProps(props);
2877
- return Promise.resolve(quadbinTableSource$1(props)).then(function (response) {
1003
+ return Promise.resolve(carto.quadbinTableSource(props)).then(function (response) {
2878
1004
  return {
2879
1005
  ...response,
2880
1006
  widgetSource: new WidgetTableSource(props)
@@ -2888,7 +1014,7 @@ const quadbinTableSource = function (props) {
2888
1014
  const h3QuerySource = function (props) {
2889
1015
  try {
2890
1016
  assignDefaultProps(props);
2891
- return Promise.resolve(h3QuerySource$1(props)).then(function (response) {
1017
+ return Promise.resolve(carto.h3QuerySource(props)).then(function (response) {
2892
1018
  return {
2893
1019
  ...response,
2894
1020
  widgetSource: new WidgetQuerySource(props)
@@ -2902,7 +1028,7 @@ const h3QuerySource = function (props) {
2902
1028
  const h3TableSource = function (props) {
2903
1029
  try {
2904
1030
  assignDefaultProps(props);
2905
- return Promise.resolve(h3TableSource$1(props)).then(function (response) {
1031
+ return Promise.resolve(carto.h3TableSource(props)).then(function (response) {
2906
1032
  return {
2907
1033
  ...response,
2908
1034
  widgetSource: new WidgetTableSource(props)
@@ -2916,7 +1042,7 @@ const h3TableSource = function (props) {
2916
1042
  const vectorQuerySource = function (props) {
2917
1043
  try {
2918
1044
  assignDefaultProps(props);
2919
- return Promise.resolve(vectorQuerySource$1(props)).then(function (response) {
1045
+ return Promise.resolve(carto.vectorQuerySource(props)).then(function (response) {
2920
1046
  return {
2921
1047
  ...response,
2922
1048
  widgetSource: new WidgetQuerySource(props)
@@ -2929,7 +1055,7 @@ const vectorQuerySource = function (props) {
2929
1055
  const vectorTableSource = function (props) {
2930
1056
  try {
2931
1057
  assignDefaultProps(props);
2932
- return Promise.resolve(vectorTableSource$1(props)).then(function (response) {
1058
+ return Promise.resolve(carto.vectorTableSource(props)).then(function (response) {
2933
1059
  return {
2934
1060
  ...response,
2935
1061
  widgetSource: new WidgetTableSource(props)