@loaders.gl/json 3.0.10 → 3.0.14

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///../worker-utils/src/lib/env-utils/assert.ts","webpack:////home/user/apps/loaders.gl/node_modules/@probe.gl/stats/dist/esm/utils/hi-res-timestamp.js","webpack:///../worker-utils/src/lib/env-utils/version.ts","webpack:///(webpack)/buildin/global.js","webpack:///../schema/src/lib/schema/index.ts","webpack:////home/user/apps/loaders.gl/node_modules/process/browser.js","webpack:///../worker-utils/src/lib/env-utils/globals.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-thread.ts","webpack:///../worker-utils/src/lib/worker-utils/get-transfer-list.ts","webpack:///./src/lib/jsonpath/jsonpath.ts","webpack:///./src/lib/parse-json.ts","webpack:///./src/lib/parse-json-in-batches.ts","webpack:///../schema/src/lib/table/row-table-batch-aggregator.ts","webpack:///../schema/src/lib/utils/row-utils.ts","webpack:///../schema/src/lib/table/columnar-table-batch-aggregator.ts","webpack:///../loader-utils/src/lib/env-utils/assert.ts","webpack:///../worker-utils/src/index.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-job.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-farm.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-pool.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-body.ts","webpack:///../worker-utils/src/lib/worker-api/get-worker-url.ts","webpack:///../worker-utils/src/lib/async-queue/async-queue.ts","webpack:///../loader-utils/src/lib/binary-utils/get-first-characters.ts","webpack:///../loader-utils/src/lib/binary-utils/array-buffer-utils.ts","webpack:///../loader-utils/src/lib/binary-utils/memory-copy-utils.ts","webpack:///./src/lib/clarinet/clarinet.js","webpack:///./src/bundle.ts","webpack:///./src/index.ts","webpack:///./src/json-loader.ts","webpack:///../schema/src/index.ts","webpack:///../schema/src/lib/table/table-batch-builder.ts","webpack:///../schema/src/lib/table/base-table-batch-aggregator.ts","webpack:///../schema/src/category/mesh/mesh-utils.ts","webpack:///../schema/src/lib/schema/impl/schema.ts","webpack:///../schema/src/lib/utils/assert.ts","webpack:///../schema/src/lib/schema/impl/field.ts","webpack:///../schema/src/lib/schema/impl/type.ts","webpack:///../schema/src/lib/schema/impl/enum.ts","webpack:///../schema/src/lib/schema-utils/deduce-table-schema.ts","webpack:///../schema/src/lib/schema-utils/get-type-info.ts","webpack:///../schema/src/lib/schema-utils/type-utils.ts","webpack:///../schema/src/lib/utils/async-queue.ts","webpack:///../loader-utils/src/index.ts","webpack:///../loader-utils/src/lib/env-utils/globals.ts","webpack:///../loader-utils/src/lib/worker-loader-utils/create-loader-worker.ts","webpack:///../worker-utils/src/lib/worker-utils/get-loadable-worker-url.ts","webpack:///../worker-utils/src/lib/worker-api/process-on-worker.ts","webpack:///../worker-utils/src/lib/worker-utils/remove-nontransferable-options.ts","webpack:///../worker-utils/src/lib/worker-api/create-worker.ts","webpack:///../worker-utils/src/lib/worker-api/validate-worker-version.ts","webpack:///../worker-utils/src/lib/library-utils/library-utils.ts","webpack:///../loader-utils/src/lib/worker-loader-utils/parse-with-worker.ts","webpack:///../loader-utils/src/lib/parser-utils/parse-json.ts","webpack:///../loader-utils/src/lib/binary-utils/binary-copy-utils.ts","webpack:///../loader-utils/src/lib/binary-utils/encode-utils.ts","webpack:///../loader-utils/src/lib/iterators/text-iterators.ts","webpack:///../loader-utils/src/lib/iterators/async-iteration.ts","webpack:///../loader-utils/src/lib/request-utils/request-scheduler.ts","webpack:///../loader-utils/src/lib/path-utils/path.ts","webpack:///../loader-utils/src/lib/path-utils/file-aliases.ts","webpack:///../loader-utils/src/lib/binary-utils/buffer-utils.ts","webpack:///../loader-utils/src/json-loader.ts","webpack:///./src/lib/parser/streaming-json-parser.ts","webpack:///./src/lib/parser/json-parser.ts","webpack:///./src/geojson-loader.ts","webpack:///../gis/src/index.ts","webpack:///../gis/src/lib/geojson-to-binary.ts","webpack:///../gis/src/lib/binary-to-geojson.ts","webpack:///../gis/src/lib/transform.ts","webpack:////home/user/apps/loaders.gl/node_modules/@probe.gl/stats/dist/esm/lib/stat.js","webpack:////home/user/apps/loaders.gl/node_modules/@probe.gl/stats/dist/esm/lib/stats.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","condition","message","Error","getHiResTimestamp","timestamp","window","performance","now","process","hrtime","timeParts","Date","g","this","Function","e","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","setTimeout","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","length","concat","drainQueue","timeout","len","run","marker","runClearTimeout","Item","array","noop","nextTick","args","Array","arguments","push","apply","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","globals","self","global","document","self_","window_","global_","document_","isBrowser","String","isWorker","importScripts","isMobile","orientation","matches","exec","nodeVersion","parseFloat","NOOP","WorkerThread","props","source","url","assert","onMessage","onError","error","console","log","worker","_createBrowserWorker","Worker","terminate","terminated","Boolean","data","transferList","getTransferList","postMessage","event","lineno","colno","_loadableURL","getLoadableWorkerURL","onmessage","onerror","_getErrorFromErrorEvent","onmessageerror","isTransferable","ArrayBuffer","MessagePort","ImageBitmap","OffscreenCanvas","recursive","transfers","transfersSet","Set","add","buffer","isView","undefined","from","JSONPath","path","isArray","split","join","pop","other","shift","field","jsonText","options","json","JSON","parse","table","getFirstArray","values","binaryAsyncIterator","asyncIterator","makeTextDecoderIterator","metadata","jsonpaths","isFirstChunk","shape","tableBatchBuilder","TableBatchBuilder","parser","StreamingJSONParser","chunk","rows","write","jsonpath","getStreamingJsonPathAsString","initialBatch","batchType","bytesUsed","container","getPartialResult","row","addRow","batch","getFullBatch","chunkComplete","getFinalBatch","finalBatch","RowTableBatchAggregator","schema","_headers","index","cursor","Number","isFinite","rowObject","convertToObjectRow","addObjectRow","arrayRows","rowArray","convertToArrayRow","addArrayRow","objectRows","slice","arrayRow","headers","objectRow","ColumnarTableBatchAggregator","_reallocateColumns","fieldName","columns","_pruneColumns","allocated","ArrayType","type","Float32Array","oldColumn","typedArray","set","entries","columnName","column","NullWorker","id","VERSION","null","WorkerJob","jobName","workerThread","isRunning","_resolve","_reject","result","Promise","resolve","reject","payload","DEFAULT_PROPS","maxConcurrency","maxMobileConcurrency","onDebug","reuseWorkers","WorkerFarm","Map","setProps","workerPools","isSupported","_workerFarm","destroy","_getWorkerPoolProps","workerPool","WorkerPool","idleQueue","forEach","isDestroyed","job","done","startPromise","onStart","jobQueue","_startQueuedJob","_getAvailableWorker","queuedJob","backlog","returnWorkerToQueue","count","_getMaxConcurrency","toLowerCase","onMessageWrapperMap","WorkerBody","isKnownMessage","onMessageWrapper","addEventListener","removeEventListener","startsWith","warning","workerOptions","workerFile","workerUrl","_workerType","versionTag","AsyncQueue","_values","_settlers","_closed","enqueue","settler","getMagicString","arrayBuffer","byteOffset","byteLength","dataView","DataView","magic","fromCharCode","getUint8","node","toArrayBuffer","text","TextEncoder","encode","_toArrayBuffer","arrayBuffer1","arrayBuffer2","array1","Uint8Array","array2","sources","sourceArrays","map","source2","reduce","offset","sourceArray","typedArrays","arrays","TypedArrayConstructor","constructor","sumLength","acc","subArray","subarray","targetBuffer","sourceBuffer","targetArray","target","targetOffset","srcByteOffset","srcByteLength","padToNBytes","padding","MAX_BUFFER_LENGTH","MAX_SAFE_INTEGER","DEBUG","CDEBUG","buffers","textNode","numberNode","S","STATE","BEGIN","VALUE","OPEN_OBJECT","CLOSE_OBJECT","OPEN_ARRAY","CLOSE_ARRAY","TEXT_ESCAPE","STRING","BACKSLASH","END","OPEN_KEY","CLOSE_KEY","TRUE","TRUE2","TRUE3","FALSE","FALSE2","FALSE3","FALSE4","NULL","NULL2","NULL3","NUMBER_DECIMAL_POINT","NUMBER_DIGIT","s_","Char","stringTokenPattern","ClarinetParser","_initialize","_clearBuffers","bufferCheckPosition","q","closed","closedRoot","sawRoot","tag","state","stack","position","line","slashed","unicodeI","unicodeS","depth","onready","onopenobject","onkey","oncloseobject","onopenarray","onclosearray","onvalue","onend","onchunkparsed","closeValue","end","charCodeAt","isWhitespace","emitNode","starti","STRING_BIGLOOP","parseInt","substring","lastIndex","reResult","indexOf","closeNumber","maxAllowed","Math","max","maxActual","closeText","checkBufferLength","opt","trim","normalize","replace","textopts","er","moduleExports","require","_global","loaders","assign","DEFAULT_JSON_LOADER_OPTIONS","JSONLoader","extensions","mimeTypes","category","parseTextSync","parseInBatches","jsonOptions","TextDecoder","decode","DEFAULT_OPTIONS","batchSize","batchDebounceMs","limit","_limitMB","totalLength","totalBytes","limitReached","rowBytes","_estimateRowMB","aggregator","TableBatchType","_getTableBatchType","isChunkComplete","_isFull","_getBatch","keys","rowCount","lastBatchEmittedMs","normalizedBatch","getBatch","batchCount","BaseTableBatchAggregator","ArrowBatch","attributes","size","attributeName","attribute","BYTES_PER_ELEMENT","minX","Infinity","minY","minZ","maxX","maxY","maxZ","positions","POSITION","x","y","z","Schema","fields","usedNames","warn","checkNames","compareTo","nameMap","columnNames","selectedFields","filter","columnIndices","schemaOrFields","otherSchema","mergeMaps","fieldMap","m1","m2","Field","nullable","typeId","DataType","Type","NONE","Null","Int","Float","Binary","Utf8","Bool","Decimal","Time","Timestamp","Interval","List","Struct","Union","FixedSizeBinary","FixedSizeList","Dictionary","isSigned","bitWidth","Int8","Int16","Int32","Int64","Uint8","Uint16","Uint32","Uint64","Precision","precision","Float16","Float32","Float64","DateUnit","DAY","MILLISECOND","unit","DateDay","DateMillisecond","TimeUnit","SECOND","MICROSECOND","NANOSECOND","TimeSecond","TimeMillisecond","timezone","TimestampSecond","TimestampMillisecond","TimestampMicrosecond","TimestampNanosecond","IntervalUnit","DAY_TIME","YEAR_MONTH","IntervalDayTime","IntervalYearMonth","listSize","child","children","valueType","deduceTypeFromValue","deducedSchema","rowTable","deduceSchemaForRowTable","columnarTable","deduceSchemaForColumnarTable","arrowTypeLike","typeName","toString","typeEnumName","getTypeKey","ReverseType","typeKey","Int8Array","Int16Array","Uint16Array","Int32Array","Uint32Array","Float64Array","ArrayQueue","dequeue","asyncIterable","iterator","next","loader","input","parseData","context","parseOnMainThread","requestId","parseSync","textDecoder","workerURL","workerURLCache","getLoadableWorkerURLFromSource","getLoadableWorkerURLFromURL","workerSource","blob","Blob","URL","createObjectURL","getWorkerName","getWorkerURL","workerFarm","getWorkerFarm","getWorkerPool","startJob","transferableOptions","removeNontransferableOptions","v","cache","stringify","has","err","processInBatches","processOnMainThread","inputBatches","resultIterator","close","coreVersion","workerVersion","loadLibraryPromises","libraryUrl","moduleName","getLibraryUrl","loadLibraryFromFile","library","CDN","endsWith","fetch","response","requireFromFile","scriptSource","loadLibraryFromString","requireFromString","eval","script","createElement","appendChild","createTextNode","body","string","_","getFirstCharacters","stringBuffer","copyPaddedArrayBufferToDataView","paddedLength","padLength","setUint8","byteAlignment","ceil","whitespace","binary","arrayBufferIterator","stream","textIterator","textEncoder","previous","eolIndex","lineIterator","counter","visitor","arrayBuffers","concatenateArrayBuffers","strings","throttleRequests","maxRequests","RequestScheduler","stats","Stats","handle","getPriority","requestMap","request","priority","promise","requestQueue","_issueNewRequests","isDone","activeRequestCount","deferredUpdate","_issueNewRequestsAsync","freeSlots","_updateAllRequests","_issueRequest","_updateRequest","splice","sort","a","b","slashIndex","lastIndexOf","substr","parts","separator","part","RegExp","prefix","pathPrefix","aliases","fileAliases","filename","alias","replacement","isBuffer","toBuffer","_typecheckJSONLoader","jsonPaths","_extendParser","streamingArray","topLevelObject","streamingJsonPath","currentPath","getJsonPath","equals","_matchJSONPath","clone","_openArray","_openObject","JSONParser","reset","_initializeParser","previousStates","currentState","freeze","newContainer","_pushOrSet","_parser","_closeObject","_closeArray","DEFAULT_GEOJSON_LOADER_OPTIONS","geojson","gis","format","GeoJSONWorkerLoader","GeoJSONLoader","geojsonIterator","makeBinaryGeometryIterator","geojsonToBinary","features","firstPassData","firstPass","secondPass","coordLength","numericPropKeys","PositionDataType","TEST_EXPORTS","pointPositionsCount","pointFeaturesCount","linePositionsCount","linePathsCount","lineFeaturesCount","polygonPositionsCount","polygonObjectsCount","polygonRingsCount","polygonFeaturesCount","coordLengths","feature","geometry","coordinates","point","coord","flatten","polygon","properties","val","k","GlobalFeatureIdsDataType","points","globalFeatureIds","featureIds","numericProps","lines","pathIndices","polygons","polygonIndices","primitivePolygonIndices","propName","indexMap","pointPosition","pointFeature","linePosition","linePath","lineFeature","polygonPosition","polygonObject","polygonRing","polygonFeature","handlePoint","keepStringProperties","handleMultiPoint","handleLineString","handleMultiLineString","handlePolygon","handleMultiPolygon","returnObj","geomType","numericProp","makeAccessorObjects","coords","fillNumericProperties","fillCoords","nPositions","fill","ring","numericPropName","numericKeys","includes","startVertex","parseFeatures","dataArray","lastValue","currValue","parseFeature","parseFeatureCollection","normalizeInput","binaryToGeometry","startIndex","endIndex","ringToGeoJson","pointToGeoJson","multi","ringCoordinates","lineStringToGeoJson","polygonToGeoJson","startRingIndex","endRingIndex","startPolygonIndex","endPolygonIndex","polygonCoordinates","unexpectedInput","parseType","parseProperties","parseFields","j","globalFeatureId","getSingleFeature","transformBinaryGeometryPositions","binaryGeometry","fn","transformedCoord","coordMap","isCoord","item","binaryFeatures","transformCoordinate","sampleSize","samples","addCount","subtractCount","_count","_samples","_checkSampling","time","_time","lastTiming","_startTime","_timerPending","addTime","lastSampleCount","lastSampleTime","_initializeStats","seal","_getOrCreate","stat","average","getAverageTime","hz","getHz"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GA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C,QACE,IAAK,MAAMtC,KAAOsB,KAAK2nB,MACrB3nB,KAAK2nB,MAAMjpB,GAAKqsB,QAGlB,OAAO/qB,KAGT,QAAQsyB,GACN,IAAK,MAAM5zB,KAAOsB,KAAK2nB,MACrB2K,EAAGtyB,KAAK2nB,MAAMjpB,IAIlB,WACE,MAAMwJ,EAAQ,GASd,OARAlI,KAAKkO,QAAQ6lB,IACX7rB,EAAM6rB,EAAKr2B,MAAQ,CACjB01B,KAAMW,EAAKX,MAAQ,EACnBtkB,MAAOilB,EAAKjlB,OAAS,EACrBklB,QAASD,EAAKE,kBAAoB,EAClCC,GAAIH,EAAKI,SAAW,KAGjBjsB,EAGT,iBAAiByf,EAAQ,IACvBA,EAAMzZ,QAAQ6lB,GAAQ/zB,KAAK8zB,aAAaC,IAG1C,aAAaA,GACX,IAAKA,IAASA,EAAKr2B,KACjB,OAAO,KAGT,MAAM,KACJA,EAAI,KACJiO,GACEooB,EAUJ,OARK/zB,KAAK2nB,MAAMjqB,KAEZsC,KAAK2nB,MAAMjqB,GADTq2B,aAAgB,EACCA,EAEA,IAAI,EAAKr2B,EAAMiO,IAI/B3L,KAAK2nB,MAAMjqB","file":"dist.es5.min.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 28);\n","// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\n\n/** Throws an `Error` with the optional `message` if `condition` is falsy */\nexport function assert(condition: any, message?: string): void {\n if (!condition) {\n throw new Error(message || 'loaders.gl assertion failed.');\n }\n}\n","export default function getHiResTimestamp() {\n let timestamp;\n\n if (typeof window !== 'undefined' && window.performance) {\n timestamp = window.performance.now();\n } else if (typeof process !== 'undefined' && process.hrtime) {\n const timeParts = process.hrtime();\n timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;\n } else {\n timestamp = Date.now();\n }\n\n return timestamp;\n}\n//# sourceMappingURL=hi-res-timestamp.js.map","// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\n// __VERSION__ is injected by babel-plugin-version-inline\n\n// Change to `latest` on production branches\nconst DEFAULT_VERSION = 'beta';\ndeclare let __VERSION__;\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : DEFAULT_VERSION;\nif (typeof __VERSION__ === 'undefined') {\n // eslint-disable-next-line\n console.error(\n 'loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN.'\n );\n}\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","/*\nexport {\n Schema,\n Field,\n DataType,\n Null,\n Bool,\n Int,\n Int8,\n Int16,\n Int32,\n Int64,\n Uint8,\n Uint16,\n Uint32,\n Uint64,\n Float,\n Float16,\n Float32,\n Float64,\n Binary,\n Utf8,\n Date,\n DateDay,\n DateMillisecond,\n Time,\n TimeSecond,\n TimeMillisecond,\n TimeMicrosecond,\n TimeNanosecond,\n Timestamp,\n TimestampSecond,\n TimestampMillisecond,\n TimestampMicrosecond,\n TimestampNanosecond,\n Interval,\n IntervalDayTime,\n IntervalYearMonth,\n FixedSizeList\n} from 'apache-arrow';\n*/\nexport {default as Schema} from './impl/schema';\nexport {default as Field} from './impl/field';\nexport {Type} from './impl/type';\nexport {\n DataType,\n Null,\n Bool,\n Int,\n Int8,\n Int16,\n Int32,\n Int64,\n Uint8,\n Uint16,\n Uint32,\n Uint64,\n Float,\n Float16,\n Float32,\n Float64,\n Binary,\n Utf8,\n Date,\n DateDay,\n DateMillisecond,\n Time,\n TimeSecond,\n TimeMillisecond,\n // TimeMicrosecond,\n // TimeNanosecond,\n Timestamp,\n TimestampSecond,\n TimestampMillisecond,\n TimestampMicrosecond,\n TimestampNanosecond,\n Interval,\n IntervalDayTime,\n IntervalYearMonth,\n FixedSizeList\n} from './impl/type';\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","// Purpose: include this in your module to avoids adding dependencies on\n// micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\nconst self_: {[key: string]: any} = globals.self || globals.window || globals.global || {};\nconst window_: {[key: string]: any} = globals.window || globals.self || globals.global || {};\nconst global_: {[key: string]: any} = globals.global || globals.self || globals.window || {};\nconst document_: {[key: string]: any} = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\n/** true if running in the browser, false if running in Node.js */\nexport const isBrowser: boolean =\n // @ts-ignore process.browser\n typeof process !== 'object' || String(process) !== '[object process]' || process.browser;\n\n/** true if running on a worker thread */\nexport const isWorker: boolean = typeof importScripts === 'function';\n\n/** true if running on a mobile device */\nexport const isMobile: boolean =\n typeof window !== 'undefined' && typeof window.orientation !== 'undefined';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\n\n/** Version of Node.js if running under Node, otherwise 0 */\nexport const nodeVersion: number = (matches && parseFloat(matches[1])) || 0;\n","import {assert} from '../env-utils/assert';\nimport {getLoadableWorkerURL} from '../worker-utils/get-loadable-worker-url';\nimport {getTransferList} from '../worker-utils/get-transfer-list';\n\nconst NOOP = () => {};\n\nexport type WorkerThreadProps = {\n name: string;\n source?: string;\n url?: string;\n};\n\n/**\n * Represents one worker thread\n */\nexport default class WorkerThread {\n readonly name: string;\n readonly source: string | undefined;\n readonly url: string | undefined;\n terminated: boolean = false;\n worker: Worker;\n onMessage: (message: any) => void;\n onError: (error: Error) => void;\n\n private _loadableURL: string = '';\n\n static isSupported(): boolean {\n return typeof Worker !== 'undefined';\n }\n\n constructor(props: WorkerThreadProps) {\n const {name, source, url} = props;\n assert(source || url); // Either source or url must be defined\n this.name = name;\n this.source = source;\n this.url = url;\n this.onMessage = NOOP;\n this.onError = (error) => console.log(error); // eslint-disable-line\n\n this.worker = this._createBrowserWorker();\n }\n\n /**\n * Terminate this worker thread\n * @note Can free up significant memory\n */\n destroy(): void {\n this.onMessage = NOOP;\n this.onError = NOOP;\n // @ts-ignore\n this.worker.terminate();\n this.terminated = true;\n }\n\n get isRunning() {\n return Boolean(this.onMessage);\n }\n\n /**\n * Send a message to this worker thread\n * @param data any data structure, ideally consisting mostly of transferrable objects\n * @param transferList If not supplied, calculated automatically by traversing data\n */\n postMessage(data: any, transferList?: any[]): void {\n transferList = transferList || getTransferList(data);\n // @ts-ignore\n this.worker.postMessage(data, transferList);\n }\n\n // PRIVATE\n\n /**\n * Generate a standard Error from an ErrorEvent\n * @param {ErrorEvent} event\n */\n _getErrorFromErrorEvent(event) {\n // Note Error object does not have the expected fields if loading failed completely\n // https://developer.mozilla.org/en-US/docs/Web/API/Worker#Event_handlers\n // https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent\n let message = 'Failed to load ';\n message += `worker ${this.name}. `;\n if (event.message) {\n message += `${event.message} in `;\n }\n // const hasFilename = event.filename && !event.filename.startsWith('blob:');\n // message += hasFilename ? event.filename : this.source.slice(0, 100);\n if (event.lineno) {\n message += `:${event.lineno}:${event.colno}`;\n }\n return new Error(message);\n }\n\n /**\n * Creates a worker thread on the browser\n */\n _createBrowserWorker() {\n this._loadableURL = getLoadableWorkerURL({source: this.source, url: this.url});\n const worker = new Worker(this._loadableURL, {name: this.name});\n\n worker.onmessage = (event) => {\n if (!event.data) {\n this.onError(new Error('No data received'));\n } else {\n this.onMessage(event.data);\n }\n };\n // This callback represents an uncaught exception in the worker thread\n worker.onerror = (error) => {\n this.onError(this._getErrorFromErrorEvent(error));\n this.terminated = true;\n };\n // TODO - not clear when this would be called, for now just log in case it happens\n worker.onmessageerror = (event) => console.error(event); // eslint-disable-line\n\n return worker;\n }\n}\n","// NOTE - there is a copy of this function is both in core and loader-utils\n// core does not need all the utils in loader-utils, just this one.\n\n/**\n * Returns an array of Transferrable objects that can be used with postMessage\n * https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage\n * @param object data to be sent via postMessage\n * @param recursive - not for application use\n * @param transfers - not for application use\n * @returns a transfer list that can be passed to postMessage\n */\nexport function getTransferList(\n object: any,\n recursive: boolean = true,\n transfers?: Set<any>\n): Transferable[] {\n // Make sure that items in the transfer list is unique\n const transfersSet = transfers || new Set();\n\n if (!object) {\n // ignore\n } else if (isTransferable(object)) {\n transfersSet.add(object);\n } else if (isTransferable(object.buffer)) {\n // Typed array\n transfersSet.add(object.buffer);\n } else if (ArrayBuffer.isView(object)) {\n // object is a TypeArray viewing into a SharedArrayBuffer (not transferable)\n // Do not iterate through the content in this case\n } else if (recursive && typeof object === 'object') {\n for (const key in object) {\n // Avoid perf hit - only go one level deep\n getTransferList(object[key], recursive, transfersSet);\n }\n }\n\n // If transfers is defined, is internal recursive call\n // Otherwise it's called by the user\n return transfers === undefined ? Array.from(transfersSet) : [];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Transferable\nfunction isTransferable(object) {\n if (!object) {\n return false;\n }\n if (object instanceof ArrayBuffer) {\n return true;\n }\n if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {\n return true;\n }\n if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {\n return true;\n }\n if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {\n return true;\n }\n return false;\n}\n","/**\n * A parser for a minimal subset of the jsonpath standard\n * Full JSON path parsers for JS exist but are quite large (bundle size)\n *\n * Supports\n *\n * `$.component.component.component`\n */\nexport default class JSONPath {\n path: string[];\n\n constructor(path: JSONPath | string[] | string | null = null) {\n this.path = ['$'];\n\n if (path instanceof JSONPath) {\n // @ts-ignore\n this.path = [...path.path];\n return;\n }\n\n if (Array.isArray(path)) {\n this.path.push(...path);\n return;\n }\n\n // Parse a string as a JSONPath\n if (typeof path === 'string') {\n this.path = path.split('.');\n if (this.path[0] !== '$') {\n throw new Error('JSONPaths must start with $');\n }\n }\n }\n\n clone(): JSONPath {\n return new JSONPath(this);\n }\n\n toString(): string {\n return this.path.join('.');\n }\n\n push(name: string): void {\n this.path.push(name);\n }\n\n pop() {\n return this.path.pop();\n }\n\n set(name: string): void {\n this.path[this.path.length - 1] = name;\n }\n\n equals(other: JSONPath): boolean {\n if (!this || !other || this.path.length !== other.path.length) {\n return false;\n }\n\n for (let i = 0; i < this.path.length; ++i) {\n if (this.path[i] !== other.path[i]) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Sets the value pointed at by path\n * TODO - handle root path\n * @param object\n * @param value\n */\n setFieldAtPath(object, value) {\n const path = [...this.path];\n path.shift();\n const field = path.pop();\n for (const component of path) {\n object = object[component];\n }\n // @ts-ignore\n object[field] = value;\n }\n\n /**\n * Gets the value pointed at by path\n * TODO - handle root path\n * @param object\n */\n getFieldAtPath(object) {\n const path = [...this.path];\n path.shift();\n const field = path.pop();\n for (const component of path) {\n object = object[component];\n }\n // @ts-ignore\n return object[field];\n }\n}\n","import type {JSONLoaderOptions} from '../json-loader';\n\nexport default function parseJSONSync(jsonText: string, options: JSONLoaderOptions) {\n try {\n const json = JSON.parse(jsonText);\n if (options.json?.table) {\n return getFirstArray(json) || json;\n }\n return json;\n } catch (error) {\n throw new Error('JSONLoader: failed to parse JSON');\n }\n}\n\nfunction getFirstArray(json) {\n if (Array.isArray(json)) {\n return json;\n }\n if (json && typeof json === 'object') {\n for (const value of Object.values(json)) {\n const array = getFirstArray(value);\n if (array) {\n return array;\n }\n }\n }\n return null;\n}\n","import type {Batch} from '@loaders.gl/schema';\nimport type {JSONLoaderOptions} from '../json-loader';\nimport {TableBatchBuilder} from '@loaders.gl/schema';\nimport {makeTextDecoderIterator} from '@loaders.gl/loader-utils';\nimport StreamingJSONParser from './parser/streaming-json-parser';\n\n// TODO - support batch size 0 = no batching/single batch?\n// eslint-disable-next-line max-statements, complexity\nexport default async function* parseJSONInBatches(\n binaryAsyncIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>,\n options: JSONLoaderOptions\n): AsyncIterable<Batch> {\n const asyncIterator = makeTextDecoderIterator(binaryAsyncIterator);\n\n const {metadata} = options;\n const {jsonpaths} = options.json || {};\n\n let isFirstChunk: boolean = true;\n\n // TODO fix Schema deduction\n const schema = null; // new Schema([]);\n const shape = options?.json?.shape || 'row-table';\n // @ts-ignore\n const tableBatchBuilder = new TableBatchBuilder(schema, {\n ...options,\n shape\n });\n\n const parser = new StreamingJSONParser({jsonpaths});\n\n for await (const chunk of asyncIterator) {\n const rows = parser.write(chunk);\n\n const jsonpath = rows.length > 0 && parser.getStreamingJsonPathAsString();\n\n if (rows.length > 0 && isFirstChunk) {\n if (metadata) {\n const initialBatch: Batch = {\n // Common fields\n shape,\n batchType: 'partial-result',\n data: [],\n length: 0,\n bytesUsed: 0,\n // JSON additions\n container: parser.getPartialResult(),\n jsonpath\n };\n yield initialBatch;\n }\n isFirstChunk = false;\n // schema = deduceSchema(rows);\n }\n\n // Add the row\n for (const row of rows) {\n tableBatchBuilder.addRow(row);\n // If a batch has been completed, emit it\n const batch = tableBatchBuilder.getFullBatch({jsonpath});\n if (batch) {\n yield batch;\n }\n }\n\n tableBatchBuilder.chunkComplete(chunk);\n const batch = tableBatchBuilder.getFullBatch({jsonpath});\n if (batch) {\n yield batch;\n }\n }\n\n // yield final batch\n const jsonpath = parser.getStreamingJsonPathAsString();\n const batch = tableBatchBuilder.getFinalBatch({jsonpath});\n if (batch) {\n yield batch;\n }\n\n if (metadata) {\n const finalBatch: Batch = {\n shape,\n batchType: 'final-result',\n container: parser.getPartialResult(),\n jsonpath: parser.getStreamingJsonPathAsString(),\n data: [],\n length: 0\n // schema: null\n };\n yield finalBatch;\n }\n}\n","import type {Schema} from '../schema';\nimport type {TableBatch} from '../../category/table';\n// import type {ArrayRowTableBatch, ObjectRowTableBatch} from '../../category/table';\nimport {convertToArrayRow, convertToObjectRow} from '../utils/row-utils';\nimport {TableBatchAggregator, TableBatchOptions} from './table-batch-aggregator';\n\nconst DEFAULT_ROW_COUNT = 100;\n\nexport default class RowTableBatchAggregator implements TableBatchAggregator {\n schema: Schema;\n options: TableBatchOptions;\n\n length: number = 0;\n objectRows: {[columnName: string]: any} | null = null;\n arrayRows: any[] | null = null;\n cursor: number = 0;\n private _headers: string[] = [];\n\n constructor(schema: Schema, options: TableBatchOptions) {\n this.options = options;\n this.schema = schema;\n\n // schema is an array if there're no headers\n // object if there are headers\n if (!Array.isArray(schema)) {\n this._headers = [];\n for (const key in schema) {\n this._headers[schema[key].index] = schema[key].name;\n }\n }\n }\n\n rowCount(): number {\n return this.length;\n }\n\n addArrayRow(row: any[], cursor?: number): void {\n if (Number.isFinite(cursor)) {\n this.cursor = cursor as number;\n }\n\n // eslint-disable-next-line default-case\n switch (this.options.shape) {\n case 'object-row-table':\n const rowObject = convertToObjectRow(row, this._headers);\n this.addObjectRow(rowObject, cursor);\n break;\n case 'array-row-table':\n this.arrayRows = this.arrayRows || new Array(DEFAULT_ROW_COUNT);\n this.arrayRows[this.length] = row;\n this.length++;\n break;\n }\n }\n\n addObjectRow(row: {[columnName: string]: any}, cursor?: number): void {\n if (Number.isFinite(cursor)) {\n this.cursor = cursor as number;\n }\n\n // eslint-disable-next-line default-case\n switch (this.options.shape) {\n case 'array-row-table':\n const rowArray = convertToArrayRow(row, this._headers);\n this.addArrayRow(rowArray, cursor);\n break;\n case 'object-row-table':\n this.objectRows = this.objectRows || new Array(DEFAULT_ROW_COUNT);\n this.objectRows[this.length] = row;\n this.length++;\n break;\n }\n }\n\n getBatch(): TableBatch | null {\n let rows = this.arrayRows || this.objectRows;\n if (!rows) {\n return null;\n }\n\n rows = rows.slice(0, this.length);\n this.arrayRows = null;\n this.objectRows = null;\n\n return {\n shape: this.options.shape,\n batchType: 'data',\n data: rows,\n length: this.length,\n schema: this.schema,\n cursor: this.cursor\n };\n }\n}\n","/** Convert an object row to an array row */\nexport function convertToObjectRow(\n arrayRow: any[],\n headers: string[]\n): {[columnName: string]: any} {\n if (!arrayRow) {\n throw new Error('null row');\n }\n if (!headers) {\n throw new Error('no headers');\n }\n const objectRow = {};\n for (let i = 0; i < headers.length; i++) {\n objectRow[headers[i]] = arrayRow[i];\n }\n return objectRow;\n}\n\n/** Convert an object row to an array row */\nexport function convertToArrayRow(\n objectRow: {[columnName: string]: any},\n headers: string[]\n): any[] {\n if (!objectRow) {\n throw new Error('null row');\n }\n if (!headers) {\n throw new Error('no headers');\n }\n const arrayRow = new Array(headers.length);\n for (let i = 0; i < headers.length; i++) {\n arrayRow[i] = objectRow[headers[i]];\n }\n return arrayRow;\n}\n","import type {Schema} from '../schema';\nimport type {ColumnarTableBatch, ArrowTableBatch} from '../../category/table';\nimport {TableBatchAggregator} from './table-batch-aggregator';\n\ntype ColumnarTableBatchOptions = {};\n\nconst DEFAULT_ROW_COUNT = 100;\n\nexport default class ColumnarTableBatchAggregator implements TableBatchAggregator {\n schema: Schema;\n length: number = 0;\n allocated: number = 0;\n columns: {[columnName: string]: any[]} = {};\n\n constructor(schema: Schema, options: ColumnarTableBatchOptions) {\n this.schema = schema;\n this._reallocateColumns();\n }\n\n rowCount(): number {\n return this.length;\n }\n\n addArrayRow(row: any[]) {\n // If user keeps pushing rows beyond batch size, reallocate\n this._reallocateColumns();\n let i = 0;\n // TODO what if no csv header, columns not populated?\n for (const fieldName in this.columns) {\n this.columns[fieldName][this.length] = row[i++];\n }\n this.length++;\n }\n\n addObjectRow(row: {[columnName: string]: any}): void {\n // If user keeps pushing rows beyond batch size, reallocate\n this._reallocateColumns();\n for (const fieldName in row) {\n this.columns[fieldName][this.length] = row[fieldName];\n }\n this.length++;\n }\n\n getBatch(): ColumnarTableBatch | ArrowTableBatch | null {\n this._pruneColumns();\n const columns = Array.isArray(this.schema) ? this.columns : {};\n\n // schema is an array if there're no headers\n // object if there are headers\n // columns should match schema format\n if (!Array.isArray(this.schema)) {\n for (const fieldName in this.schema) {\n const field = this.schema[fieldName];\n columns[field.name] = this.columns[field.index];\n }\n }\n\n this.columns = {};\n\n const batch: ColumnarTableBatch = {\n shape: 'columnar-table',\n batchType: 'data',\n data: columns,\n schema: this.schema,\n length: this.length\n };\n\n return batch;\n }\n\n // HELPERS\n\n _reallocateColumns() {\n if (this.length < this.allocated) {\n return;\n }\n\n // @ts-ignore TODO\n this.allocated = this.allocated > 0 ? (this.allocated *= 2) : DEFAULT_ROW_COUNT;\n this.columns = {};\n\n for (const fieldName in this.schema) {\n const field = this.schema[fieldName];\n const ArrayType = field.type || Float32Array;\n const oldColumn = this.columns[field.index];\n\n if (oldColumn && ArrayBuffer.isView(oldColumn)) {\n // Copy the old data to the new array\n const typedArray = new ArrayType(this.allocated);\n typedArray.set(oldColumn);\n this.columns[field.index] = typedArray;\n } else if (oldColumn) {\n // Plain array\n oldColumn.length = this.allocated;\n this.columns[field.index] = oldColumn;\n } else {\n // Create new\n this.columns[field.index] = new ArrayType(this.allocated);\n }\n }\n }\n\n _pruneColumns() {\n for (const [columnName, column] of Object.entries(this.columns)) {\n this.columns[columnName] = column.slice(0, this.length);\n }\n }\n}\n","/**\n * Throws an `Error` with the optional `message` if `condition` is falsy\n * @note Replacement for the external assert method to reduce bundle size\n */\nexport function assert(condition: any, message?: string): void {\n if (!condition) {\n throw new Error(message || 'loader assertion failed.');\n }\n}\n","import type {WorkerObject} from './types';\nimport {VERSION} from './lib/env-utils/version';\n\n// TYPES\nexport type {\n WorkerObject,\n WorkerOptions,\n // Protocol\n WorkerMessage,\n WorkerMessageType,\n WorkerMessageData,\n WorkerMessagePayload\n} from './types';\n\n// GENERAL UTILS\nexport {assert} from './lib/env-utils/assert';\nexport {isBrowser, isWorker} from './lib/env-utils/globals';\n\n// WORKER UTILS - TYPES\nexport {default as WorkerJob} from './lib/worker-farm/worker-job';\nexport {default as WorkerThread} from './lib/worker-farm/worker-thread';\n\n// WORKER FARMS\nexport {default as WorkerFarm} from './lib/worker-farm/worker-farm';\nexport {default as WorkerPool} from './lib/worker-farm/worker-pool';\nexport {default as WorkerBody} from './lib/worker-farm/worker-body';\n\nexport {processOnWorker, canProcessOnWorker} from './lib/worker-api/process-on-worker';\nexport {createWorker} from './lib/worker-api/create-worker';\n\n// WORKER UTILS - EXPORTS\nexport {getWorkerURL} from './lib/worker-api/get-worker-url';\nexport {validateWorkerVersion} from './lib/worker-api/validate-worker-version';\nexport {getTransferList} from './lib/worker-utils/get-transfer-list';\n\n// LIBRARY UTILS\nexport {getLibraryUrl, loadLibrary} from './lib/library-utils/library-utils';\n\n// PARSER UTILS\nexport {default as AsyncQueue} from './lib/async-queue/async-queue';\n\n// PROCESS UTILS\nexport {default as ChildProcessProxy} from './lib/process-utils/child-process-proxy';\n\n// WORKER OBJECTS\n\n/** A null worker to test that worker processing is functional */\nexport const NullWorker: WorkerObject = {\n id: 'null',\n name: 'null',\n module: 'worker-utils',\n version: VERSION,\n options: {\n null: {}\n }\n};\n","import type {WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport WorkerThread from './worker-thread';\nimport {assert} from '../env-utils/assert';\n\n/**\n * Represents one Job handled by a WorkerPool or WorkerFarm\n */\nexport default class WorkerJob {\n readonly name: string;\n readonly workerThread: WorkerThread;\n isRunning: boolean;\n /** Promise that resolves when Job is done */\n readonly result: Promise<any>;\n\n private _resolve: (value: any) => void;\n private _reject: (reason?: any) => void;\n\n constructor(jobName: string, workerThread: WorkerThread) {\n this.name = jobName;\n this.workerThread = workerThread;\n this.isRunning = true;\n this._resolve = () => {};\n this._reject = () => {};\n this.result = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n /**\n * Send a message to the job's worker thread\n * @param data any data structure, ideally consisting mostly of transferrable objects\n */\n postMessage(type: WorkerMessageType, payload: WorkerMessagePayload): void {\n this.workerThread.postMessage({\n source: 'loaders.gl', // Lets worker ignore unrelated messages\n type,\n payload\n });\n }\n\n /**\n * Call to resolve the `result` Promise with the supplied value\n */\n done(value): void {\n assert(this.isRunning);\n this.isRunning = false;\n this._resolve(value);\n }\n\n /**\n * Call to reject the `result` Promise with the supplied error\n */\n error(error): void {\n assert(this.isRunning);\n this.isRunning = false;\n this._reject(error);\n }\n}\n","import WorkerPool from './worker-pool';\nimport WorkerThread from './worker-thread';\n\n/**\n * @param maxConcurrency {number} - max count of workers\n */\nexport type WorkerFarmProps = {\n maxConcurrency?: number;\n maxMobileConcurrency?: number;\n reuseWorkers?: boolean;\n onDebug?: () => void;\n};\n\nconst DEFAULT_PROPS: WorkerFarmProps = {\n maxConcurrency: 3,\n maxMobileConcurrency: 1,\n onDebug: () => {},\n reuseWorkers: true\n};\n\n/**\n * Process multiple jobs with a \"farm\" of different workers in worker pools.\n */\nexport default class WorkerFarm {\n private props: WorkerFarmProps;\n private workerPools = new Map<string, WorkerPool>();\n // singleton\n private static _workerFarm?: WorkerFarm;\n\n /** Check if Workers are supported */\n static isSupported(): boolean {\n return WorkerThread.isSupported();\n }\n\n /** Get the singleton instance of the global worker farm */\n static getWorkerFarm(props: WorkerFarmProps = {}): WorkerFarm {\n WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});\n WorkerFarm._workerFarm.setProps(props);\n return WorkerFarm._workerFarm;\n }\n\n /** get global instance with WorkerFarm.getWorkerFarm() */\n private constructor(props: WorkerFarmProps) {\n this.props = {...DEFAULT_PROPS};\n this.setProps(props);\n /** @type Map<string, WorkerPool>} */\n this.workerPools = new Map();\n }\n\n /**\n * Terminate all workers in the farm\n * @note Can free up significant memory\n */\n destroy(): void {\n for (const workerPool of this.workerPools.values()) {\n workerPool.destroy();\n }\n }\n\n /**\n * Set props used when initializing worker pools\n * @param props\n */\n setProps(props: WorkerFarmProps): void {\n this.props = {...this.props, ...props};\n // Update worker pool props\n for (const workerPool of this.workerPools.values()) {\n workerPool.setProps(this._getWorkerPoolProps());\n }\n }\n\n /**\n * Returns a worker pool for the specified worker\n * @param options - only used first time for a specific worker name\n * @param options.name - the name of the worker - used to identify worker pool\n * @param options.url -\n * @param options.source -\n * @example\n * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...);\n */\n getWorkerPool(options: {name: string; source?: string; url?: string}): WorkerPool {\n const {name, source, url} = options;\n let workerPool = this.workerPools.get(name);\n if (!workerPool) {\n workerPool = new WorkerPool({\n name,\n source,\n url\n });\n workerPool.setProps(this._getWorkerPoolProps());\n this.workerPools.set(name, workerPool);\n }\n return workerPool;\n }\n\n _getWorkerPoolProps() {\n return {\n maxConcurrency: this.props.maxConcurrency,\n maxMobileConcurrency: this.props.maxMobileConcurrency,\n reuseWorkers: this.props.reuseWorkers,\n onDebug: this.props.onDebug\n };\n }\n}\n","import type {WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport {isMobile} from '../env-utils/globals';\nimport WorkerThread from './worker-thread';\nimport WorkerJob from './worker-job';\n\n/** WorkerPool onDebug Callback Parameters */\ntype OnDebugParameters = {\n message: string;\n worker: string;\n name: string;\n job: string;\n backlog: number;\n workerThread: WorkerThread;\n};\n\n/** WorkerPool Properties */\nexport type WorkerPoolProps = {\n name?: string;\n source?: string; // | Function;\n url?: string;\n maxConcurrency?: number;\n maxMobileConcurrency?: number;\n onDebug?: (options: OnDebugParameters) => any;\n reuseWorkers?: boolean;\n};\n\n/** Private helper types */\ntype OnMessage = (job: WorkerJob, type: WorkerMessageType, payload: WorkerMessagePayload) => void;\ntype OnError = (job: WorkerJob, error: Error) => void;\n\ntype QueuedJob = {\n name: string;\n onMessage: OnMessage;\n onError: OnError;\n onStart: (value: any) => void; // Resolve job start promise\n};\n\n/**\n * Process multiple data messages with small pool of identical workers\n */\nexport default class WorkerPool {\n name: string = 'unnamed';\n source?: string; // | Function;\n url?: string;\n maxConcurrency: number = 1;\n maxMobileConcurrency: number = 1;\n onDebug: (options: OnDebugParameters) => any = () => {};\n reuseWorkers: boolean = true;\n\n private props: WorkerPoolProps = {};\n private jobQueue: QueuedJob[] = [];\n private idleQueue: WorkerThread[] = [];\n private count = 0;\n private isDestroyed = false;\n\n /**\n * @param processor - worker function\n * @param maxConcurrency - max count of workers\n */\n constructor(props: WorkerPoolProps) {\n this.source = props.source;\n this.url = props.url;\n this.setProps(props);\n }\n\n /**\n * Terminates all workers in the pool\n * @note Can free up significant memory\n */\n destroy(): void {\n // Destroy idle workers, active Workers will be destroyed on completion\n this.idleQueue.forEach((worker) => worker.destroy());\n this.isDestroyed = true;\n }\n\n setProps(props: WorkerPoolProps) {\n this.props = {...this.props, ...props};\n\n if (props.name !== undefined) {\n this.name = props.name;\n }\n if (props.maxConcurrency !== undefined) {\n this.maxConcurrency = props.maxConcurrency;\n }\n if (props.maxMobileConcurrency !== undefined) {\n this.maxMobileConcurrency = props.maxMobileConcurrency;\n }\n if (props.reuseWorkers !== undefined) {\n this.reuseWorkers = props.reuseWorkers;\n }\n if (props.onDebug !== undefined) {\n this.onDebug = props.onDebug;\n }\n }\n\n async startJob(\n name: string,\n onMessage: OnMessage = (job, type, data) => job.done(data),\n onError: OnError = (job, error) => job.error(error)\n ): Promise<WorkerJob> {\n // Promise resolves when thread starts working on this job\n const startPromise = new Promise<WorkerJob>((onStart) => {\n // Promise resolves when thread completes or fails working on this job\n this.jobQueue.push({name, onMessage, onError, onStart});\n return this;\n });\n this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises\n return await startPromise;\n }\n\n // PRIVATE\n\n /**\n * Starts first queued job if worker is available or can be created\n * Called when job is started and whenever a worker returns to the idleQueue\n */\n async _startQueuedJob(): Promise<void> {\n if (!this.jobQueue.length) {\n return;\n }\n\n const workerThread = this._getAvailableWorker();\n if (!workerThread) {\n return;\n }\n\n // We have a worker, dequeue and start the job\n const queuedJob = this.jobQueue.shift();\n if (queuedJob) {\n // Emit a debug event\n // @ts-ignore\n this.onDebug({\n message: 'Starting job',\n name: queuedJob.name,\n workerThread,\n backlog: this.jobQueue.length\n });\n\n // Create a worker job to let the app access thread and manage job completion\n const job = new WorkerJob(queuedJob.name, workerThread);\n\n // Set the worker thread's message handlers\n workerThread.onMessage = (data) => queuedJob.onMessage(job, data.type, data.payload);\n workerThread.onError = (error) => queuedJob.onError(job, error);\n\n // Resolve the start promise so that the app can start sending messages to worker\n queuedJob.onStart(job);\n\n // Wait for the app to signal that the job is complete, then return worker to queue\n try {\n await job.result;\n } finally {\n this.returnWorkerToQueue(workerThread);\n }\n }\n }\n\n /**\n * Returns a worker to the idle queue\n * Destroys the worker if\n * - pool is destroyed\n * - if this pool doesn't reuse workers\n * - if maxConcurrency has been lowered\n * @param worker\n */\n returnWorkerToQueue(worker: WorkerThread) {\n const shouldDestroyWorker =\n this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();\n\n if (shouldDestroyWorker) {\n worker.destroy();\n this.count--;\n } else {\n this.idleQueue.push(worker);\n }\n\n if (!this.isDestroyed) {\n this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises\n }\n }\n\n /**\n * Returns idle worker or creates new worker if maxConcurrency has not been reached\n */\n _getAvailableWorker(): WorkerThread | null {\n // If a worker has completed and returned to the queue, it can be used\n if (this.idleQueue.length > 0) {\n return this.idleQueue.shift() || null;\n }\n\n // Create fresh worker if we haven't yet created the max amount of worker threads for this worker source\n if (this.count < this._getMaxConcurrency()) {\n this.count++;\n const name = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`;\n return new WorkerThread({name, source: this.source, url: this.url});\n }\n\n // No worker available, have to wait\n return null;\n }\n\n _getMaxConcurrency() {\n return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;\n }\n}\n","import type {WorkerMessageData, WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport {getTransferList} from '../worker-utils/get-transfer-list';\n\nconst onMessageWrapperMap = new Map();\n\n/**\n * Type safe wrapper for worker code\n */\nexport default class WorkerBody {\n /*\n * (type: WorkerMessageType, payload: WorkerMessagePayload) => any\n */\n static set onmessage(onMessage: (type: WorkerMessageType, payload: WorkerMessagePayload) => any) {\n // eslint-disable-next-line no-restricted-globals\n self.onmessage = (message) => {\n if (!isKnownMessage(message)) {\n return;\n }\n\n // Confusingly the message itself also has a 'type' field which is always set to 'message'\n const {type, payload} = message.data;\n onMessage(type, payload);\n };\n }\n\n static addEventListener(\n onMessage: (type: WorkerMessageType, payload: WorkerMessagePayload) => any\n ) {\n let onMessageWrapper = onMessageWrapperMap.get(onMessage);\n\n if (!onMessageWrapper) {\n onMessageWrapper = (message) => {\n if (!isKnownMessage(message)) {\n return;\n }\n\n // Confusingly the message itself also has a 'type' field which is always set to 'message'\n const {type, payload} = message.data;\n onMessage(type, payload);\n };\n }\n\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('message', onMessageWrapper);\n }\n\n static removeEventListener(\n onMessage: (type: WorkerMessageType, payload: WorkerMessagePayload) => any\n ) {\n const onMessageWrapper = onMessageWrapperMap.get(onMessage);\n onMessageWrapperMap.delete(onMessage);\n // eslint-disable-next-line no-restricted-globals\n self.removeEventListener('message', onMessageWrapper);\n }\n\n /**\n * Send a message from a worker to creating thread (main thread)\n * @param type\n * @param payload\n */\n static postMessage(type: WorkerMessageType, payload: WorkerMessagePayload): void {\n if (self) {\n const data: WorkerMessageData = {source: 'loaders.gl', type, payload};\n const transferList = getTransferList(payload);\n // eslint-disable-next-line no-restricted-globals\n // @ts-ignore\n self.postMessage(data, transferList);\n }\n }\n}\n\n// Filter out noise messages sent to workers\nfunction isKnownMessage(message) {\n const {type, data} = message;\n return (\n type === 'message' &&\n data &&\n typeof data.source === 'string' &&\n data.source.startsWith('loaders.gl')\n );\n}\n","import type {WorkerObject, WorkerOptions} from '../../types';\nimport {assert} from '../env-utils/assert';\nimport {VERSION as __VERSION__} from '../env-utils/version';\n\nconst NPM_TAG = 'latest';\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : NPM_TAG;\n\n/**\n * Gets worker object's name (for debugging in Chrome thread inspector window)\n */\nexport function getWorkerName(worker: WorkerObject): string {\n const warning = worker.version !== VERSION ? ` (worker-utils@${VERSION})` : '';\n return `${worker.name}@${worker.version}${warning}`;\n}\n\n/**\n * Generate a worker URL based on worker object and options\n * @returns A URL to one of the following:\n * - a published worker on unpkg CDN\n * - a local test worker\n * - a URL provided by the user in options\n */\nexport function getWorkerURL(worker: WorkerObject, options: WorkerOptions = {}): string {\n const workerOptions = options[worker.id] || {};\n\n const workerFile = `${worker.id}-worker.js`;\n\n let url = workerOptions.workerUrl;\n\n // If URL is test, generate local loaders.gl url\n // @ts-ignore _workerType\n if (options._workerType === 'test') {\n url = `modules/${worker.module}/dist/${workerFile}`;\n }\n\n // If url override is not provided, generate a URL to published version on npm CDN unpkg.com\n if (!url) {\n // GENERATE\n let version = worker.version;\n // On master we need to load npm alpha releases published with the `beta` tag\n if (version === 'latest') {\n // throw new Error('latest worker version specified');\n version = NPM_TAG;\n }\n const versionTag = version ? `@${version}` : '';\n url = `https://unpkg.com/@loaders.gl/${worker.module}${versionTag}/dist/${workerFile}`;\n }\n\n assert(url);\n\n // Allow user to override location\n return url;\n}\n","// From https://github.com/rauschma/async-iter-demo/tree/master/src under MIT license\n// http://2ality.com/2016/10/asynchronous-iteration.html\n\n/**\n * Async Queue\n * - AsyncIterable: An async iterator can be\n * - Values can be pushed onto the queue\n * @example\n * const asyncQueue = new AsyncQueue();\n * setTimeout(() => asyncQueue.enqueue('tick'), 1000);\n * setTimeout(() => asyncQueue.enqueue(new Error('done')), 10000);\n * for await (const value of asyncQueue) {\n * console.log(value); // tick\n * }\n */\nexport default class AsyncQueue<T> {\n private _values: any[];\n private _settlers: any[];\n private _closed: boolean;\n\n constructor() {\n this._values = []; // enqueues > dequeues\n this._settlers = []; // dequeues > enqueues\n this._closed = false;\n }\n\n /** Return an async iterator for this queue */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this;\n }\n\n /** Push a new value - the async iterator will yield a promise resolved to this value */\n push(value: T): void {\n return this.enqueue(value);\n }\n\n /**\n * Push a new value - the async iterator will yield a promise resolved to this value\n * Add an error - the async iterator will yield a promise rejected with this value\n */\n enqueue(value: T | Error): void {\n if (this._closed) {\n throw new Error('Closed');\n }\n\n if (this._settlers.length > 0) {\n if (this._values.length > 0) {\n throw new Error('Illegal internal state');\n }\n const settler = this._settlers.shift();\n if (value instanceof Error) {\n settler.reject(value);\n } else {\n settler.resolve({value});\n }\n } else {\n this._values.push(value);\n }\n }\n\n /** Indicate that we not waiting for more values - The async iterator will be done */\n close(): void {\n while (this._settlers.length > 0) {\n const settler = this._settlers.shift();\n settler.resolve({done: true});\n }\n this._closed = true;\n }\n\n // ITERATOR IMPLEMENTATION\n\n /** @returns a Promise for an IteratorResult */\n next(): Promise<IteratorResult<T, any>> {\n // If values in queue, yield the first value\n if (this._values.length > 0) {\n const value = this._values.shift();\n if (value instanceof Error) {\n return Promise.reject(value);\n }\n return Promise.resolve({done: false, value});\n }\n\n // If queue is closed, the iterator is done\n if (this._closed) {\n if (this._settlers.length > 0) {\n throw new Error('Illegal internal state');\n }\n return Promise.resolve({done: true, value: undefined});\n }\n\n // Yield a promise that waits for new values to be enqueued\n return new Promise((resolve, reject) => {\n this._settlers.push({resolve, reject});\n });\n }\n}\n","export function getFirstCharacters(data, length = 5): string {\n if (typeof data === 'string') {\n return data.slice(0, length);\n } else if (ArrayBuffer.isView(data)) {\n // Typed Arrays can have offsets into underlying buffer\n return getMagicString(data.buffer, data.byteOffset, length);\n } else if (data instanceof ArrayBuffer) {\n const byteOffset = 0;\n return getMagicString(data, byteOffset, length);\n }\n return '';\n}\n\nexport function getMagicString(\n arrayBuffer: ArrayBuffer,\n byteOffset: number,\n length: number\n): string {\n if (arrayBuffer.byteLength <= byteOffset + length) {\n return '';\n }\n const dataView = new DataView(arrayBuffer);\n let magic = '';\n for (let i = 0; i < length; i++) {\n magic += String.fromCharCode(dataView.getUint8(byteOffset + i));\n }\n return magic;\n}\n","import {TypedArray} from '../../types';\nimport * as node from '../node/buffer-utils.node';\n\n/**\n * Convert an object to an array buffer\n */\nexport function toArrayBuffer(data: any): ArrayBuffer {\n // Note: Should be called first, Buffers can trigger other detections below\n if (node.toArrayBuffer) {\n // TODO - per docs we should just be able to call buffer.buffer, but there are issues\n data = node.toArrayBuffer(data);\n }\n\n if (data instanceof ArrayBuffer) {\n return data;\n }\n\n // Careful - Node Buffers will look like ArrayBuffers (keep after isBuffer)\n if (ArrayBuffer.isView(data)) {\n return data.buffer;\n }\n\n if (typeof data === 'string') {\n const text = data;\n const uint8Array = new TextEncoder().encode(text);\n return uint8Array.buffer;\n }\n\n // HACK to support Blob polyfill\n if (data && typeof data === 'object' && data._toArrayBuffer) {\n return data._toArrayBuffer();\n }\n\n throw new Error('toArrayBuffer');\n}\n\n/**\n * compare two binary arrays for equality\n * @param {ArrayBuffer} a\n * @param {ArrayBuffer} b\n * @param {number} byteLength\n */\nexport function compareArrayBuffers(\n arrayBuffer1: ArrayBuffer,\n arrayBuffer2: ArrayBuffer,\n byteLength?: number\n): boolean {\n byteLength = byteLength || arrayBuffer1.byteLength;\n if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {\n return false;\n }\n const array1 = new Uint8Array(arrayBuffer1);\n const array2 = new Uint8Array(arrayBuffer2);\n for (let i = 0; i < array1.length; ++i) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Concatenate a sequence of ArrayBuffers\n * @return A concatenated ArrayBuffer\n */\nexport function concatenateArrayBuffers(...sources: (ArrayBuffer | Uint8Array)[]): ArrayBuffer {\n // Make sure all inputs are wrapped in typed arrays\n const sourceArrays = sources.map((source2) =>\n source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2\n );\n\n // Get length of all inputs\n const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);\n\n // Allocate array with space for all inputs\n const result = new Uint8Array(byteLength);\n\n // Copy the subarrays\n let offset = 0;\n for (const sourceArray of sourceArrays) {\n result.set(sourceArray, offset);\n offset += sourceArray.byteLength;\n }\n\n // We work with ArrayBuffers, discard the typed array wrapper\n return result.buffer;\n}\n\n/**\n * Concatenate arbitrary count of typed arrays\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays\n * @param {...*} arrays - list of arrays. All arrays should be the same type\n * @return A concatenated TypedArray\n */\nexport function concatenateTypedArrays<T>(...typedArrays: T[]): T {\n // @ts-ignore\n const arrays = typedArrays as TypedArray[];\n // @ts-ignore\n const TypedArrayConstructor = (arrays && arrays.length > 1 && arrays[0].constructor) || null;\n if (!TypedArrayConstructor) {\n throw new Error(\n '\"concatenateTypedArrays\" - incorrect quantity of arguments or arguments have incompatible data types'\n );\n }\n\n const sumLength = arrays.reduce((acc, value) => acc + value.length, 0);\n // @ts-ignore typescript does not like dynamic constructors\n const result = new TypedArrayConstructor(sumLength);\n let offset = 0;\n for (const array of arrays) {\n result.set(array, offset);\n offset += array.length;\n }\n return result;\n}\n\n/**\n * Copy a view of an ArrayBuffer into new ArrayBuffer with byteOffset = 0\n * @param arrayBuffer\n * @param byteOffset\n * @param byteLength\n */\nexport function sliceArrayBuffer(\n arrayBuffer: ArrayBuffer,\n byteOffset: number,\n byteLength?: number\n): ArrayBuffer {\n const subArray =\n byteLength !== undefined\n ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength)\n : new Uint8Array(arrayBuffer).subarray(byteOffset);\n const arrayCopy = new Uint8Array(subArray);\n return arrayCopy.buffer;\n}\n","import {assert} from '../env-utils/assert';\n\n/**\n * Calculate new size of an arrayBuffer to be aligned to an n-byte boundary\n * This function increases `byteLength` by the minimum delta,\n * allowing the total length to be divided by `padding`\n * @param byteLength\n * @param padding\n */\nexport function padToNBytes(byteLength: number, padding: number): number {\n assert(byteLength >= 0); // `Incorrect 'byteLength' value: ${byteLength}`\n assert(padding > 0); // `Incorrect 'padding' value: ${padding}`\n return (byteLength + (padding - 1)) & ~(padding - 1);\n}\n\n/**\n * Creates a new Uint8Array based on two different ArrayBuffers\n * @param targetBuffer The first buffer.\n * @param sourceBuffer The second buffer.\n * @return The new ArrayBuffer created out of the two.\n */\nexport function copyArrayBuffer(\n targetBuffer: ArrayBuffer,\n sourceBuffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number = sourceBuffer.byteLength\n): ArrayBuffer {\n const targetArray = new Uint8Array(targetBuffer, byteOffset, byteLength);\n const sourceArray = new Uint8Array(sourceBuffer);\n targetArray.set(sourceArray);\n return targetBuffer;\n}\n\n/**\n * Copy from source to target at the targetOffset\n *\n * @param source - The data to copy\n * @param target - The destination to copy data into\n * @param targetOffset - The start offset into target to place the copied data\n * @returns the new offset taking into account proper padding\n */\nexport function copyToArray(source: ArrayBuffer | any, target: any, targetOffset: number): number {\n let sourceArray;\n\n if (source instanceof ArrayBuffer) {\n sourceArray = new Uint8Array(source);\n } else {\n // Pack buffer onto the big target array\n //\n // 'source.data.buffer' could be a view onto a larger buffer.\n // We MUST use this constructor to ensure the byteOffset and byteLength is\n // set to correct values from 'source.data' and not the underlying\n // buffer for target.set() to work properly.\n const srcByteOffset = source.byteOffset;\n const srcByteLength = source.byteLength;\n // In gltf parser it is set as \"arrayBuffer\" instead of \"buffer\"\n // https://github.com/visgl/loaders.gl/blob/1e3a82a0a65d7b6a67b1e60633453e5edda2960a/modules/gltf/src/lib/parse-gltf.js#L85\n sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);\n }\n\n // Pack buffer onto the big target array\n target.set(sourceArray, targetOffset);\n\n return targetOffset + padToNBytes(sourceArray.byteLength, 4);\n}\n","/* eslint-disable */\n// @ts-nocheck\nconst env = {};\n\nexport const EVENTS = [\n 'value',\n 'string',\n 'key',\n 'openobject',\n 'closeobject',\n 'openarray',\n 'closearray',\n 'error',\n 'end',\n 'ready'\n];\n\n// Removes the MAX_BUFFER_LENGTH, originally set to 64 * 1024\nconst MAX_BUFFER_LENGTH = Number.MAX_SAFE_INTEGER;\nconst DEBUG = env.CDEBUG === 'debug';\n\nconst buffers = {\n textNode: undefined,\n numberNode: ''\n};\n\nlet S = 0;\n\nconst STATE = {\n BEGIN: S++,\n VALUE: S++, // general stuff\n OPEN_OBJECT: S++, // {\n CLOSE_OBJECT: S++, // }\n OPEN_ARRAY: S++, // [\n CLOSE_ARRAY: S++, // ]\n TEXT_ESCAPE: S++, // \\ stuff\n STRING: S++, // \"\"\n BACKSLASH: S++,\n END: S++, // No more stack\n OPEN_KEY: S++, // , \"a\"\n CLOSE_KEY: S++, // :\n TRUE: S++, // r\n TRUE2: S++, // u\n TRUE3: S++, // e\n FALSE: S++, // a\n FALSE2: S++, // l\n FALSE3: S++, // s\n FALSE4: S++, // e\n NULL: S++, // u\n NULL2: S++, // l\n NULL3: S++, // l\n NUMBER_DECIMAL_POINT: S++, // .\n NUMBER_DIGIT: S++ // [0-9]\n};\n\nfor (var s_ in STATE) STATE[STATE[s_]] = s_;\n\n// switcharoo\nS = STATE;\n\nconst Char = {\n tab: 0x09, // \\t\n lineFeed: 0x0a, // \\n\n carriageReturn: 0x0d, // \\r\n space: 0x20, // \" \"\n\n doubleQuote: 0x22, // \"\n plus: 0x2b, // +\n comma: 0x2c, // ,\n minus: 0x2d, // -\n period: 0x2e, // .\n\n _0: 0x30, // 0\n _9: 0x39, // 9\n\n colon: 0x3a, // :\n\n E: 0x45, // E\n\n openBracket: 0x5b, // [\n backslash: 0x5c, // \\\n closeBracket: 0x5d, // ]\n\n a: 0x61, // a\n b: 0x62, // b\n e: 0x65, // e\n f: 0x66, // f\n l: 0x6c, // l\n n: 0x6e, // n\n r: 0x72, // r\n s: 0x73, // s\n t: 0x74, // t\n u: 0x75, // u\n\n openBrace: 0x7b, // {\n closeBrace: 0x7d // }\n};\n\nfunction checkBufferLength(parser) {\n const maxAllowed = Math.max(MAX_BUFFER_LENGTH, 10);\n let maxActual = 0;\n\n for (var buffer in buffers) {\n var len = parser[buffer] === undefined ? 0 : parser[buffer].length;\n if (len > maxAllowed) {\n switch (buffer) {\n case 'text':\n closeText(parser);\n break;\n\n default:\n error(parser, 'Max buffer length exceeded: ' + buffer);\n }\n }\n maxActual = Math.max(maxActual, len);\n }\n parser.bufferCheckPosition = MAX_BUFFER_LENGTH - maxActual + parser.position;\n}\n\nvar stringTokenPattern = /[\\\\\"\\n]/g;\n\nexport default class ClarinetParser {\n constructor(options = {}) {\n this._initialize(options);\n }\n\n _initialize(options) {\n this._clearBuffers(this);\n this.bufferCheckPosition = MAX_BUFFER_LENGTH;\n this.q = '';\n this.c = '';\n this.p = '';\n this.options = options || {};\n this.closed = false;\n this.closedRoot = false;\n this.sawRoot = false;\n this.tag = null;\n this.error = null;\n this.state = S.BEGIN;\n this.stack = new Array();\n // mostly just for error reporting\n this.position = this.column = 0;\n this.line = 1;\n this.slashed = false;\n this.unicodeI = 0;\n this.unicodeS = null;\n this.depth = 0;\n\n // install callbacks\n if ('onready' in options) {\n this.onready = options.onready;\n }\n\n if ('onopenobject' in options) {\n this.onopenobject = options.onopenobject;\n }\n\n if ('onkey' in options) {\n this.onkey = options.onkey;\n }\n\n if ('oncloseobject' in options) {\n this.oncloseobject = options.oncloseobject;\n }\n\n if ('onopenarray' in options) {\n this.onopenarray = options.onopenarray;\n }\n\n if ('onclosearray' in options) {\n this.onclosearray = options.onclosearray;\n }\n\n if ('onvalue' in options) {\n this.onvalue = options.onvalue;\n }\n\n if ('onerror' in options) {\n this.onerror = options.onerror;\n }\n\n if ('onend' in options) {\n this.onend = options.onend;\n }\n\n if ('onchunkparsed' in options) {\n this.onchunkparsed = options.onchunkparsed;\n }\n\n emit(this, 'onready');\n }\n\n _clearBuffers() {\n for (var buffer in buffers) {\n this[buffer] = buffers[buffer];\n }\n }\n\n end() {\n if (this.state !== S.VALUE || this.depth !== 0) error(this, 'Unexpected end');\n\n closeValue(this);\n this.c = '';\n this.closed = true;\n emit(this, 'onend');\n this._initialize(this.options);\n return this;\n }\n\n resume() {\n this.error = null;\n return this;\n }\n\n close() {\n return this.write(null);\n }\n\n write(chunk) {\n if (this.error) {\n throw this.error;\n }\n if (this.closed) {\n return error(this, 'Cannot write after close. Assign an onready handler.');\n }\n if (chunk === null) {\n return this.end();\n }\n var i = 0,\n c = chunk.charCodeAt(0),\n p = this.p;\n if (DEBUG) console.log('write -> [' + chunk + ']');\n while (c) {\n p = c;\n this.c = c = chunk.charCodeAt(i++);\n // if chunk doesnt have next, like streaming char by char\n // this way we need to check if previous is really previous\n // if not we need to reset to what the this says is the previous\n // from buffer\n if (p !== c) {\n this.p = p;\n } else {\n p = this.p;\n }\n\n if (!c) break;\n\n if (DEBUG) console.log(i, c, STATE[this.state]);\n this.position++;\n if (c === Char.lineFeed) {\n this.line++;\n this.column = 0;\n } else this.column++;\n\n switch (this.state) {\n case S.BEGIN:\n if (c === Char.openBrace) this.state = S.OPEN_OBJECT;\n else if (c === Char.openBracket) this.state = S.OPEN_ARRAY;\n else if (!isWhitespace(c)) {\n error(this, 'Non-whitespace before {[.');\n }\n continue;\n\n case S.OPEN_KEY:\n case S.OPEN_OBJECT:\n if (isWhitespace(c)) continue;\n if (this.state === S.OPEN_KEY) this.stack.push(S.CLOSE_KEY);\n else {\n if (c === Char.closeBrace) {\n emit(this, 'onopenobject');\n this.depth++;\n emit(this, 'oncloseobject');\n this.depth--;\n this.state = this.stack.pop() || S.VALUE;\n continue;\n } else this.stack.push(S.CLOSE_OBJECT);\n }\n if (c === Char.doubleQuote) this.state = S.STRING;\n else error(this, 'Malformed object key should start with \"');\n continue;\n\n case S.CLOSE_KEY:\n case S.CLOSE_OBJECT:\n if (isWhitespace(c)) continue;\n var event = this.state === S.CLOSE_KEY ? 'key' : 'object';\n if (c === Char.colon) {\n if (this.state === S.CLOSE_OBJECT) {\n this.stack.push(S.CLOSE_OBJECT);\n closeValue(this, 'onopenobject');\n this.depth++;\n } else closeValue(this, 'onkey');\n this.state = S.VALUE;\n } else if (c === Char.closeBrace) {\n emitNode(this, 'oncloseobject');\n this.depth--;\n this.state = this.stack.pop() || S.VALUE;\n } else if (c === Char.comma) {\n if (this.state === S.CLOSE_OBJECT) this.stack.push(S.CLOSE_OBJECT);\n closeValue(this);\n this.state = S.OPEN_KEY;\n } else error(this, 'Bad object');\n continue;\n\n case S.OPEN_ARRAY: // after an array there always a value\n case S.VALUE:\n if (isWhitespace(c)) continue;\n if (this.state === S.OPEN_ARRAY) {\n emit(this, 'onopenarray');\n this.depth++;\n this.state = S.VALUE;\n if (c === Char.closeBracket) {\n emit(this, 'onclosearray');\n this.depth--;\n this.state = this.stack.pop() || S.VALUE;\n continue;\n } else {\n this.stack.push(S.CLOSE_ARRAY);\n }\n }\n if (c === Char.doubleQuote) this.state = S.STRING;\n else if (c === Char.openBrace) this.state = S.OPEN_OBJECT;\n else if (c === Char.openBracket) this.state = S.OPEN_ARRAY;\n else if (c === Char.t) this.state = S.TRUE;\n else if (c === Char.f) this.state = S.FALSE;\n else if (c === Char.n) this.state = S.NULL;\n else if (c === Char.minus) {\n // keep and continue\n this.numberNode += '-';\n } else if (Char._0 <= c && c <= Char._9) {\n this.numberNode += String.fromCharCode(c);\n this.state = S.NUMBER_DIGIT;\n } else error(this, 'Bad value');\n continue;\n\n case S.CLOSE_ARRAY:\n if (c === Char.comma) {\n this.stack.push(S.CLOSE_ARRAY);\n closeValue(this, 'onvalue');\n this.state = S.VALUE;\n } else if (c === Char.closeBracket) {\n emitNode(this, 'onclosearray');\n this.depth--;\n this.state = this.stack.pop() || S.VALUE;\n } else if (isWhitespace(c)) continue;\n else error(this, 'Bad array');\n continue;\n\n case S.STRING:\n if (this.textNode === undefined) {\n this.textNode = '';\n }\n\n // thanks thejh, this is an about 50% performance improvement.\n var starti = i - 1,\n slashed = this.slashed,\n unicodeI = this.unicodeI;\n STRING_BIGLOOP: while (true) {\n if (DEBUG) console.log(i, c, STATE[this.state], slashed);\n // zero means \"no unicode active\". 1-4 mean \"parse some more\". end after 4.\n while (unicodeI > 0) {\n this.unicodeS += String.fromCharCode(c);\n c = chunk.charCodeAt(i++);\n this.position++;\n if (unicodeI === 4) {\n // TODO this might be slow? well, probably not used too often anyway\n this.textNode += String.fromCharCode(parseInt(this.unicodeS, 16));\n unicodeI = 0;\n starti = i - 1;\n } else {\n unicodeI++;\n }\n // we can just break here: no stuff we skipped that still has to be sliced out or so\n if (!c) break STRING_BIGLOOP;\n }\n if (c === Char.doubleQuote && !slashed) {\n this.state = this.stack.pop() || S.VALUE;\n this.textNode += chunk.substring(starti, i - 1);\n this.position += i - 1 - starti;\n break;\n }\n if (c === Char.backslash && !slashed) {\n slashed = true;\n this.textNode += chunk.substring(starti, i - 1);\n this.position += i - 1 - starti;\n c = chunk.charCodeAt(i++);\n this.position++;\n if (!c) break;\n }\n if (slashed) {\n slashed = false;\n if (c === Char.n) {\n this.textNode += '\\n';\n } else if (c === Char.r) {\n this.textNode += '\\r';\n } else if (c === Char.t) {\n this.textNode += '\\t';\n } else if (c === Char.f) {\n this.textNode += '\\f';\n } else if (c === Char.b) {\n this.textNode += '\\b';\n } else if (c === Char.u) {\n // \\uxxxx. meh!\n unicodeI = 1;\n this.unicodeS = '';\n } else {\n this.textNode += String.fromCharCode(c);\n }\n c = chunk.charCodeAt(i++);\n this.position++;\n starti = i - 1;\n if (!c) break;\n else continue;\n }\n\n stringTokenPattern.lastIndex = i;\n var reResult = stringTokenPattern.exec(chunk);\n if (reResult === null) {\n i = chunk.length + 1;\n this.textNode += chunk.substring(starti, i - 1);\n this.position += i - 1 - starti;\n break;\n }\n i = reResult.index + 1;\n c = chunk.charCodeAt(reResult.index);\n if (!c) {\n this.textNode += chunk.substring(starti, i - 1);\n this.position += i - 1 - starti;\n break;\n }\n }\n this.slashed = slashed;\n this.unicodeI = unicodeI;\n continue;\n\n case S.TRUE:\n if (c === Char.r) this.state = S.TRUE2;\n else error(this, 'Invalid true started with t' + c);\n continue;\n\n case S.TRUE2:\n if (c === Char.u) this.state = S.TRUE3;\n else error(this, 'Invalid true started with tr' + c);\n continue;\n\n case S.TRUE3:\n if (c === Char.e) {\n emit(this, 'onvalue', true);\n this.state = this.stack.pop() || S.VALUE;\n } else error(this, 'Invalid true started with tru' + c);\n continue;\n\n case S.FALSE:\n if (c === Char.a) this.state = S.FALSE2;\n else error(this, 'Invalid false started with f' + c);\n continue;\n\n case S.FALSE2:\n if (c === Char.l) this.state = S.FALSE3;\n else error(this, 'Invalid false started with fa' + c);\n continue;\n\n case S.FALSE3:\n if (c === Char.s) this.state = S.FALSE4;\n else error(this, 'Invalid false started with fal' + c);\n continue;\n\n case S.FALSE4:\n if (c === Char.e) {\n emit(this, 'onvalue', false);\n this.state = this.stack.pop() || S.VALUE;\n } else error(this, 'Invalid false started with fals' + c);\n continue;\n\n case S.NULL:\n if (c === Char.u) this.state = S.NULL2;\n else error(this, 'Invalid null started with n' + c);\n continue;\n\n case S.NULL2:\n if (c === Char.l) this.state = S.NULL3;\n else error(this, 'Invalid null started with nu' + c);\n continue;\n\n case S.NULL3:\n if (c === Char.l) {\n emit(this, 'onvalue', null);\n this.state = this.stack.pop() || S.VALUE;\n } else error(this, 'Invalid null started with nul' + c);\n continue;\n\n case S.NUMBER_DECIMAL_POINT:\n if (c === Char.period) {\n this.numberNode += '.';\n this.state = S.NUMBER_DIGIT;\n } else error(this, 'Leading zero not followed by .');\n continue;\n\n case S.NUMBER_DIGIT:\n if (Char._0 <= c && c <= Char._9) this.numberNode += String.fromCharCode(c);\n else if (c === Char.period) {\n if (this.numberNode.indexOf('.') !== -1) error(this, 'Invalid number has two dots');\n this.numberNode += '.';\n } else if (c === Char.e || c === Char.E) {\n if (this.numberNode.indexOf('e') !== -1 || this.numberNode.indexOf('E') !== -1)\n error(this, 'Invalid number has two exponential');\n this.numberNode += 'e';\n } else if (c === Char.plus || c === Char.minus) {\n if (!(p === Char.e || p === Char.E)) error(this, 'Invalid symbol in number');\n this.numberNode += String.fromCharCode(c);\n } else {\n closeNumber(this);\n i--; // go back one\n this.state = this.stack.pop() || S.VALUE;\n }\n continue;\n\n default:\n error(this, 'Unknown state: ' + this.state);\n }\n }\n if (this.position >= this.bufferCheckPosition) {\n checkBufferLength(this);\n }\n\n emit(this, 'onchunkparsed');\n\n return this;\n }\n}\n\nfunction emit(parser, event, data) {\n if (DEBUG) {\n console.log('-- emit', event, data);\n }\n if (parser[event]) {\n parser[event](data, parser);\n }\n}\n\nfunction emitNode(parser, event, data) {\n closeValue(parser);\n emit(parser, event, data);\n}\n\nfunction closeValue(parser, event) {\n parser.textNode = textopts(parser.options, parser.textNode);\n if (parser.textNode !== undefined) {\n emit(parser, event ? event : 'onvalue', parser.textNode);\n }\n parser.textNode = undefined;\n}\n\nfunction closeNumber(parser) {\n if (parser.numberNode) emit(parser, 'onvalue', parseFloat(parser.numberNode));\n parser.numberNode = '';\n}\n\nfunction textopts(opt, text) {\n if (text === undefined) {\n return text;\n }\n if (opt.trim) text = text.trim();\n if (opt.normalize) text = text.replace(/\\s+/g, ' ');\n return text;\n}\n\nfunction error(parser, er) {\n closeValue(parser);\n er += '\\nLine: ' + parser.line + '\\nColumn: ' + parser.column + '\\nChar: ' + parser.c;\n er = new Error(er);\n parser.error = er;\n emit(parser, 'onerror', er);\n return parser;\n}\n\nfunction isWhitespace(c) {\n return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab;\n}\n","// @ts-nocheck\nconst moduleExports = require('./index');\nconst _global = typeof window === 'undefined' ? global : window;\n_global.loaders = _global.loaders || {};\nmodule.exports = Object.assign(_global.loaders, moduleExports);\n","export type {JSONLoaderOptions} from './json-loader';\nexport {JSONLoader} from './json-loader';\n\n// EXPERIMENTAL EXPORTS - WARNING: MAY BE REMOVED WIHTOUT NOTICE IN FUTURE RELEASES\nexport type {GeoJSONLoaderOptions as _GeoJSONLoaderOptions} from './geojson-loader';\nexport {\n GeoJSONLoader as _GeoJSONLoader,\n GeoJSONWorkerLoader as _GeoJSONWorkerLoader\n} from './geojson-loader';\n\nexport {default as _JSONPath} from './lib/jsonpath/jsonpath';\nexport {default as _ClarinetParser} from './lib/clarinet/clarinet';\n","import type {Batch} from '@loaders.gl/schema';\nimport type {LoaderWithParser, LoaderOptions} from '@loaders.gl/loader-utils';\nimport parseJSONSync from './lib/parse-json';\nimport parseJSONInBatches from './lib/parse-json-in-batches';\n\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n\n/**\n * @param table -\n * @param jsonpaths -\n */\nexport type JSONLoaderOptions = LoaderOptions & {\n json?: {\n shape?: 'row-table';\n table?: false;\n jsonpaths?: string[];\n };\n};\n\nconst DEFAULT_JSON_LOADER_OPTIONS = {\n json: {\n shape: 'row-table',\n table: false,\n jsonpaths: []\n // batchSize: 'auto'\n }\n};\n\nexport const JSONLoader: LoaderWithParser = {\n name: 'JSON',\n id: 'json',\n module: 'json',\n version: VERSION,\n extensions: ['json', 'geojson'],\n mimeTypes: ['application/json'],\n // TODO - support various line based JSON formats\n /*\n extensions: {\n json: null,\n jsonl: {stream: true},\n ndjson: {stream: true}\n },\n mimeTypes: {\n 'application/json': null,\n 'application/json-seq': {stream: true},\n 'application/x-ndjson': {stream: true}\n },\n */\n category: 'table',\n text: true,\n parse,\n parseTextSync,\n parseInBatches,\n options: DEFAULT_JSON_LOADER_OPTIONS\n};\n\nasync function parse(arrayBuffer: ArrayBuffer, options?: JSONLoaderOptions) {\n return parseTextSync(new TextDecoder().decode(arrayBuffer), options);\n}\n\nfunction parseTextSync(text: string, options?: JSONLoaderOptions) {\n const jsonOptions = {...options, json: {...DEFAULT_JSON_LOADER_OPTIONS.json, ...options?.json}};\n return parseJSONSync(text, jsonOptions as JSONLoaderOptions);\n}\n\nfunction parseInBatches(\n asyncIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>,\n options?: JSONLoaderOptions\n): AsyncIterable<Batch> {\n const jsonOptions = {...options, json: {...DEFAULT_JSON_LOADER_OPTIONS.json, ...options?.json}};\n return parseJSONInBatches(asyncIterator, jsonOptions as JSONLoaderOptions);\n}\n","// COMMON CATEGORY\nexport type {TypedArray, NumberArray, AnyArray} from './types';\n\nexport type {Batch} from './category/common';\n\n// TABLE CATEGORY TYPES\n\nexport type {\n Table,\n ArrayRowTable,\n ObjectRowTable,\n ColumnarTable,\n ArrowTable\n} from './category/table';\nexport type {\n TableBatch,\n RowArrayTableBatch,\n RowObjectTableBatch,\n ColumnarTableBatch,\n ArrowTableBatch\n} from './category/table';\n\n// TABLE CATEGORY UTILS\nexport {default as TableBatchBuilder} from './lib/table/table-batch-builder';\nexport type {TableBatchAggregator} from './lib/table/table-batch-aggregator';\nexport {default as RowTableBatchAggregator} from './lib/table/row-table-batch-aggregator';\nexport {default as ColumnarTableBatchAggregator} from './lib/table/columnar-table-batch-aggregator';\n\nexport {convertToObjectRow, convertToArrayRow} from './lib/utils/row-utils';\n\n// MESH CATEGORY\nexport type {MeshTable, MeshArrowTable, Mesh, MeshAttribute} from './category/mesh';\n\n// MESH CATEGORY UTILS\nexport type {Attributes as _Attributes} from './category/mesh/mesh-utils';\nexport {getMeshSize, getMeshBoundingBox} from './category/mesh/mesh-utils';\n\n// TYPES\n// GIS CATEGORY - GEOJSON\nexport type {GeoJSON, Feature, Geometry, Position, GeoJsonProperties} from './category/gis';\nexport type {\n Point,\n MultiPoint,\n LineString,\n MultiLineString,\n Polygon,\n MultiPolygon\n} from './category/gis';\n\n// GIS CATEGORY - BINARY\nexport type {\n BinaryGeometryType,\n BinaryGeometry,\n BinaryPointGeometry,\n BinaryLineGeometry,\n BinaryPolygonGeometry,\n BinaryAttribute\n} from './category/gis';\nexport type {\n BinaryFeatures,\n BinaryPointFeatures,\n BinaryLineFeatures,\n BinaryPolygonFeatures\n} from './category/gis';\n\n// SCHEMA\nexport {\n Schema,\n Field,\n DataType,\n Null,\n Binary,\n Bool,\n Int,\n Int8,\n Int16,\n Int32,\n Int64,\n Uint8,\n Uint16,\n Uint32,\n Uint64,\n Float,\n Float16,\n Float32,\n Float64,\n Utf8,\n Date,\n DateDay,\n DateMillisecond,\n Time,\n TimeMillisecond,\n TimeSecond,\n Timestamp,\n TimestampSecond,\n TimestampMillisecond,\n TimestampMicrosecond,\n TimestampNanosecond,\n Interval,\n IntervalDayTime,\n IntervalYearMonth,\n FixedSizeList\n} from './lib/schema';\n\n// SCHEMA UTILS\nexport {deduceTableSchema} from './lib/schema-utils/deduce-table-schema';\nexport {getTypeInfo} from './lib/schema-utils/get-type-info';\nexport {getArrowTypeFromTypedArray} from './lib/schema-utils/type-utils';\n\n// EXPERIMENTAL APIs\nexport {default as AsyncQueue} from './lib/utils/async-queue';\n","import type {Schema} from '../schema';\nimport type {TableBatch} from '../../category/table';\nimport type {TableBatchAggregator, TableBatchConstructor} from './table-batch-aggregator';\nimport BaseTableBatchAggregator from './base-table-batch-aggregator';\nimport RowTableBatchAggregator from './row-table-batch-aggregator';\nimport ColumnarTableBatchAggregator from './columnar-table-batch-aggregator';\n\n// TODO define interface instead\ntype TableBatchBuilderOptions = {\n shape: 'row-table' | 'array-row-table' | 'object-row-table' | 'columnar-table' | 'arrow-table';\n batchSize?: number | 'auto';\n batchDebounceMs?: number;\n limit: number;\n _limitMB: number;\n};\n\ntype GetBatchOptions = {\n bytesUsed?: number;\n [key: string]: any;\n};\n\nconst DEFAULT_OPTIONS: Required<TableBatchBuilderOptions> = {\n shape: 'array-row-table',\n batchSize: 'auto',\n batchDebounceMs: 0,\n limit: 0,\n _limitMB: 0\n};\n\nconst ERR_MESSAGE = 'TableBatchBuilder';\n\n/** Incrementally builds batches from a stream of rows */\nexport default class TableBatchBuilder {\n schema: Schema;\n options: Required<TableBatchBuilderOptions>;\n\n private aggregator: TableBatchAggregator | null = null;\n private batchCount: number = 0;\n private bytesUsed: number = 0;\n private isChunkComplete: boolean = false;\n private lastBatchEmittedMs: number = Date.now();\n private totalLength: number = 0;\n private totalBytes: number = 0;\n private rowBytes: number = 0;\n\n static ArrowBatch?: TableBatchConstructor;\n\n constructor(schema: Schema, options?: TableBatchBuilderOptions) {\n this.schema = schema;\n this.options = {...DEFAULT_OPTIONS, ...options};\n }\n\n limitReached(): boolean {\n if (Boolean(this.options?.limit) && this.totalLength >= this.options.limit) {\n return true;\n }\n if (Boolean(this.options?._limitMB) && this.totalBytes / 1e6 >= this.options._limitMB) {\n return true;\n }\n return false;\n }\n\n /** @deprecated Use addArrayRow or addObjectRow */\n addRow(row: any[] | {[columnName: string]: any}): void {\n if (this.limitReached()) {\n return;\n }\n this.totalLength++;\n this.rowBytes = this.rowBytes || this._estimateRowMB(row);\n this.totalBytes += this.rowBytes;\n if (Array.isArray(row)) {\n this.addArrayRow(row);\n } else {\n this.addObjectRow(row);\n }\n }\n\n /** Add one row to the batch */\n protected addArrayRow(row: any[]) {\n if (!this.aggregator) {\n const TableBatchType = this._getTableBatchType();\n this.aggregator = new TableBatchType(this.schema, this.options);\n }\n this.aggregator.addArrayRow(row);\n }\n\n /** Add one row to the batch */\n protected addObjectRow(row: {[columnName: string]: any}): void {\n if (!this.aggregator) {\n const TableBatchType = this._getTableBatchType();\n this.aggregator = new TableBatchType(this.schema, this.options);\n }\n this.aggregator.addObjectRow(row);\n }\n\n /** Mark an incoming raw memory chunk has completed */\n chunkComplete(chunk: ArrayBuffer | string): void {\n if (chunk instanceof ArrayBuffer) {\n this.bytesUsed += chunk.byteLength;\n }\n if (typeof chunk === 'string') {\n this.bytesUsed += chunk.length;\n }\n this.isChunkComplete = true;\n }\n\n getFullBatch(options?: GetBatchOptions): TableBatch | null {\n return this._isFull() ? this._getBatch(options) : null;\n }\n\n getFinalBatch(options?: GetBatchOptions): TableBatch | null {\n return this._getBatch(options);\n }\n\n // INTERNAL\n\n _estimateRowMB(row) {\n return Array.isArray(row) ? row.length * 8 : Object.keys(row).length * 8;\n }\n\n private _isFull(): boolean {\n // No batch, not ready\n if (!this.aggregator || this.aggregator.rowCount() === 0) {\n return false;\n }\n\n // if batchSize === 'auto' we wait for chunk to complete\n // if batchSize === number, ensure we have enough rows\n if (this.options.batchSize === 'auto') {\n if (!this.isChunkComplete) {\n return false;\n }\n } else if (this.options.batchSize > this.aggregator.rowCount()) {\n return false;\n }\n\n // Debounce batches\n if (this.options.batchDebounceMs > Date.now() - this.lastBatchEmittedMs) {\n return false;\n }\n\n // Emit batch\n this.isChunkComplete = false;\n this.lastBatchEmittedMs = Date.now();\n return true;\n }\n\n /**\n * bytesUsed can be set via chunkComplete or via getBatch*\n */\n private _getBatch(options?: GetBatchOptions): TableBatch | null {\n if (!this.aggregator) {\n return null;\n }\n\n // TODO - this can overly increment bytes used?\n if (options?.bytesUsed) {\n this.bytesUsed = options.bytesUsed;\n }\n const normalizedBatch = this.aggregator.getBatch() as TableBatch;\n normalizedBatch.count = this.batchCount;\n normalizedBatch.bytesUsed = this.bytesUsed;\n Object.assign(normalizedBatch, options);\n\n this.batchCount++;\n this.aggregator = null;\n return normalizedBatch;\n }\n\n private _getTableBatchType(): TableBatchConstructor {\n switch (this.options.shape) {\n case 'row-table':\n return BaseTableBatchAggregator;\n case 'array-row-table':\n case 'object-row-table':\n return RowTableBatchAggregator;\n case 'columnar-table':\n return ColumnarTableBatchAggregator;\n case 'arrow-table':\n if (!TableBatchBuilder.ArrowBatch) {\n throw new Error(ERR_MESSAGE);\n }\n return TableBatchBuilder.ArrowBatch;\n default:\n throw new Error(ERR_MESSAGE);\n }\n }\n}\n","import type {Schema} from '../schema';\nimport type {TableBatch} from '../../category/table';\nimport {TableBatchAggregator, TableBatchOptions} from './table-batch-aggregator';\n\nconst DEFAULT_ROW_COUNT = 100;\n\nexport default class RowTableBatchAggregator implements TableBatchAggregator {\n schema: Schema;\n options: TableBatchOptions;\n\n length: number = 0;\n rows: any[] | null = null;\n cursor: number = 0;\n private _headers: string[] = [];\n\n constructor(schema: Schema, options: TableBatchOptions) {\n this.options = options;\n this.schema = schema;\n\n // schema is an array if there're no headers\n // object if there are headers\n if (!Array.isArray(schema)) {\n this._headers = [];\n for (const key in schema) {\n this._headers[schema[key].index] = schema[key].name;\n }\n }\n }\n\n rowCount(): number {\n return this.length;\n }\n\n addArrayRow(row: any[], cursor?: number): void {\n if (Number.isFinite(cursor)) {\n this.cursor = cursor as number;\n }\n\n this.rows = this.rows || new Array(DEFAULT_ROW_COUNT);\n this.rows[this.length] = row;\n this.length++;\n }\n\n addObjectRow(row: {[columnName: string]: any}, cursor?: number): void {\n if (Number.isFinite(cursor)) {\n this.cursor = cursor as number;\n }\n\n this.rows = this.rows || new Array(DEFAULT_ROW_COUNT);\n this.rows[this.length] = row;\n this.length++;\n }\n\n getBatch(): TableBatch | null {\n let rows = this.rows;\n if (!rows) {\n return null;\n }\n\n rows = rows.slice(0, this.length);\n this.rows = null;\n\n const batch: TableBatch = {\n shape: this.options.shape,\n batchType: 'data',\n data: rows,\n length: this.length,\n schema: this.schema,\n cursor: this.cursor\n };\n\n return batch;\n }\n}\n","// Mesh category utilities\n// TODO - move to mesh category module, or to math.gl/geometry module\nimport {TypedArray} from '../../types';\n\ntype Attribute = {\n size?: number;\n type?: number;\n normalized?: boolean;\n value: TypedArray;\n};\n\ntype TypedArrays = {[key: string]: TypedArray};\nexport type Attributes = {[key: string]: Attribute};\n\n/**\n * Holds an axis aligned bounding box\n * TODO - make sure AxisAlignedBoundingBox in math.gl/culling understands this format (or change this format)\n */\ntype BoundingBox = [[number, number, number], [number, number, number]];\n\n/**\n * Get number of vertices in mesh\n * @param attributes\n */\nexport function getMeshSize(attributes: TypedArrays): number {\n let size = 0;\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n if (ArrayBuffer.isView(attribute)) {\n // @ts-ignore DataView doesn't have BYTES_PER_ELEMENT\n size += attribute.byteLength * attribute.BYTES_PER_ELEMENT;\n }\n }\n return size;\n}\n\n/**\n * Get the (axis aligned) bounding box of a mesh\n * @param attributes\n * @returns array of two vectors representing the axis aligned bounding box\n */\n// eslint-disable-next-line complexity\nexport function getMeshBoundingBox(attributes: Attributes): BoundingBox {\n let minX = Infinity;\n let minY = Infinity;\n let minZ = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n let maxZ = -Infinity;\n\n const positions = attributes.POSITION ? attributes.POSITION.value : [];\n const len = positions && positions.length;\n\n for (let i = 0; i < len; i += 3) {\n const x = positions[i];\n const y = positions[i + 1];\n const z = positions[i + 2];\n\n minX = x < minX ? x : minX;\n minY = y < minY ? y : minY;\n minZ = z < minZ ? z : minZ;\n\n maxX = x > maxX ? x : maxX;\n maxY = y > maxY ? y : maxY;\n maxZ = z > maxZ ? z : maxZ;\n }\n return [\n [minX, minY, minZ],\n [maxX, maxY, maxZ]\n ];\n}\n","import {assert} from '../../utils/assert';\nimport Field from './field';\n\nexport type SchemaMetadata = Map<string, any>;\n\n/**\n * ArrowJS `Schema` API-compatible class for row-based tables (returned from `DataTable`)\n * https://loaders.gl/arrowjs/docs/api-reference/schema\n */\nexport default class Schema {\n fields: Field[];\n // TODO - Arrow just allows Map<string, string>\n metadata: SchemaMetadata;\n\n constructor(fields: Field[], metadata?: SchemaMetadata) {\n assert(Array.isArray(fields));\n checkNames(fields);\n // For kepler fields, create arrow compatible `Fields` that have kepler fields as `metadata`\n this.fields = fields;\n this.metadata = metadata || new Map();\n }\n\n // TODO - arrow only seems to compare fields, not metadata\n compareTo(other: Schema): boolean {\n if (this.metadata !== other.metadata) {\n return false;\n }\n if (this.fields.length !== other.fields.length) {\n return false;\n }\n for (let i = 0; i < this.fields.length; ++i) {\n if (!this.fields[i].compareTo(other.fields[i])) {\n return false;\n }\n }\n return true;\n }\n\n select(...columnNames: string[]): Schema {\n // Ensure column names reference valid fields\n const nameMap = Object.create(null);\n for (const name of columnNames) {\n nameMap[name] = true;\n }\n const selectedFields = this.fields.filter((field) => nameMap[field.name]);\n return new Schema(selectedFields, this.metadata);\n }\n\n selectAt(...columnIndices: number[]): Schema {\n // Ensure column indices reference valid fields\n const selectedFields = columnIndices.map((index) => this.fields[index]).filter(Boolean);\n return new Schema(selectedFields, this.metadata);\n }\n\n assign(schemaOrFields: Schema | Field[]): Schema {\n let fields: Field[];\n let metadata: SchemaMetadata = this.metadata;\n\n if (schemaOrFields instanceof Schema) {\n const otherSchema = schemaOrFields;\n fields = otherSchema.fields;\n metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);\n } else {\n fields = schemaOrFields;\n }\n\n // Create a merged list of fields, overwrite fields in place, new fields at end\n const fieldMap: {[key: string]: Field} = Object.create(null);\n\n for (const field of this.fields) {\n fieldMap[field.name] = field;\n }\n\n for (const field of fields) {\n fieldMap[field.name] = field;\n }\n\n const mergedFields = Object.values(fieldMap);\n\n return new Schema(mergedFields, metadata);\n }\n}\n\n// Warn if any duplicated field names\nfunction checkNames(fields) {\n const usedNames = {};\n for (const field of fields) {\n if (usedNames[field.name]) {\n // eslint-disable-next-line\n console.warn('Schema: duplicated field name', field.name, field);\n }\n usedNames[field.name] = true;\n }\n}\n\nfunction mergeMaps<T>(m1: T, m2: T): T {\n // @ts-ignore\n return new Map([...(m1 || new Map()), ...(m2 || new Map())]);\n}\n","// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\nexport function assert(condition: boolean, message?: string) {\n if (!condition) {\n throw new Error(message || 'loader assertion failed.');\n }\n}\n","import {DataType} from './type';\n\n/**\n * ArrowJS `Field` API-compatible class for row-based tables\n * https://loaders.gl/arrowjs/docs/api-reference/field\n * A field holds name, nullable, and metadata information about a table \"column\"\n * A Schema is essentially a list of fields\n */\nexport default class Field {\n name: string;\n type: DataType;\n nullable: boolean;\n metadata: Map<string, string>;\n\n constructor(\n name: string,\n type: DataType,\n nullable = false,\n metadata: Map<string, string> = new Map()\n ) {\n this.name = name;\n this.type = type;\n this.nullable = nullable;\n this.metadata = metadata;\n }\n\n get typeId(): number {\n return this.type && this.type.typeId;\n }\n\n clone(): Field {\n return new Field(this.name, this.type, this.nullable, this.metadata);\n }\n\n compareTo(other: this): boolean {\n return (\n this.name === other.name &&\n this.type === other.type &&\n this.nullable === other.nullable &&\n this.metadata === other.metadata\n );\n }\n\n toString(): string {\n return `${this.type}${this.nullable ? ', nullable' : ''}${\n this.metadata ? `, metadata: ${this.metadata}` : ''\n }`;\n }\n}\n","// This code is adapted from ArrowJS https://github.com/apache/arrow\n// under Apache license http://www.apache.org/licenses/LICENSE-2.0\n\nimport {Type} from './enum';\n\nimport Field from './field';\n\nexport {Type} from './enum';\n\nexport type TypedIntArray =\n | Int8Array\n | Uint8Array\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Int32Array\n | Uint32Array\n | Uint8ClampedArray;\n\nexport type TypedFloatArray = Float32Array | Float64Array;\n\nexport type TypedArray = TypedIntArray | TypedFloatArray;\n\nexport type AnyArrayType = Array<any> | TypedIntArray | TypedFloatArray;\n\nexport class DataType {\n static isNull(x: any): boolean {\n return x && x.typeId === Type.Null;\n }\n static isInt(x: any): boolean {\n return x && x.typeId === Type.Int;\n }\n static isFloat(x: any): boolean {\n return x && x.typeId === Type.Float;\n }\n static isBinary(x: any): boolean {\n return x && x.typeId === Type.Binary;\n }\n static isUtf8(x: any): boolean {\n return x && x.typeId === Type.Utf8;\n }\n static isBool(x: any): boolean {\n return x && x.typeId === Type.Bool;\n }\n static isDecimal(x: any): boolean {\n return x && x.typeId === Type.Decimal;\n }\n static isDate(x: any): boolean {\n return x && x.typeId === Type.Date;\n }\n static isTime(x: any): boolean {\n return x && x.typeId === Type.Time;\n }\n static isTimestamp(x: any): boolean {\n return x && x.typeId === Type.Timestamp;\n }\n static isInterval(x: any): boolean {\n return x && x.typeId === Type.Interval;\n }\n static isList(x: any): boolean {\n return x && x.typeId === Type.List;\n }\n static isStruct(x: any): boolean {\n return x && x.typeId === Type.Struct;\n }\n static isUnion(x: any): boolean {\n return x && x.typeId === Type.Union;\n }\n static isFixedSizeBinary(x: any): boolean {\n return x && x.typeId === Type.FixedSizeBinary;\n }\n static isFixedSizeList(x: any): boolean {\n return x && x.typeId === Type.FixedSizeList;\n }\n static isMap(x: any): boolean {\n return x && x.typeId === Type.Map;\n }\n static isDictionary(x: any): boolean {\n return x && x.typeId === Type.Dictionary;\n }\n\n get typeId(): Type {\n return Type.NONE;\n }\n\n // get ArrayType(): AnyArrayType {\n // return Int8Array;\n // }\n\n // get ArrayType() { return Array; }\n compareTo(other: DataType): boolean {\n // TODO\n return this === other; // comparer.visit(this, other);\n }\n}\n\n// NULL\n\nexport class Null extends DataType {\n get typeId(): Type {\n return Type.Null;\n }\n get [Symbol.toStringTag](): string {\n return 'Null';\n }\n toString(): string {\n return 'Null';\n }\n}\n\n// BOOLEANS\n\nexport class Bool extends DataType {\n get typeId(): Type {\n return Type.Bool;\n }\n // get ArrayType() {\n // return Uint8Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Bool';\n }\n toString(): string {\n return 'Bool';\n }\n}\n\n// INTS\n\nexport class Int extends DataType {\n readonly isSigned: boolean;\n readonly bitWidth: number;\n constructor(isSigned, bitWidth) {\n super();\n this.isSigned = isSigned;\n this.bitWidth = bitWidth;\n }\n get typeId(): Type {\n return Type.Int;\n }\n // get ArrayType() {\n // switch (this.bitWidth) {\n // case 8:\n // return this.isSigned ? Int8Array : Uint8Array;\n // case 16:\n // return this.isSigned ? Int16Array : Uint16Array;\n // case 32:\n // return this.isSigned ? Int32Array : Uint32Array;\n // case 64:\n // return this.isSigned ? Int32Array : Uint32Array;\n // default:\n // throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);\n // }\n // }\n get [Symbol.toStringTag](): string {\n return 'Int';\n }\n toString(): string {\n return `${this.isSigned ? 'I' : 'Ui'}nt${this.bitWidth}`;\n }\n}\n\nexport class Int8 extends Int {\n constructor() {\n super(true, 8);\n }\n}\nexport class Int16 extends Int {\n constructor() {\n super(true, 16);\n }\n}\nexport class Int32 extends Int {\n constructor() {\n super(true, 32);\n }\n}\nexport class Int64 extends Int {\n constructor() {\n super(true, 64);\n }\n}\nexport class Uint8 extends Int {\n constructor() {\n super(false, 8);\n }\n}\nexport class Uint16 extends Int {\n constructor() {\n super(false, 16);\n }\n}\nexport class Uint32 extends Int {\n constructor() {\n super(false, 32);\n }\n}\nexport class Uint64 extends Int {\n constructor() {\n super(false, 64);\n }\n}\n\n// FLOATS\n\nconst Precision = {\n HALF: 16,\n SINGLE: 32,\n DOUBLE: 64\n};\n\nexport class Float extends DataType {\n readonly precision: number;\n constructor(precision) {\n super();\n this.precision = precision;\n }\n get typeId(): Type {\n return Type.Float;\n }\n // get ArrayType() {\n // switch (this.precision) {\n // case Precision.HALF:\n // return Uint16Array;\n // case Precision.SINGLE:\n // return Float32Array;\n // case Precision.DOUBLE:\n // return Float64Array;\n // default:\n // throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);\n // }\n // }\n get [Symbol.toStringTag](): string {\n return 'Float';\n }\n toString(): string {\n return `Float${this.precision}`;\n }\n}\n\nexport class Float16 extends Float {\n constructor() {\n super(Precision.HALF);\n }\n}\nexport class Float32 extends Float {\n constructor() {\n super(Precision.SINGLE);\n }\n}\nexport class Float64 extends Float {\n constructor() {\n super(Precision.DOUBLE);\n }\n}\n\nexport class Binary extends DataType {\n constructor() {\n super();\n }\n get typeId() {\n return Type.Binary;\n }\n toString() {\n return 'Binary';\n }\n get [Symbol.toStringTag]() {\n return 'Binary';\n }\n}\n\n// STRINGS\n\nexport class Utf8 extends DataType {\n get typeId(): Type {\n return Type.Utf8;\n }\n // get ArrayType() {\n // return Uint8Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Utf8';\n }\n toString(): string {\n return 'Utf8';\n }\n}\n\n// DATES, TIMES AND INTERVALS\n\nconst DateUnit = {\n DAY: 0,\n MILLISECOND: 1\n};\n\nexport class Date extends DataType {\n readonly unit: number;\n constructor(unit) {\n super();\n this.unit = unit;\n }\n get typeId(): Type {\n return Type.Date;\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Date';\n }\n toString(): string {\n return `Date${(this.unit + 1) * 32}<${DateUnit[this.unit]}>`;\n }\n}\n\nexport class DateDay extends Date {\n constructor() {\n super(DateUnit.DAY);\n }\n}\nexport class DateMillisecond extends Date {\n constructor() {\n super(DateUnit.MILLISECOND);\n }\n}\n\nconst TimeUnit = {\n SECOND: 1,\n MILLISECOND: 1e3,\n MICROSECOND: 1e6,\n NANOSECOND: 1e9\n};\n\nexport class Time extends DataType {\n readonly unit: number;\n readonly bitWidth: number;\n\n constructor(unit, bitWidth) {\n super();\n this.unit = unit;\n this.bitWidth = bitWidth;\n }\n get typeId(): Type {\n return Type.Time;\n }\n toString(): string {\n return `Time${this.bitWidth}<${TimeUnit[this.unit]}>`;\n }\n get [Symbol.toStringTag](): string {\n return 'Time';\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n}\n\nexport class TimeSecond extends Time {\n constructor() {\n super(TimeUnit.SECOND, 32);\n }\n}\nexport class TimeMillisecond extends Time {\n constructor() {\n super(TimeUnit.MILLISECOND, 32);\n }\n}\n// export class TimeMicrosecond extends Time { constructor() { super(TimeUnit.MICROSECOND, 64); } }\n// export class TimeNanosecond extends Time { constructor() { super(TimeUnit.NANOSECOND, 64); } }\n\nexport class Timestamp extends DataType {\n readonly unit: any;\n readonly timezone: any;\n\n constructor(unit: any, timezone = null) {\n super();\n this.unit = unit;\n this.timezone = timezone;\n }\n get typeId(): Type {\n return Type.Timestamp;\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Timestamp';\n }\n toString(): string {\n return `Timestamp<${TimeUnit[this.unit]}${this.timezone ? `, ${this.timezone}` : ''}>`;\n }\n}\n\nexport class TimestampSecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.SECOND, timezone);\n }\n}\nexport class TimestampMillisecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.MILLISECOND, timezone);\n }\n}\nexport class TimestampMicrosecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.MICROSECOND, timezone);\n }\n}\nexport class TimestampNanosecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.NANOSECOND, timezone);\n }\n}\n\nconst IntervalUnit = {\n DAY_TIME: 0,\n YEAR_MONTH: 1\n};\n\nexport class Interval extends DataType {\n readonly unit: number;\n constructor(unit: number) {\n super();\n this.unit = unit;\n }\n get typeId(): Type {\n return Type.Interval;\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Interval';\n }\n toString(): string {\n return `Interval<${IntervalUnit[this.unit]}>`;\n }\n}\n\nexport class IntervalDayTime extends Interval {\n constructor() {\n super(IntervalUnit.DAY_TIME);\n }\n}\nexport class IntervalYearMonth extends Interval {\n constructor() {\n super(IntervalUnit.YEAR_MONTH);\n }\n}\n\nexport class FixedSizeList extends DataType {\n readonly listSize: number;\n readonly children: Field[];\n\n constructor(listSize: number, child: Field) {\n super();\n this.listSize = listSize;\n this.children = [child];\n }\n get typeId(): Type {\n return Type.FixedSizeList;\n }\n get valueType() {\n return this.children[0].type;\n }\n get valueField() {\n return this.children[0];\n }\n // get ArrayType() {\n // return this.valueType.ArrayType;\n // }\n get [Symbol.toStringTag](): string {\n return 'FixedSizeList';\n }\n toString(): string {\n return `FixedSizeList[${this.listSize}]<${this.valueType}>`;\n }\n}\n","// This code is adapted from ArrowJS https://github.com/apache/arrow\n// under Apache license http://www.apache.org/licenses/LICENSE-2.0\n\n/**\n * Main data type enumeration.\n *\n * Data types in this library are all *logical*. They can be expressed as\n * either a primitive physical type (bytes or bits of some fixed size), a\n * nested type consisting of other data types, or another data type (e.g. a\n * timestamp encoded as an int64).\n *\n * **Note**: Only enum values 0-17 (NONE through Map) are written to an Arrow\n * IPC payload.\n *\n * The rest of the values are specified here so TypeScript can narrow the type\n * signatures further beyond the base Arrow Types. The Arrow DataTypes include\n * metadata like `bitWidth` that impact the type signatures of the values we\n * accept and return.\n *\n * For example, the `Int8Vector` reads 1-byte numbers from an `Int8Array`, an\n * `Int32Vector` reads a 4-byte number from an `Int32Array`, and an `Int64Vector`\n * reads a pair of 4-byte lo, hi 32-bit integers as a zero-copy slice from the\n * underlying `Int32Array`.\n *\n * Library consumers benefit by knowing the narrowest type, since we can ensure\n * the types across all public methods are propagated, and never bail to `any`.\n * These values are _never_ used at runtime, and they will _never_ be written\n * to the flatbuffers metadata of serialized Arrow IPC payloads.\n */\nexport enum Type {\n /** The default placeholder type */\n NONE = 0,\n /** A NULL type having no physical storage */\n Null = 1,\n /** Signed or unsigned 8, 16, 32, or 64-bit little-endian integer */\n Int = 2,\n /** 2, 4, or 8-byte floating point value */\n Float = 3,\n /** Variable-length bytes (no guarantee of UTF8-ness) */\n Binary = 4,\n /** UTF8 variable-length string as List<Char> */\n Utf8 = 5,\n /** Boolean as 1 bit, LSB bit-packed ordering */\n Bool = 6,\n /** Precision-and-scale-based decimal type. Storage type depends on the parameters. */\n Decimal = 7,\n /** int32_t days or int64_t milliseconds since the UNIX epoch */\n Date = 8,\n /** Time as signed 32 or 64-bit integer, representing either seconds, milliseconds, microseconds, or nanoseconds since midnight since midnight */\n Time = 9,\n /** Exact timestamp encoded with int64 since UNIX epoch (Default unit millisecond) */\n Timestamp = 10,\n /** YEAR_MONTH or DAY_TIME interval in SQL style */\n Interval = 11,\n /** A list of some logical data type */\n List = 12,\n /** Struct of logical types */\n Struct = 13,\n /** Union of logical types */\n Union = 14,\n /** Fixed-size binary. Each value occupies the same number of bytes */\n FixedSizeBinary = 15,\n /** Fixed-size list. Each value occupies the same number of bytes */\n FixedSizeList = 16,\n /** Map of named logical types */\n Map = 17,\n\n /** Dictionary aka Category type */\n Dictionary = -1,\n Int8 = -2,\n Int16 = -3,\n Int32 = -4,\n Int64 = -5,\n Uint8 = -6,\n Uint16 = -7,\n Uint32 = -8,\n Uint64 = -9,\n Float16 = -10,\n Float32 = -11,\n Float64 = -12,\n DateDay = -13,\n DateMillisecond = -14,\n TimestampSecond = -15,\n TimestampMillisecond = -16,\n TimestampMicrosecond = -17,\n TimestampNanosecond = -18,\n TimeSecond = -19,\n TimeMillisecond = -20,\n TimeMicrosecond = -21,\n TimeNanosecond = -22,\n DenseUnion = -23,\n SparseUnion = -24,\n IntervalDayTime = -25,\n IntervalYearMonth = -26\n}\n","// Type deduction\nimport {\n Schema\n // Int,\n // Int8,\n // Int16,\n // Int32,\n // Uint8,\n // Uint16,\n // Uint32,\n // Float32,\n // Float64\n // Bool,\n // Utf8,\n // TimestampMillisecond,\n // Null\n} from '../schema';\n\n// const TYPED_ARRAY_TO_TYPE = {\n// Int8Array: new Int8(),\n// Int16Array: new Int16(),\n// Int32Array: new Int32(),\n// Uint8Array: new Uint8(),\n// Uint8ClampedArray: new Uint8(),\n// Uint16Array: new Uint16(),\n// Uint32Array: new Uint32(),\n// Float32Array: new Float32(),\n// Float64Array: new Float64()\n// };\n\n// if (typeof BigInt64Array !== 'undefined') {\n// TYPED_ARRAY_TO_TYPE.BigInt64Array = new Int64();\n// TYPED_ARRAY_TO_TYPE.BigUint64Array = new Uint64();\n// }\n\n/**\n * SCHEMA SUPPORT - AUTODEDUCTION\n * @param {*} table\n * @param {*} schema\n * @returns\n */\nexport function deduceTableSchema(table, schema?: Schema) {\n const deducedSchema = Array.isArray(table)\n ? deduceSchemaForRowTable(table)\n : deduceSchemaForColumnarTable(table);\n // Deduced schema will fill in missing info from partial options.schema, if provided\n return Object.assign(deducedSchema, schema);\n}\n\nfunction deduceSchemaForColumnarTable(columnarTable) {\n const schema = {};\n for (const field in columnarTable) {\n const column = columnarTable[field];\n // Check if column is typed, if so we are done\n if (ArrayBuffer.isView(column)) {\n schema[field] = column.constructor;\n // else we need data\n } else if (column.length) {\n const value = column[0];\n schema[field] = deduceTypeFromValue(value);\n // TODO - support nested schemas?\n }\n // else we mark as present but unknow\n schema[field] = schema[field] || null;\n }\n return schema;\n}\n\nfunction deduceSchemaForRowTable(rowTable) {\n const schema = {};\n if (rowTable.length) {\n const row = rowTable[0];\n // TODO - Could look at additional rows if nulls in first row\n for (const field in row) {\n const value = row[field];\n schema[field] = deduceTypeFromValue(value);\n }\n }\n return schema;\n}\n\nfunction deduceTypeFromValue(value) {\n if (value instanceof Date) {\n return Date;\n } else if (value instanceof Number) {\n return Float32Array;\n } else if (typeof value === 'string') {\n return String;\n }\n return null;\n}\n\n/*\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction deduceSchema(rows) {\n const row = rows[0];\n\n const schema = {};\n let i = 0;\n for (const columnName in row) {\n const value = row[columnName];\n switch (typeof value) {\n case 'number':\n case 'boolean':\n // TODO - booleans could be handled differently...\n schema[columnName] = {name: String(columnName), index: i, type: Float32Array};\n break;\n\n case 'object':\n schema[columnName] = {name: String(columnName), index: i, type: Array};\n break;\n\n case 'string':\n default:\n schema[columnName] = {name: String(columnName), index: i, type: Array};\n // We currently only handle numeric rows\n // TODO we could offer a function to map strings to numbers?\n }\n i++;\n }\n return schema;\n}\n*/\n","import {Type} from '../schema';\nimport {AnyArray} from '../../types';\n\n/**\n * Gets type information from an Arrow type object or \"mock\" Arrow type object\n * @param arrowTypeLike Arrow Type or type object of similar shape\n */\nexport function getTypeInfo(arrowTypeLike: any): {\n typeId: Type;\n ArrayType: AnyArray;\n typeName: string;\n typeEnumName?: string;\n precision?: number;\n} {\n return {\n typeId: arrowTypeLike.typeId,\n ArrayType: arrowTypeLike.ArrayType,\n typeName: arrowTypeLike.toString(),\n typeEnumName: getTypeKey(arrowTypeLike.typeId),\n precision: arrowTypeLike.precision\n };\n}\n\nlet ReverseType: {[key: string]: string} | null = null;\n\nfunction getTypeKey(typeKey) {\n if (!ReverseType) {\n ReverseType = {};\n for (const key in Type) {\n ReverseType[Type[key]] = key;\n }\n }\n\n return ReverseType[typeKey];\n}\n","import type {TypedArray} from '../../types';\nimport {DataType, Float32, Float64, Int16, Int32, Int8, Uint16, Uint32, Uint8} from '../schema';\n\nexport function getArrowTypeFromTypedArray(array: TypedArray): DataType {\n switch (array.constructor) {\n case Int8Array:\n return new Int8();\n case Uint8Array:\n return new Uint8();\n case Int16Array:\n return new Int16();\n case Uint16Array:\n return new Uint16();\n case Int32Array:\n return new Int32();\n case Uint32Array:\n return new Uint32();\n case Float32Array:\n return new Float32();\n case Float64Array:\n return new Float64();\n default:\n throw new Error('array type not supported');\n }\n}\n","// From https://github.com/rauschma/async-iter-demo/tree/master/src under MIT license\n// http://2ality.com/2016/10/asynchronous-iteration.html\n\nclass ArrayQueue<T> extends Array<T> {\n enqueue(value) {\n // Add at the end\n return this.push(value);\n }\n dequeue(): T {\n // Remove first element\n return this.shift() as T;\n }\n}\n\nexport default class AsyncQueue<T> {\n private _values: ArrayQueue<T>;\n private _settlers: ArrayQueue<{resolve; reject}>;\n private _closed: boolean;\n\n constructor() {\n // enqueues > dequeues\n this._values = new ArrayQueue<T>();\n // dequeues > enqueues\n this._settlers = new ArrayQueue<{resolve; reject}>();\n this._closed = false;\n }\n\n close(): void {\n while (this._settlers.length > 0) {\n this._settlers.dequeue().resolve({done: true});\n }\n this._closed = true;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this;\n }\n\n enqueue(value: T | Error): void {\n if (this._closed) {\n throw new Error('Closed');\n }\n\n if (this._settlers.length > 0) {\n if (this._values.length > 0) {\n throw new Error('Illegal internal state');\n }\n const settler = this._settlers.dequeue();\n if (value instanceof Error) {\n settler.reject(value);\n } else {\n settler.resolve({value});\n }\n } else {\n this._values.enqueue(value);\n }\n }\n\n /**\n * @returns a Promise for an IteratorResult\n */\n next(): Promise<any> {\n if (this._values.length > 0) {\n const value = this._values.dequeue();\n if (value instanceof Error) {\n return Promise.reject(value);\n }\n return Promise.resolve({value});\n }\n\n if (this._closed) {\n if (this._settlers.length > 0) {\n throw new Error('Illegal internal state');\n }\n return Promise.resolve({done: true});\n }\n // Wait for new values to be enqueued\n return new Promise((resolve, reject) => {\n this._settlers.enqueue({resolve, reject});\n });\n }\n}\n\n/**\n * @returns a Promise for an Array with the elements in `asyncIterable`\n */\nexport async function takeAsync(\n asyncIterable: AsyncIterable<any>,\n count = Infinity\n): Promise<any[]> {\n const result: Array<any> = [];\n const iterator = asyncIterable[Symbol.asyncIterator]();\n while (result.length < count) {\n const {value, done} = await iterator.next();\n if (done) {\n break;\n }\n result.push(value);\n }\n return result;\n}\n","// TYPES\nexport type {\n Loader,\n LoaderWithParser,\n LoaderContext,\n LoaderOptions,\n Writer,\n WriterOptions,\n DataType,\n SyncDataType,\n BatchableDataType,\n IFileSystem,\n IRandomAccessReadFileSystem\n} from './types';\n\n// GENERAL UTILS\nexport {assert} from './lib/env-utils/assert';\nexport {\n isBrowser,\n isWorker,\n nodeVersion,\n self,\n window,\n global,\n document\n} from './lib/env-utils/globals';\n\n// LOADERS.GL-SPECIFIC WORKER UTILS\nexport {createLoaderWorker} from './lib/worker-loader-utils/create-loader-worker';\nexport {parseWithWorker, canParseWithWorker} from './lib/worker-loader-utils/parse-with-worker';\n\n// PARSER UTILS\nexport {parseJSON} from './lib/parser-utils/parse-json';\n\n// MEMORY COPY UTILS\nexport {\n toArrayBuffer,\n sliceArrayBuffer,\n concatenateArrayBuffers,\n concatenateTypedArrays,\n compareArrayBuffers\n} from './lib/binary-utils/array-buffer-utils';\nexport {padToNBytes, copyToArray, copyArrayBuffer} from './lib/binary-utils/memory-copy-utils';\nexport {\n copyPaddedArrayBufferToDataView,\n copyPaddedStringToDataView\n} from './lib/binary-utils/binary-copy-utils';\nexport {\n padStringToByteAlignment,\n copyStringToDataView,\n copyBinaryToDataView\n} from './lib/binary-utils/encode-utils';\nexport {getFirstCharacters, getMagicString} from './lib/binary-utils/get-first-characters';\n\n// ITERATOR UTILS\nexport {\n makeTextEncoderIterator,\n makeTextDecoderIterator,\n makeLineIterator,\n makeNumberedLineIterator\n} from './lib/iterators/text-iterators';\nexport {forEach, concatenateArrayBuffersAsync} from './lib/iterators/async-iteration';\n\n// REQUEST UTILS\nexport {default as RequestScheduler} from './lib/request-utils/request-scheduler';\n\n// NODE `path`` REPLACEMENT\nimport * as path from './lib/path-utils/path';\nexport {path};\nexport {setPathPrefix, getPathPrefix, resolvePath} from './lib/path-utils/file-aliases';\nexport {addAliases as _addAliases} from './lib/path-utils/file-aliases';\n\n// NODE `fs` WRAPPERS\nimport * as fs from './lib/node/fs';\nexport {fs};\n\n// NODE `buffer` WRAPPERS\nexport {isBuffer, toBuffer, bufferToArrayBuffer} from './lib/binary-utils/buffer-utils';\n\nexport {JSONLoader} from './json-loader';\n","// Purpose: include this in your module to avoid\n// dependencies on micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\ntype obj = {[key: string]: any};\nconst self_: obj = globals.self || globals.window || globals.global || {};\nconst window_: obj = globals.window || globals.self || globals.global || {};\nconst global_: obj = globals.global || globals.self || globals.window || {};\nconst document_: obj = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\n/** true if running in a browser */\nexport const isBrowser: boolean =\n // @ts-ignore process does not exist on browser\n typeof process !== 'object' || String(process) !== '[object process]' || process.browser;\n\n/** true if running in a worker thread */\nexport const isWorker: boolean = typeof importScripts === 'function';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\n/** Major Node version (as a number) */\nexport const nodeVersion: number = (matches && parseFloat(matches[1])) || 0;\n","/* eslint-disable no-restricted-globals */\nimport type {LoaderWithParser} from '../../types';\nimport {WorkerBody} from '@loaders.gl/worker-utils';\n// import {validateLoaderVersion} from './validate-loader-version';\n\nlet requestId = 0;\n\n/**\n * Set up a WebWorkerGlobalScope to talk with the main thread\n * @param loader\n */\nexport function createLoaderWorker(loader: LoaderWithParser) {\n // Check that we are actually in a worker thread\n if (typeof self === 'undefined') {\n return;\n }\n\n WorkerBody.onmessage = async (type, payload) => {\n switch (type) {\n case 'process':\n try {\n // validateLoaderVersion(loader, data.source.split('@')[1]);\n\n const {input, options = {}} = payload;\n\n const result = await parseData({\n loader,\n arrayBuffer: input,\n options,\n context: {\n parse: parseOnMainThread\n }\n });\n WorkerBody.postMessage('done', {result});\n } catch (error) {\n const message = error instanceof Error ? error.message : '';\n WorkerBody.postMessage('error', {error: message});\n }\n break;\n default:\n }\n };\n}\n\nfunction parseOnMainThread(arrayBuffer: ArrayBuffer, options: {[key: string]: any}): Promise<void> {\n return new Promise((resolve, reject) => {\n const id = requestId++;\n\n /**\n */\n const onMessage = (type, payload) => {\n if (payload.id !== id) {\n // not ours\n return;\n }\n\n switch (type) {\n case 'done':\n WorkerBody.removeEventListener(onMessage);\n resolve(payload.result);\n break;\n\n case 'error':\n WorkerBody.removeEventListener(onMessage);\n reject(payload.error);\n break;\n\n default:\n // ignore\n }\n };\n\n WorkerBody.addEventListener(onMessage);\n\n // Ask the main thread to decode data\n const payload = {id, input: arrayBuffer, options};\n WorkerBody.postMessage('process', payload);\n });\n}\n\n// TODO - Support byteOffset and byteLength (enabling parsing of embedded binaries without copies)\n// TODO - Why not support async loader.parse* funcs here?\n// TODO - Why not reuse a common function instead of reimplementing loader.parse* selection logic? Keeping loader small?\n// TODO - Lack of appropriate parser functions can be detected when we create worker, no need to wait until parse\nasync function parseData({loader, arrayBuffer, options, context}) {\n let data;\n let parser;\n if (loader.parseSync || loader.parse) {\n data = arrayBuffer;\n parser = loader.parseSync || loader.parse;\n } else if (loader.parseTextSync) {\n const textDecoder = new TextDecoder();\n data = textDecoder.decode(arrayBuffer);\n parser = loader.parseTextSync;\n } else {\n throw new Error(`Could not load data with ${loader.name} loader`);\n }\n\n // TODO - proper merge in of loader options...\n options = {\n ...options,\n modules: (loader && loader.options && loader.options.modules) || {},\n worker: false\n };\n\n return await parser(data, {...options}, context, loader);\n}\n","import {assert} from '../env-utils/assert';\n\nconst workerURLCache = new Map();\n\n/**\n * Creates a loadable URL from worker source or URL\n * that can be used to create `Worker` instances.\n * Due to CORS issues it may be necessary to wrap a URL in a small importScripts\n * @param props\n * @param props.source Worker source\n * @param props.url Worker URL\n * @returns loadable url\n */\nexport function getLoadableWorkerURL(props: {source?: string; url?: string}) {\n assert((props.source && !props.url) || (!props.source && props.url)); // Either source or url must be defined\n\n let workerURL = workerURLCache.get(props.source || props.url);\n if (!workerURL) {\n // Differentiate worker urls from worker source code\n if (props.url) {\n workerURL = getLoadableWorkerURLFromURL(props.url);\n workerURLCache.set(props.url, workerURL);\n }\n\n if (props.source) {\n workerURL = getLoadableWorkerURLFromSource(props.source);\n workerURLCache.set(props.source, workerURL);\n }\n }\n\n assert(workerURL);\n return workerURL;\n}\n\n/**\n * Build a loadable worker URL from worker URL\n * @param url\n * @returns loadable URL\n */\nfunction getLoadableWorkerURLFromURL(url: string): string {\n // A local script url, we can use it to initialize a Worker directly\n if (!url.startsWith('http')) {\n return url;\n }\n\n // A remote script, we need to use `importScripts` to load from different origin\n const workerSource = buildScriptSource(url);\n return getLoadableWorkerURLFromSource(workerSource);\n}\n\n/**\n * Build a loadable worker URL from worker source\n * @param workerSource\n * @returns loadable url\n */\nfunction getLoadableWorkerURLFromSource(workerSource: string): string {\n // NOTE: webworkify was previously used\n // const blob = webworkify(workerSource, {bare: true});\n const blob = new Blob([workerSource], {type: 'application/javascript'});\n return URL.createObjectURL(blob);\n}\n\n/**\n * Per spec, worker cannot be initialized with a script from a different origin\n * However a local worker script can still import scripts from other origins,\n * so we simply build a wrapper script.\n *\n * @param workerUrl\n * @returns source\n */\nfunction buildScriptSource(workerUrl: string): string {\n return `\\\ntry {\n importScripts('${workerUrl}');\n} catch (error) {\n console.error(error);\n throw error;\n}`;\n}\n","import type {\n WorkerObject,\n WorkerOptions,\n WorkerContext,\n WorkerMessageType,\n WorkerMessagePayload\n} from '../../types';\nimport type WorkerJob from '../worker-farm/worker-job';\nimport WorkerFarm from '../worker-farm/worker-farm';\nimport {removeNontransferableOptions} from '../worker-utils/remove-nontransferable-options';\nimport {getWorkerURL, getWorkerName} from './get-worker-url';\n\ntype ProcessOnWorkerOptions = WorkerOptions & {\n jobName?: string;\n [key: string]: any;\n};\n\n/**\n * Determines if we can parse with worker\n * @param loader\n * @param data\n * @param options\n */\nexport function canProcessOnWorker(worker: WorkerObject, options?: WorkerOptions) {\n if (!WorkerFarm.isSupported()) {\n return false;\n }\n\n return worker.worker && options?.worker;\n}\n\n/**\n * This function expects that the worker thread sends certain messages,\n * Creating such a worker can be automated if the worker is wrapper by a call to\n * createWorker in @loaders.gl/worker-utils.\n */\nexport async function processOnWorker(\n worker: WorkerObject,\n data: any,\n options: ProcessOnWorkerOptions = {},\n context: WorkerContext = {}\n): Promise<any> {\n const name = getWorkerName(worker);\n const url = getWorkerURL(worker, options);\n\n const workerFarm = WorkerFarm.getWorkerFarm(options);\n const workerPool = workerFarm.getWorkerPool({name, url});\n\n const jobName = options.jobName || worker.name;\n const job = await workerPool.startJob(\n jobName,\n // eslint-disable-next-line\n onMessage.bind(null, context)\n );\n\n // Kick off the processing in the worker\n const transferableOptions = removeNontransferableOptions(options);\n job.postMessage('process', {input: data, options: transferableOptions});\n\n const result = await job.result;\n return result.result;\n}\n\n/**\n * Job completes when we receive the result\n * @param job\n * @param message\n */\nasync function onMessage(\n context: WorkerContext,\n job: WorkerJob,\n type: WorkerMessageType,\n payload: WorkerMessagePayload\n) {\n switch (type) {\n case 'done':\n // Worker is done\n job.done(payload);\n break;\n\n case 'error':\n // Worker encountered an error\n job.error(payload.error);\n break;\n\n case 'process':\n // Worker is asking for us (main thread) to process something\n const {id, input, options} = payload;\n try {\n if (!context.process) {\n job.postMessage('error', {id, error: 'Worker not set up to process on main thread'});\n return;\n }\n const result = await context.process(input, options);\n job.postMessage('done', {id, result});\n } catch (error) {\n const message = error instanceof Error ? error.message : 'unknown error';\n job.postMessage('error', {id, error: message});\n }\n break;\n\n default:\n // eslint-disable-next-line\n console.warn(`process-on-worker: unknown message ${type}`);\n }\n}\n","/**\n * Safely stringify JSON (drop non serializable values like functions and regexps)\n * @param value\n */\nexport function removeNontransferableOptions(object: object): object {\n // options.log object contains functions which cannot be transferred\n // TODO - decide how to handle logging on workers\n // TODO - warn if options stringification is long\n return JSON.parse(stringifyJSON(object));\n}\n\nfunction stringifyJSON(v) {\n const cache = new Set();\n return JSON.stringify(v, (key, value) => {\n if (typeof value === 'object' && value !== null) {\n if (cache.has(value)) {\n // Circular reference found\n try {\n // If this value does not reference a parent it can be deduped\n return JSON.parse(JSON.stringify(value));\n } catch (err) {\n // discard key if value cannot be deduped\n return undefined;\n }\n }\n // Store value in our set\n cache.add(value);\n }\n return value;\n });\n}\n","import type {\n WorkerMessageType,\n WorkerMessagePayload,\n WorkerContext,\n Process,\n ProcessInBatches\n} from '../../types';\nimport AsyncQueue from '../async-queue/async-queue';\nimport WorkerBody from '../worker-farm/worker-body';\n// import {validateWorkerVersion} from './validate-worker-version';\n\n/** Counter for jobs */\nlet requestId = 0;\nlet inputBatches;\nlet options;\n\nexport type ProcessOnMainThread = (data: any, options?: {[key: string]: any}, context?) => any;\n\n/**\n * Set up a WebWorkerGlobalScope to talk with the main thread\n */\nexport function createWorker(process: Process, processInBatches?: ProcessInBatches): void {\n // Check that we are actually in a worker thread\n if (typeof self === 'undefined') {\n return;\n }\n\n const context: WorkerContext = {\n process: processOnMainThread\n };\n\n // eslint-disable-next-line complexity\n WorkerBody.onmessage = async (type: WorkerMessageType, payload: WorkerMessagePayload) => {\n try {\n switch (type) {\n case 'process':\n if (!process) {\n throw new Error('Worker does not support atomic processing');\n }\n const result = await process(payload.input, payload.options || {}, context);\n WorkerBody.postMessage('done', {result});\n break;\n\n case 'process-in-batches':\n if (!processInBatches) {\n throw new Error('Worker does not support batched processing');\n }\n inputBatches = new AsyncQueue();\n options = payload.options || {};\n const resultIterator = processInBatches(inputBatches, options, context?.processInBatches);\n for await (const batch of resultIterator) {\n WorkerBody.postMessage('output-batch', {result: batch});\n }\n WorkerBody.postMessage('done', {});\n break;\n\n case 'input-batch':\n inputBatches.push(payload.input);\n break;\n\n case 'input-done':\n inputBatches.close();\n break;\n\n default:\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : '';\n WorkerBody.postMessage('error', {error: message});\n }\n };\n}\n\nfunction processOnMainThread(arrayBuffer, options = {}) {\n return new Promise((resolve, reject) => {\n const id = requestId++;\n\n /**\n */\n const onMessage = (type, payload) => {\n if (payload.id !== id) {\n // not ours\n return;\n }\n\n switch (type) {\n case 'done':\n WorkerBody.removeEventListener(onMessage);\n resolve(payload.result);\n break;\n\n case 'error':\n WorkerBody.removeEventListener(onMessage);\n reject(payload.error);\n break;\n\n default:\n // ignore\n }\n };\n\n WorkerBody.addEventListener(onMessage);\n\n // Ask the main thread to decode data\n const payload = {id, input: arrayBuffer, options};\n WorkerBody.postMessage('process', payload);\n });\n}\n","import type {WorkerObject} from '../../types';\nimport {assert} from '../env-utils/assert';\nimport {VERSION} from '../env-utils/version';\n\n/**\n * Check if worker is compatible with this library version\n * @param worker\n * @param libVersion\n * @returns `true` if the two versions are compatible\n */\nexport function validateWorkerVersion(\n worker: WorkerObject,\n coreVersion: string = VERSION\n): boolean {\n assert(worker, 'no worker provided');\n\n const workerVersion = worker.version;\n if (!coreVersion || !workerVersion) {\n return false;\n }\n\n // TODO enable when fix the __version__ injection\n // const coreVersions = parseVersion(coreVersion);\n // const workerVersions = parseVersion(workerVersion);\n // assert(\n // coreVersion.major === workerVersion.major && coreVersion.minor <= workerVersion.minor,\n // `worker: ${worker.name} is not compatible. ${coreVersion.major}.${\n // coreVersion.minor\n // }+ is required.`\n // );\n\n return true;\n}\n\n// @ts-ignore\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction parseVersion(version) {\n const parts = version.split('.').map(Number);\n return {major: parts[0], minor: parts[1]};\n}\n","/* global importScripts */\nimport {global, isBrowser, isWorker} from '../env-utils/globals';\nimport * as node from '../node/require-utils.node';\nimport {assert} from '../env-utils/assert';\nimport {VERSION as __VERSION__} from '../env-utils/version';\n\n// TODO - unpkg.com doesn't seem to have a `latest` specifier for alpha releases...\nconst LATEST = 'beta';\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : LATEST;\n\nconst loadLibraryPromises = {}; // promises\n\n/**\n * Dynamically loads a library (\"module\")\n *\n * - wasm library: Array buffer is returned\n * - js library: Parse JS is returned\n *\n * Method depends on environment\n * - browser - script element is created and installed on document\n * - worker - eval is called on global context\n * - node - file is required\n *\n * @param libraryUrl\n * @param moduleName\n * @param options\n */\nexport async function loadLibrary(\n libraryUrl: string,\n moduleName: string | null = null,\n options: object = {}\n): Promise<any> {\n if (moduleName) {\n libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);\n }\n\n // Ensure libraries are only loaded once\n loadLibraryPromises[libraryUrl] =\n loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);\n return await loadLibraryPromises[libraryUrl];\n}\n\n// TODO - sort out how to resolve paths for main/worker and dev/prod\nexport function getLibraryUrl(library, moduleName?: string, options?): string {\n // Check if already a URL\n if (library.startsWith('http')) {\n return library;\n }\n\n // Allow application to import and supply libraries through `options.modules`\n const modules = options.modules || {};\n if (modules[library]) {\n return modules[library];\n }\n\n // Load from local files, not from CDN scripts in Node.js\n // TODO - needs to locate the modules directory when installed!\n if (!isBrowser) {\n return `modules/${moduleName}/dist/libs/${library}`;\n }\n\n // In browser, load from external scripts\n if (options.CDN) {\n assert(options.CDN.startsWith('http'));\n return `${options.CDN}/${moduleName}@${VERSION}/dist/libs/${library}`;\n }\n\n // TODO - loading inside workers requires paths relative to worker script location...\n if (isWorker) {\n return `../src/libs/${library}`;\n }\n\n return `modules/${moduleName}/src/libs/${library}`;\n}\n\nasync function loadLibraryFromFile(libraryUrl) {\n if (libraryUrl.endsWith('wasm')) {\n const response = await fetch(libraryUrl);\n return await response.arrayBuffer();\n }\n\n if (!isBrowser) {\n return node.requireFromFile && (await node.requireFromFile(libraryUrl));\n }\n if (isWorker) {\n return importScripts(libraryUrl);\n }\n // TODO - fix - should be more secure than string parsing since observes CORS\n // if (isBrowser) {\n // return await loadScriptFromFile(libraryUrl);\n // }\n\n const response = await fetch(libraryUrl);\n const scriptSource = await response.text();\n return loadLibraryFromString(scriptSource, libraryUrl);\n}\n\n/*\nasync function loadScriptFromFile(libraryUrl) {\n const script = document.createElement('script');\n script.src = libraryUrl;\n return await new Promise((resolve, reject) => {\n script.onload = data => {\n resolve(data);\n };\n script.onerror = reject;\n });\n}\n*/\n\n// TODO - Needs security audit...\n// - Raw eval call\n// - Potentially bypasses CORS\n// Upside is that this separates fetching and parsing\n// we could create a`LibraryLoader` or`ModuleLoader`\nfunction loadLibraryFromString(scriptSource, id) {\n if (!isBrowser) {\n return node.requireFromString && node.requireFromString(scriptSource, id);\n }\n\n if (isWorker) {\n // Use lvalue trick to make eval run in global scope\n eval.call(global, scriptSource); // eslint-disable-line no-eval\n // https://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript\n // http://perfectionkills.com/global-eval-what-are-the-options/\n return null;\n }\n\n const script = document.createElement('script');\n script.id = id;\n // most browsers like a separate text node but some throw an error. The second method covers those.\n try {\n script.appendChild(document.createTextNode(scriptSource));\n } catch (e) {\n script.text = scriptSource;\n }\n document.body.appendChild(script);\n return null;\n}\n\n// TODO - technique for module injection into worker, from THREE.DracoLoader...\n/*\nfunction combineWorkerWithLibrary(worker, jsContent) {\n var fn = wWorker.toString();\n var body = [\n '// injected',\n jsContent,\n '',\n '// worker',\n fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))\n ].join('\\n');\n this.workerSourceURL = URL.createObjectURL(new Blob([body]));\n}\n*/\n","import type {WorkerJob, WorkerMessageType, WorkerMessagePayload} from '@loaders.gl/worker-utils';\nimport type {Loader, LoaderOptions, LoaderContext} from '../../types';\nimport {WorkerFarm, getWorkerURL} from '@loaders.gl/worker-utils';\n\n/**\n * Determines if a loader can parse with worker\n * @param loader\n * @param options\n */\nexport function canParseWithWorker(loader: Loader, options?: LoaderOptions) {\n if (!WorkerFarm.isSupported()) {\n return false;\n }\n\n return loader.worker && options?.worker;\n}\n\n/**\n * this function expects that the worker function sends certain messages,\n * this can be automated if the worker is wrapper by a call to createLoaderWorker in @loaders.gl/loader-utils.\n */\nexport async function parseWithWorker(\n loader: Loader,\n data,\n options?: LoaderOptions,\n context?: LoaderContext,\n parseOnMainThread?: (arrayBuffer: ArrayBuffer, options: {[key: string]: any}) => Promise<void>\n) {\n const name = loader.id; // TODO\n const url = getWorkerURL(loader, options);\n\n const workerFarm = WorkerFarm.getWorkerFarm(options);\n const workerPool = workerFarm.getWorkerPool({name, url});\n\n // options.log object contains functions which cannot be transferred\n // TODO - decide how to handle logging on workers\n options = JSON.parse(JSON.stringify(options));\n\n const job = await workerPool.startJob(\n 'process-on-worker',\n // eslint-disable-next-line\n onMessage.bind(null, parseOnMainThread)\n );\n\n job.postMessage('process', {\n // @ts-ignore\n input: data,\n options\n });\n\n const result = await job.result;\n return await result.result;\n}\n\n/**\n * Handle worker's responses to the main thread\n * @param job\n * @param type\n * @param payload\n */\nasync function onMessage(\n parseOnMainThread,\n job: WorkerJob,\n type: WorkerMessageType,\n payload: WorkerMessagePayload\n) {\n switch (type) {\n case 'done':\n job.done(payload);\n break;\n\n case 'error':\n job.error(payload.error);\n break;\n\n case 'process':\n // Worker is asking for main thread to parseO\n const {id, input, options} = payload;\n try {\n const result = await parseOnMainThread(input, options);\n job.postMessage('done', {id, result});\n } catch (error) {\n const message = error instanceof Error ? error.message : 'unknown error';\n job.postMessage('error', {id, error: message});\n }\n break;\n\n default:\n // eslint-disable-next-line\n console.warn(`parse-with-worker unknown message ${type}`);\n }\n}\n","import {getFirstCharacters} from '../binary-utils/get-first-characters';\n\n/**\n * Minimal JSON parser that throws more meaningful error messages\n */\nexport function parseJSON(string: string): any {\n try {\n return JSON.parse(string);\n } catch (_) {\n throw new Error(`Failed to parse JSON from data starting with \"${getFirstCharacters(string)}\"`);\n }\n}\n","import {TypedArray} from '../../types';\nimport {padToNBytes} from './memory-copy-utils';\n\n/**\n * Copy sourceBuffer to dataView with some padding\n *\n * @param {DataView | null} dataView - destination data container. If null - only new offset is calculated\n * @param {number} byteOffset - destination byte offset to copy to\n * @param {Array | TypedArray} sourceBuffer - source data buffer\n * @param {number} padding - pad the resulting array to multiple of \"padding\" bytes. Additional bytes are filled with 0x20 (ASCII space)\n *\n * @return new byteOffset of resulting dataView\n */\nexport function copyPaddedArrayBufferToDataView(\n dataView: DataView | null,\n byteOffset: number,\n sourceBuffer: TypedArray,\n padding: number\n) {\n const paddedLength = padToNBytes(sourceBuffer.byteLength, padding);\n const padLength = paddedLength - sourceBuffer.byteLength;\n\n if (dataView) {\n // Copy array\n const targetArray = new Uint8Array(\n dataView.buffer,\n dataView.byteOffset + byteOffset,\n sourceBuffer.byteLength\n );\n const sourceArray = new Uint8Array(sourceBuffer);\n targetArray.set(sourceArray);\n\n // Add PADDING\n for (let i = 0; i < padLength; ++i) {\n // json chunk is padded with spaces (ASCII 0x20)\n dataView.setUint8(byteOffset + sourceBuffer.byteLength + i, 0x20);\n }\n }\n byteOffset += paddedLength;\n return byteOffset;\n}\n\n/**\n * Copy string to dataView with some padding\n *\n * @param {DataView | null} dataView - destination data container. If null - only new offset is calculated\n * @param {number} byteOffset - destination byte offset to copy to\n * @param {string} string - source string\n * @param {number} padding - pad the resulting array to multiple of \"padding\" bytes. Additional bytes are filled with 0x20 (ASCII space)\n *\n * @return new byteOffset of resulting dataView\n */\nexport function copyPaddedStringToDataView(\n dataView: DataView | null,\n byteOffset: number,\n string: string,\n padding: number\n): number {\n const textEncoder = new TextEncoder();\n // PERFORMANCE IDEA: We encode twice, once to get size and once to store\n // PERFORMANCE IDEA: Use TextEncoder.encodeInto() to avoid temporary copy\n const stringBuffer = textEncoder.encode(string);\n\n byteOffset = copyPaddedArrayBufferToDataView(dataView, byteOffset, stringBuffer, padding);\n\n return byteOffset;\n}\n","// Note: These were broken out from gltf loader...\n// eslint-disable-next-line complexity\n\n// PERFORMANCE IDEA: No need to copy string twice...\nexport function padStringToByteAlignment(string, byteAlignment) {\n const length = string.length;\n const paddedLength = Math.ceil(length / byteAlignment) * byteAlignment; // Round up to the required alignment\n const padding = paddedLength - length;\n let whitespace = '';\n for (let i = 0; i < padding; ++i) {\n whitespace += ' ';\n }\n return string + whitespace;\n}\n\nexport function copyStringToDataView(dataView, byteOffset, string, byteLength) {\n if (dataView) {\n for (let i = 0; i < byteLength; i++) {\n dataView.setUint8(byteOffset + i, string.charCodeAt(i));\n }\n }\n return byteOffset + byteLength;\n}\n\nexport function copyBinaryToDataView(dataView, byteOffset, binary, byteLength) {\n if (dataView) {\n for (let i = 0; i < byteLength; i++) {\n dataView.setUint8(byteOffset + i, binary[i]);\n }\n }\n return byteOffset + byteLength;\n}\n","// TextDecoder iterators\n// TextDecoder will keep any partial undecoded bytes between calls to `decode`\n\nexport async function* makeTextDecoderIterator(\n arrayBufferIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>,\n options: TextDecoderOptions = {}\n): AsyncIterable<string> {\n const textDecoder = new TextDecoder(undefined, options);\n for await (const arrayBuffer of arrayBufferIterator) {\n yield typeof arrayBuffer === 'string'\n ? arrayBuffer\n : textDecoder.decode(arrayBuffer, {stream: true});\n }\n}\n\n// TextEncoder iterator\n// TODO - this is not useful unless min chunk size is given\n// TextEncoder will keep any partial undecoded bytes between calls to `encode`\n// If iterator does not yield strings, assume arrayBuffer and return unencoded\n\nexport async function* makeTextEncoderIterator(\n textIterator: AsyncIterable<string> | Iterable<ArrayBuffer>\n): AsyncIterable<ArrayBuffer> {\n const textEncoder = new TextEncoder();\n for await (const text of textIterator) {\n yield typeof text === 'string' ? textEncoder.encode(text) : text;\n }\n}\n\n/**\n * @param textIterator async iterable yielding strings\n * @returns an async iterable over lines\n * See http://2ality.com/2018/04/async-iter-nodejs.html\n */\n\nexport async function* makeLineIterator(\n textIterator: AsyncIterable<string>\n): AsyncIterable<string> {\n let previous = '';\n for await (const textChunk of textIterator) {\n previous += textChunk;\n let eolIndex;\n while ((eolIndex = previous.indexOf('\\n')) >= 0) {\n // line includes the EOL\n const line = previous.slice(0, eolIndex + 1);\n previous = previous.slice(eolIndex + 1);\n yield line;\n }\n }\n\n if (previous.length > 0) {\n yield previous;\n }\n}\n\n/**\n * @param lineIterator async iterable yielding lines\n * @returns async iterable yielding numbered lines\n *\n * See http://2ality.com/2018/04/async-iter-nodejs.html\n */\nexport async function* makeNumberedLineIterator(\n lineIterator: AsyncIterable<string>\n): AsyncIterable<{counter: number; line: string}> {\n let counter = 1;\n for await (const line of lineIterator) {\n yield {counter, line};\n counter++;\n }\n}\n","import {concatenateArrayBuffers} from '../binary-utils/array-buffer-utils';\n\n// GENERAL UTILITIES\n\n/**\n * Iterate over async iterator, without resetting iterator if end is not reached\n * - forEach intentionally does not reset iterator if exiting loop prematurely\n * so that iteration can continue in a second loop\n * - It is recommended to use a standard for-await as last loop to ensure\n * iterator gets properly reset\n *\n * TODO - optimize using sync iteration if argument is an Iterable?\n *\n * @param iterator\n * @param visitor\n */\nexport async function forEach(iterator, visitor) {\n // eslint-disable-next-line\n while (true) {\n const {done, value} = await iterator.next();\n if (done) {\n iterator.return();\n return;\n }\n const cancel = visitor(value);\n if (cancel) {\n return;\n }\n }\n}\n\n// Breaking big data into iterable chunks, concatenating iterable chunks into big data objects\n\n/**\n * Concatenates all data chunks yielded by an (async) iterator\n * This function can e.g. be used to enable atomic parsers to work on (async) iterator inputs\n */\n\nexport async function concatenateArrayBuffersAsync(\n asyncIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>\n): Promise<ArrayBuffer> {\n const arrayBuffers: ArrayBuffer[] = [];\n for await (const chunk of asyncIterator) {\n arrayBuffers.push(chunk);\n }\n return concatenateArrayBuffers(...arrayBuffers);\n}\n\nexport async function concatenateStringsAsync(\n asyncIterator: AsyncIterable<string> | Iterable<string>\n): Promise<string> {\n const strings: string[] = [];\n for await (const chunk of asyncIterator) {\n strings.push(chunk);\n }\n return strings.join('');\n}\n","import {Stats} from '@probe.gl/stats';\n\ntype Handle = any;\ntype DoneFunction = () => any;\ntype GetPriorityFunction = () => number;\ntype RequestResult = {\n done: DoneFunction;\n} | null;\n\n/** RequestScheduler Options */\nexport type RequestSchedulerProps = {\n id?: string;\n throttleRequests?: boolean;\n maxRequests?: number;\n};\n\nconst STAT_QUEUED_REQUESTS = 'Queued Requests';\nconst STAT_ACTIVE_REQUESTS = 'Active Requests';\nconst STAT_CANCELLED_REQUESTS = 'Cancelled Requests';\nconst STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';\nconst STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';\n\nconst DEFAULT_PROPS: Required<RequestSchedulerProps> = {\n id: 'request-scheduler',\n // Specifies if the request scheduler should throttle incoming requests, mainly for comparative testing\n throttleRequests: true,\n // The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.\n maxRequests: 6\n};\n\n/** Tracks one request */\ntype Request = {\n handle: Handle;\n priority: number;\n getPriority: GetPriorityFunction;\n resolve?: (value: any) => any;\n};\n\n/**\n * Used to issue a request, without having them \"deeply queued\" by the browser.\n * @todo - Track requests globally, across multiple servers\n */\nexport default class RequestScheduler {\n readonly props: Required<RequestSchedulerProps>;\n readonly stats: Stats;\n activeRequestCount: number = 0;\n\n /** Tracks the number of active requests and prioritizes/cancels queued requests. */\n private requestQueue: Request[] = [];\n private requestMap: Map<Handle, Promise<RequestResult>> = new Map();\n private deferredUpdate: any = null;\n\n constructor(props: RequestSchedulerProps = {}) {\n this.props = {...DEFAULT_PROPS, ...props};\n\n // Returns the statistics used by the request scheduler.\n this.stats = new Stats({id: this.props.id});\n this.stats.get(STAT_QUEUED_REQUESTS);\n this.stats.get(STAT_ACTIVE_REQUESTS);\n this.stats.get(STAT_CANCELLED_REQUESTS);\n this.stats.get(STAT_QUEUED_REQUESTS_EVER);\n this.stats.get(STAT_ACTIVE_REQUESTS_EVER);\n }\n\n /**\n * Called by an application that wants to issue a request, without having it deeply queued by the browser\n *\n * When the returned promise resolved, it is OK for the application to issue a request.\n * The promise resolves to an object that contains a `done` method.\n * When the application's request has completed (or failed), the application must call the `done` function\n *\n * @param handle\n * @param getPriority will be called when request \"slots\" open up,\n * allowing the caller to update priority or cancel the request\n * Highest priority executes first, priority < 0 cancels the request\n * @returns a promise\n * - resolves to a object (with a `done` field) when the request can be issued without queueing,\n * - resolves to `null` if the request has been cancelled (by the callback return < 0).\n * In this case the application should not issue the request\n */\n scheduleRequest(\n handle: Handle,\n getPriority: GetPriorityFunction = () => 0\n ): Promise<RequestResult> {\n // Allows throttling to be disabled\n if (!this.props.throttleRequests) {\n return Promise.resolve({done: () => {}});\n }\n\n // dedupe\n if (this.requestMap.has(handle)) {\n return this.requestMap.get(handle) as Promise<any>;\n }\n\n const request: Request = {handle, priority: 0, getPriority};\n const promise = new Promise<RequestResult>((resolve) => {\n // @ts-ignore\n request.resolve = resolve;\n return request;\n });\n\n this.requestQueue.push(request);\n this.requestMap.set(handle, promise);\n this._issueNewRequests();\n return promise;\n }\n\n // PRIVATE\n\n _issueRequest(request: Request): Promise<any> {\n const {handle, resolve} = request;\n let isDone = false;\n\n const done = () => {\n // can only be called once\n if (!isDone) {\n isDone = true;\n\n // Stop tracking a request - it has completed, failed, cancelled etc\n this.requestMap.delete(handle);\n this.activeRequestCount--;\n // A slot just freed up, see if any queued requests are waiting\n this._issueNewRequests();\n }\n };\n\n // Track this request\n this.activeRequestCount++;\n\n return resolve ? resolve({done}) : Promise.resolve({done});\n }\n\n /** We check requests asynchronously, to prevent multiple updates */\n _issueNewRequests(): void {\n if (!this.deferredUpdate) {\n this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);\n }\n }\n\n /** Refresh all requests */\n _issueNewRequestsAsync() {\n // TODO - shouldn't we clear the timeout?\n this.deferredUpdate = null;\n\n const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);\n\n if (freeSlots === 0) {\n return;\n }\n\n this._updateAllRequests();\n\n // Resolve pending promises for the top-priority requests\n for (let i = 0; i < freeSlots; ++i) {\n const request = this.requestQueue.shift();\n if (request) {\n this._issueRequest(request); // eslint-disable-line @typescript-eslint/no-floating-promises\n }\n }\n\n // Uncomment to debug\n // console.log(`${freeSlots} free slots, ${this.requestQueue.length} queued requests`);\n }\n\n /** Ensure all requests have updated priorities, and that no longer valid requests are cancelled */\n _updateAllRequests() {\n const requestQueue = this.requestQueue;\n for (let i = 0; i < requestQueue.length; ++i) {\n const request = requestQueue[i];\n if (!this._updateRequest(request)) {\n // Remove the element and make sure to adjust the counter to account for shortened array\n requestQueue.splice(i, 1);\n this.requestMap.delete(request.handle);\n i--;\n }\n }\n\n // Sort the remaining requests based on priority\n requestQueue.sort((a, b) => a.priority - b.priority);\n }\n\n /** Update a single request by calling the callback */\n _updateRequest(request) {\n request.priority = request.getPriority(request.handle); // eslint-disable-line callback-return\n\n // by returning a negative priority, the callback cancels the request\n if (request.priority < 0) {\n request.resolve(null);\n return false;\n }\n return true;\n }\n}\n","// Beginning of a minimal implementation of the Node.js path API, that doesn't pull in big polyfills.\n\n/**\n * Replacement for Node.js path.dirname\n * @param url\n */\nexport function dirname(url: string): string {\n const slashIndex = url && url.lastIndexOf('/');\n return slashIndex >= 0 ? url.substr(0, slashIndex as number) : '';\n}\n\n/**\n * Replacement for Node.js path.join\n * @param parts\n */\nexport function join(...parts: string[]): string {\n const separator = '/';\n parts = parts.map((part, index) => {\n if (index) {\n part = part.replace(new RegExp(`^${separator}`), '');\n }\n if (index !== parts.length - 1) {\n part = part.replace(new RegExp(`${separator}$`), '');\n }\n return part;\n });\n return parts.join(separator);\n}\n","// Simple file alias mechanisms for tests.\n\nlet pathPrefix = '';\nconst fileAliases: {[aliasPath: string]: string} = {};\n\n/*\n * Set a relative path prefix\n */\nexport function setPathPrefix(prefix: string): void {\n pathPrefix = prefix;\n}\n\n/*\n * Get the relative path prefix\n */\nexport function getPathPrefix(): string {\n return pathPrefix;\n}\n\n/**\n *\n * @param aliases\n *\n * Note: addAliases are an experimental export, they are only for testing of loaders.gl loaders\n * not intended as a generic aliasing mechanism\n */\nexport function addAliases(aliases: {[aliasPath: string]: string}): void {\n Object.assign(fileAliases, aliases);\n}\n\n/**\n * Resolves aliases and adds path-prefix to paths\n */\nexport function resolvePath(filename: string): string {\n for (const alias in fileAliases) {\n if (filename.startsWith(alias)) {\n const replacement = fileAliases[alias];\n filename = filename.replace(alias, replacement);\n }\n }\n if (!filename.startsWith('http://') && !filename.startsWith('https://')) {\n filename = `${pathPrefix}${filename}`;\n }\n return filename;\n}\n","import * as node from '../node/buffer-utils.node';\n\n/**\n * Check for Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n */\nexport function isBuffer(value: any): boolean {\n return value && typeof value === 'object' && value.isBuffer;\n}\n\n/**\n * Converts to Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n * @todo better data type\n */\nexport function toBuffer(data: any): Buffer {\n return node.toBuffer ? node.toBuffer(data) : data;\n}\n\n/**\n * Converts Node.js `Buffer` to `ArrayBuffer` (without triggering bundler to include Buffer polyfill on browser)\n * @todo better data type\n */\nexport function bufferToArrayBuffer(data: any): ArrayBuffer {\n if (node.toArrayBuffer) {\n // TODO - per docs we should just be able to call buffer.buffer, but there are issues\n return node.toArrayBuffer(data);\n }\n return data;\n}\n","import type {LoaderWithParser} from './types';\n\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n\n/**\n * A JSON Micro loader (minimal bundle size)\n * Alternative to `@loaders.gl/json`\n */\nexport const JSONLoader = {\n name: 'JSON',\n id: 'json',\n module: 'json',\n version: VERSION,\n extensions: ['json', 'geojson'],\n mimeTypes: ['application/json'],\n category: 'json',\n text: true,\n parseTextSync,\n parse: async (arrayBuffer) => parseTextSync(new TextDecoder().decode(arrayBuffer)),\n options: {}\n};\n\n// TODO - deprecated\nfunction parseTextSync(text) {\n return JSON.parse(text);\n}\n\nexport const _typecheckJSONLoader: LoaderWithParser = JSONLoader;\n","import {default as JSONParser} from './json-parser';\nimport JSONPath from '../jsonpath/jsonpath';\n\n/**\n * The `StreamingJSONParser` looks for the first array in the JSON structure.\n * and emits an array of chunks\n */\nexport default class StreamingJSONParser extends JSONParser {\n private jsonPaths: JSONPath[];\n private streamingJsonPath: JSONPath | null = null;\n private streamingArray: any[] | null = null;\n private topLevelObject: object | null = null;\n\n constructor(options: {[key: string]: any} = {}) {\n super();\n const jsonpaths = options.jsonpaths || [];\n this.jsonPaths = jsonpaths.map((jsonpath) => new JSONPath(jsonpath));\n this._extendParser();\n }\n\n /**\n * write REDEFINITION\n * - super.write() chunk to parser\n * - get the contents (so far) of \"topmost-level\" array as batch of rows\n * - clear top-level array\n * - return the batch of rows\\\n */\n write(chunk) {\n super.write(chunk);\n let array: any[] = [];\n if (this.streamingArray) {\n array = [...this.streamingArray];\n this.streamingArray.length = 0;\n }\n return array;\n }\n\n /**\n * Returns a partially formed result object\n * Useful for returning the \"wrapper\" object when array is not top level\n * e.g. GeoJSON\n */\n getPartialResult() {\n return this.topLevelObject;\n }\n\n getStreamingJsonPath() {\n return this.streamingJsonPath;\n }\n\n getStreamingJsonPathAsString() {\n return this.streamingJsonPath && this.streamingJsonPath.toString();\n }\n\n getJsonPath() {\n return this.jsonpath;\n }\n\n // PRIVATE METHODS\n\n /**\n * Checks is this.getJsonPath matches the jsonpaths provided in options\n */\n _matchJSONPath() {\n const currentPath = this.getJsonPath();\n // console.debug(`Testing JSONPath`, currentPath);\n\n // Backwards compatibility, match any array\n // TODO implement using wildcard once that is supported\n if (this.jsonPaths.length === 0) {\n return true;\n }\n\n for (const jsonPath of this.jsonPaths) {\n if (jsonPath.equals(currentPath)) {\n return true;\n }\n }\n\n return false;\n }\n\n _extendParser() {\n // Redefine onopenarray to locate and inject value for top-level array\n this.parser.onopenarray = () => {\n if (!this.streamingArray) {\n if (this._matchJSONPath()) {\n // @ts-ignore\n this.streamingJsonPath = this.getJsonPath().clone();\n this.streamingArray = [];\n this._openArray(this.streamingArray as []);\n return;\n }\n }\n\n this._openArray();\n };\n\n // Redefine onopenarray to inject value for top-level object\n this.parser.onopenobject = (name) => {\n if (!this.topLevelObject) {\n this.topLevelObject = {};\n this._openObject(this.topLevelObject);\n } else {\n this._openObject({});\n }\n if (typeof name !== 'undefined') {\n this.parser.onkey(name);\n }\n };\n }\n}\n","// @ts-nocheck\n\nimport ClarinetParser from '../clarinet/clarinet';\nimport JSONPath from '../jsonpath/jsonpath';\n\n// JSONParser builds a JSON object using the events emitted by the Clarinet parser\n\nexport default class JSONParser {\n jsonpath: JSONPath;\n _parser?: ClarinetParser;\n\n constructor() {\n this.reset();\n this._initializeParser();\n }\n\n reset(): void {\n this.result = undefined;\n this.previousStates = [];\n this.currentState = Object.freeze({container: [], key: null});\n this.jsonpath = new JSONPath();\n }\n\n write(chunk): void {\n this.parser.write(chunk);\n }\n\n close(): void {\n this.parser.close();\n }\n\n // PRIVATE METHODS\n\n _pushOrSet(value): void {\n const {container, key} = this.currentState;\n if (key !== null) {\n container[key] = value;\n this.currentState.key = null;\n } else {\n container.push(value);\n }\n }\n\n _openArray(newContainer = []): void {\n this.jsonpath.push(null);\n this._pushOrSet(newContainer);\n this.previousStates.push(this.currentState);\n this.currentState = {container: newContainer, isArray: true, key: null};\n }\n\n _closeArray(): void {\n this.jsonpath.pop();\n this.currentState = this.previousStates.pop();\n }\n\n _openObject(newContainer = {}): void {\n this.jsonpath.push(null);\n this._pushOrSet(newContainer);\n this.previousStates.push(this.currentState);\n this.currentState = {container: newContainer, isArray: false, key: null};\n }\n\n _closeObject(): void {\n this.jsonpath.pop();\n this.currentState = this.previousStates.pop();\n }\n\n _initializeParser(): void {\n this._parser = new ClarinetParser({\n onready: () => {\n this.jsonpath = new JSONPath();\n this.previousStates.length = 0;\n this.currentState.container.length = 0;\n },\n\n onopenobject: (name) => {\n this._openObject({});\n if (typeof name !== 'undefined') {\n this.parser.onkey(name);\n }\n },\n\n onkey: (name) => {\n this.jsonpath.set(name);\n this.currentState.key = name;\n },\n\n oncloseobject: () => {\n this._closeObject();\n },\n\n onopenarray: () => {\n this._openArray();\n },\n\n onclosearray: () => {\n this._closeArray();\n },\n\n onvalue: (value) => {\n this._pushOrSet(value);\n },\n\n onerror: (error) => {\n throw error;\n },\n\n onend: () => {\n this.result = this.currentState.container.pop();\n }\n });\n }\n\n protected get parser(): ClarinetParser {\n return this._parser as ClarinetParser;\n }\n}\n","import type {Loader, LoaderWithParser} from '@loaders.gl/loader-utils';\nimport type {JSONLoaderOptions} from './json-loader';\nimport {geojsonToBinary} from '@loaders.gl/gis';\nimport parseJSONSync from './lib/parse-json';\nimport parseJSONInBatches from './lib/parse-json-in-batches';\n\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n\nexport type GeoJSONLoaderOptions = JSONLoaderOptions & {\n geojson?: {\n shape?: 'object-row-table';\n };\n gis?: {\n format: 'geojson';\n };\n};\n\nconst DEFAULT_GEOJSON_LOADER_OPTIONS = {\n geojson: {\n shape: 'object-row-table'\n },\n json: {\n jsonpaths: ['$', '$.features']\n },\n gis: {\n format: 'geojson'\n }\n};\n\n/**\n * GeoJSON loader\n */\nexport const GeoJSONWorkerLoader: Loader = {\n name: 'GeoJSON',\n id: 'geojson',\n module: 'geojson',\n version: VERSION,\n worker: true,\n extensions: ['geojson'],\n mimeTypes: ['application/geo+json'],\n category: 'geometry',\n text: true,\n options: DEFAULT_GEOJSON_LOADER_OPTIONS\n};\n\nexport const GeoJSONLoader: LoaderWithParser = {\n ...GeoJSONWorkerLoader,\n parse,\n parseTextSync,\n parseInBatches\n};\n\nasync function parse(arrayBuffer, options) {\n return parseTextSync(new TextDecoder().decode(arrayBuffer), options);\n}\n\nfunction parseTextSync(text, options) {\n // Apps can call the parse method directly, we so apply default options here\n options = {...DEFAULT_GEOJSON_LOADER_OPTIONS, ...options};\n options.json = {...DEFAULT_GEOJSON_LOADER_OPTIONS.geojson, ...options.geojson};\n options.gis = options.gis || {};\n const json = parseJSONSync(text, options);\n switch (options.gis.format) {\n case 'binary':\n return geojsonToBinary(json);\n default:\n return json;\n }\n}\n\nfunction parseInBatches(asyncIterator, options): AsyncIterable<any> {\n // Apps can call the parse method directly, we so apply default options here\n options = {...DEFAULT_GEOJSON_LOADER_OPTIONS, ...options};\n options.json = {...DEFAULT_GEOJSON_LOADER_OPTIONS.geojson, ...options.geojson};\n\n const geojsonIterator = parseJSONInBatches(asyncIterator, options);\n\n switch (options.gis.format) {\n case 'binary':\n return makeBinaryGeometryIterator(geojsonIterator);\n default:\n return geojsonIterator;\n }\n}\n\nasync function* makeBinaryGeometryIterator(geojsonIterator) {\n for await (const batch of geojsonIterator) {\n batch.data = geojsonToBinary(batch.data);\n yield batch;\n }\n}\n","// Types from `@loaders.gl/schema`\n\n// Functions\nexport {geojsonToBinary} from './lib/geojson-to-binary';\nexport {binaryToGeojson, binaryToGeoJson, binaryToGeometry} from './lib/binary-to-geojson';\nexport {transformBinaryCoords, transformGeoJsonCoords} from './lib/transform';\n","import {Feature, GeoJsonProperties} from '@loaders.gl/schema';\nimport type {BinaryFeatures} from '@loaders.gl/schema';\n\nexport type GeojsonToBinaryOptions = {\n coordLength?: number;\n numericPropKeys?: string[];\n PositionDataType?: Function;\n};\n\n/** Convert GeoJSON features to flat binary arrays */\nexport function geojsonToBinary(\n features: Feature[],\n options: GeojsonToBinaryOptions = {}\n): BinaryFeatures {\n const firstPassData = firstPass(features);\n return secondPass(features, firstPassData, {\n coordLength: options.coordLength || firstPassData.coordLength,\n numericPropKeys: options.numericPropKeys || firstPassData.numericPropKeys,\n PositionDataType: options.PositionDataType || Float32Array\n });\n}\n\nexport const TEST_EXPORTS = {\n firstPass,\n secondPass\n};\n\ntype FirstPassData = {\n coordLength: number;\n numericPropKeys: string[];\n\n pointPositionsCount: number;\n pointFeaturesCount: number;\n linePositionsCount: number;\n linePathsCount: number;\n lineFeaturesCount: number;\n polygonPositionsCount: number;\n polygonObjectsCount: number;\n polygonRingsCount: number;\n polygonFeaturesCount: number;\n};\n\n/**\n * Initial scan over GeoJSON features\n * Counts number of coordinates of each geometry type and\n * keeps track of the max coordinate dimensions\n */\n// eslint-disable-next-line complexity, max-statements\nfunction firstPass(features: Feature[]): FirstPassData {\n // Counts the number of _positions_, so [x, y, z] counts as one\n let pointPositionsCount = 0;\n let pointFeaturesCount = 0;\n let linePositionsCount = 0;\n let linePathsCount = 0;\n let lineFeaturesCount = 0;\n let polygonPositionsCount = 0;\n let polygonObjectsCount = 0;\n let polygonRingsCount = 0;\n let polygonFeaturesCount = 0;\n const coordLengths = new Set<number>();\n const numericPropKeys = {};\n\n for (const feature of features) {\n const geometry = feature.geometry;\n switch (geometry.type) {\n case 'Point':\n pointFeaturesCount++;\n pointPositionsCount++;\n coordLengths.add(geometry.coordinates.length);\n break;\n case 'MultiPoint':\n pointFeaturesCount++;\n pointPositionsCount += geometry.coordinates.length;\n for (const point of geometry.coordinates) {\n coordLengths.add(point.length);\n }\n break;\n case 'LineString':\n lineFeaturesCount++;\n linePositionsCount += geometry.coordinates.length;\n linePathsCount++;\n\n for (const coord of geometry.coordinates) {\n coordLengths.add(coord.length);\n }\n break;\n case 'MultiLineString':\n lineFeaturesCount++;\n for (const line of geometry.coordinates) {\n linePositionsCount += line.length;\n linePathsCount++;\n\n // eslint-disable-next-line max-depth\n for (const coord of line) {\n coordLengths.add(coord.length);\n }\n }\n break;\n case 'Polygon':\n polygonFeaturesCount++;\n polygonObjectsCount++;\n polygonRingsCount += geometry.coordinates.length;\n polygonPositionsCount += flatten(geometry.coordinates).length;\n\n for (const coord of flatten(geometry.coordinates)) {\n coordLengths.add(coord.length);\n }\n break;\n case 'MultiPolygon':\n polygonFeaturesCount++;\n for (const polygon of geometry.coordinates) {\n polygonObjectsCount++;\n polygonRingsCount += polygon.length;\n polygonPositionsCount += flatten(polygon).length;\n\n // eslint-disable-next-line max-depth\n for (const coord of flatten(polygon)) {\n coordLengths.add(coord.length);\n }\n }\n break;\n default:\n throw new Error(`Unsupported geometry type: ${geometry.type}`);\n }\n\n if (feature.properties) {\n for (const key in feature.properties) {\n const val = feature.properties[key];\n\n // If property has not been seen before, or if property has been numeric\n // in all previous features, check if numeric in this feature\n // If not numeric, false is stored to prevent rechecking in the future\n numericPropKeys[key] =\n numericPropKeys[key] || numericPropKeys[key] === undefined\n ? isNumeric(val)\n : numericPropKeys[key];\n }\n }\n }\n\n return {\n coordLength: coordLengths.size > 0 ? Math.max(...coordLengths) : 2,\n\n pointPositionsCount,\n pointFeaturesCount,\n linePositionsCount,\n linePathsCount,\n lineFeaturesCount,\n polygonPositionsCount,\n polygonObjectsCount,\n polygonRingsCount,\n polygonFeaturesCount,\n\n // Array of keys whose values are always numeric\n numericPropKeys: Object.keys(numericPropKeys).filter((k) => numericPropKeys[k])\n };\n}\n\n/**\n * Second scan over GeoJSON features\n * Fills coordinates into pre-allocated typed arrays\n */\n// eslint-disable-next-line complexity\nfunction secondPass(\n features,\n firstPassData: FirstPassData,\n options: Required<GeojsonToBinaryOptions>\n) {\n const {\n pointPositionsCount,\n pointFeaturesCount,\n linePositionsCount,\n linePathsCount,\n lineFeaturesCount,\n polygonPositionsCount,\n polygonObjectsCount,\n polygonRingsCount,\n polygonFeaturesCount\n } = firstPassData;\n const {coordLength, numericPropKeys, PositionDataType = Float32Array} = options;\n const GlobalFeatureIdsDataType = features.length > 65535 ? Uint32Array : Uint16Array;\n const points = {\n // @ts-ignore Typescript doesn't like dynamic constructors\n positions: new PositionDataType(pointPositionsCount * coordLength),\n globalFeatureIds: new GlobalFeatureIdsDataType(pointPositionsCount),\n featureIds:\n pointFeaturesCount > 65535\n ? new Uint32Array(pointPositionsCount)\n : new Uint16Array(pointPositionsCount),\n numericProps: {},\n properties: Array<any>(),\n fields: Array<any>()\n };\n const lines = {\n // @ts-ignore Typescript doesn't like dynamic constructors\n positions: new PositionDataType(linePositionsCount * coordLength),\n pathIndices:\n linePositionsCount > 65535\n ? new Uint32Array(linePathsCount + 1)\n : new Uint16Array(linePathsCount + 1),\n globalFeatureIds: new GlobalFeatureIdsDataType(linePositionsCount),\n featureIds:\n lineFeaturesCount > 65535\n ? new Uint32Array(linePositionsCount)\n : new Uint16Array(linePositionsCount),\n numericProps: {},\n properties: Array<any>(),\n fields: Array<any>()\n };\n const polygons = {\n // @ts-ignore Typescript doesn't like dynamic constructors\n positions: new PositionDataType(polygonPositionsCount * coordLength),\n polygonIndices:\n polygonPositionsCount > 65535\n ? new Uint32Array(polygonObjectsCount + 1)\n : new Uint16Array(polygonObjectsCount + 1),\n primitivePolygonIndices:\n polygonPositionsCount > 65535\n ? new Uint32Array(polygonRingsCount + 1)\n : new Uint16Array(polygonRingsCount + 1),\n globalFeatureIds: new GlobalFeatureIdsDataType(polygonPositionsCount),\n featureIds:\n polygonFeaturesCount > 65535\n ? new Uint32Array(polygonPositionsCount)\n : new Uint16Array(polygonPositionsCount),\n numericProps: {},\n properties: Array<any>(),\n fields: Array<any>()\n };\n\n // Instantiate numeric properties arrays; one value per vertex\n for (const object of [points, lines, polygons]) {\n for (const propName of numericPropKeys || []) {\n // If property has been numeric in all previous features in which the property existed, check\n // if numeric in this feature\n object.numericProps[propName] = new Float32Array(object.positions.length / coordLength);\n }\n }\n\n // Set last element of path/polygon indices as positions length\n lines.pathIndices[linePathsCount] = linePositionsCount;\n polygons.polygonIndices[polygonObjectsCount] = polygonPositionsCount;\n polygons.primitivePolygonIndices[polygonRingsCount] = polygonPositionsCount;\n\n const indexMap = {\n pointPosition: 0,\n pointFeature: 0,\n linePosition: 0,\n linePath: 0,\n lineFeature: 0,\n polygonPosition: 0,\n polygonObject: 0,\n polygonRing: 0,\n polygonFeature: 0,\n feature: 0\n };\n\n for (const feature of features) {\n const geometry = feature.geometry;\n const properties: GeoJsonProperties = feature.properties || {};\n\n switch (geometry.type) {\n case 'Point':\n handlePoint(geometry.coordinates, points, indexMap, coordLength, properties);\n points.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.pointFeature++;\n break;\n case 'MultiPoint':\n handleMultiPoint(geometry.coordinates, points, indexMap, coordLength, properties);\n points.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.pointFeature++;\n break;\n case 'LineString':\n handleLineString(geometry.coordinates, lines, indexMap, coordLength, properties);\n lines.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.lineFeature++;\n break;\n case 'MultiLineString':\n handleMultiLineString(geometry.coordinates, lines, indexMap, coordLength, properties);\n lines.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.lineFeature++;\n break;\n case 'Polygon':\n handlePolygon(geometry.coordinates, polygons, indexMap, coordLength, properties);\n polygons.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.polygonFeature++;\n break;\n case 'MultiPolygon':\n handleMultiPolygon(geometry.coordinates, polygons, indexMap, coordLength, properties);\n polygons.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.polygonFeature++;\n break;\n default:\n throw new Error('Invalid geometry type');\n }\n\n indexMap.feature++;\n }\n\n // Wrap each array in an accessor object with value and size keys\n return makeAccessorObjects(points, lines, polygons, coordLength);\n}\n\n/** Fills Point coordinates into points object of arrays */\nfunction handlePoint(coords, points, indexMap, coordLength, properties) {\n points.positions.set(coords, indexMap.pointPosition * coordLength);\n points.globalFeatureIds[indexMap.pointPosition] = indexMap.feature;\n points.featureIds[indexMap.pointPosition] = indexMap.pointFeature;\n\n fillNumericProperties(points, properties, indexMap.pointPosition, 1);\n indexMap.pointPosition++;\n}\n\n/** Fills MultiPoint coordinates into points object of arrays */\nfunction handleMultiPoint(coords, points, indexMap, coordLength, properties) {\n for (const point of coords) {\n handlePoint(point, points, indexMap, coordLength, properties);\n }\n}\n\n/** Fills LineString coordinates into lines object of arrays */\nfunction handleLineString(coords, lines, indexMap, coordLength, properties) {\n lines.pathIndices[indexMap.linePath] = indexMap.linePosition;\n indexMap.linePath++;\n\n fillCoords(lines.positions, coords, indexMap.linePosition, coordLength);\n\n const nPositions = coords.length;\n fillNumericProperties(lines, properties, indexMap.linePosition, nPositions);\n\n lines.globalFeatureIds.set(\n new Uint32Array(nPositions).fill(indexMap.feature),\n indexMap.linePosition\n );\n lines.featureIds.set(\n new Uint32Array(nPositions).fill(indexMap.lineFeature),\n indexMap.linePosition\n );\n indexMap.linePosition += nPositions;\n}\n\n/** Fills MultiLineString coordinates into lines object of arrays */\nfunction handleMultiLineString(coords, lines, indexMap, coordLength, properties) {\n for (const line of coords) {\n handleLineString(line, lines, indexMap, coordLength, properties);\n }\n}\n\n/** Fills Polygon coordinates into polygons object of arrays */\nfunction handlePolygon(coords, polygons, indexMap, coordLength, properties) {\n polygons.polygonIndices[indexMap.polygonObject] = indexMap.polygonPosition;\n indexMap.polygonObject++;\n\n for (const ring of coords) {\n polygons.primitivePolygonIndices[indexMap.polygonRing] = indexMap.polygonPosition;\n indexMap.polygonRing++;\n\n fillCoords(polygons.positions, ring, indexMap.polygonPosition, coordLength);\n\n const nPositions = ring.length;\n fillNumericProperties(polygons, properties, indexMap.polygonPosition, nPositions);\n\n polygons.globalFeatureIds.set(\n new Uint32Array(nPositions).fill(indexMap.feature),\n indexMap.polygonPosition\n );\n polygons.featureIds.set(\n new Uint32Array(nPositions).fill(indexMap.polygonFeature),\n indexMap.polygonPosition\n );\n indexMap.polygonPosition += nPositions;\n }\n}\n\n/** Fills MultiPolygon coordinates into polygons object of arrays */\nfunction handleMultiPolygon(coords, polygons, indexMap, coordLength, properties) {\n for (const polygon of coords) {\n handlePolygon(polygon, polygons, indexMap, coordLength, properties);\n }\n}\n\n/** Wrap each array in an accessor object with value and size keys */\nfunction makeAccessorObjects(points, lines, polygons, coordLength): BinaryFeatures {\n const returnObj = {\n points: {\n ...points,\n positions: {value: points.positions, size: coordLength},\n globalFeatureIds: {value: points.globalFeatureIds, size: 1},\n featureIds: {value: points.featureIds, size: 1},\n type: 'Point'\n },\n lines: {\n ...lines,\n pathIndices: {value: lines.pathIndices, size: 1},\n positions: {value: lines.positions, size: coordLength},\n globalFeatureIds: {value: lines.globalFeatureIds, size: 1},\n featureIds: {value: lines.featureIds, size: 1},\n type: 'LineString'\n },\n polygons: {\n ...polygons,\n polygonIndices: {value: polygons.polygonIndices, size: 1},\n primitivePolygonIndices: {value: polygons.primitivePolygonIndices, size: 1},\n positions: {value: polygons.positions, size: coordLength},\n globalFeatureIds: {value: polygons.globalFeatureIds, size: 1},\n featureIds: {value: polygons.featureIds, size: 1},\n type: 'Polygon'\n }\n };\n\n for (const geomType in returnObj) {\n for (const numericProp in returnObj[geomType].numericProps) {\n returnObj[geomType].numericProps[numericProp] = {\n value: returnObj[geomType].numericProps[numericProp],\n size: 1\n };\n }\n }\n\n return returnObj as unknown as BinaryFeatures;\n}\n\n/** Add numeric properties to object */\nfunction fillNumericProperties(object, properties, index, length) {\n for (const numericPropName in object.numericProps) {\n if (numericPropName in properties) {\n object.numericProps[numericPropName].set(\n new Array(length).fill(properties[numericPropName]),\n index\n );\n }\n }\n}\n\n/** Keep string properties in object */\nfunction keepStringProperties(properties, numericKeys: string[]): GeoJsonProperties {\n const props = {};\n for (const key in properties) {\n if (!numericKeys.includes(key)) {\n props[key] = properties[key];\n }\n }\n return props;\n}\n\n/** @param coords is expected to be a list of arrays, each with length 2-3 */\nfunction fillCoords(array, coords, startVertex, coordLength): void {\n let index = startVertex * coordLength;\n for (const coord of coords) {\n array.set(coord, index);\n index += coordLength;\n }\n}\n\n// TODO - how does this work? Different `coordinates` have different nesting\nfunction flatten(arrays): number[][] {\n return [].concat(...arrays);\n}\n\nfunction isNumeric(x: any): boolean {\n return Number.isFinite(x);\n}\n","import type {\n BinaryGeometry,\n BinaryFeatures,\n BinaryGeometryType,\n BinaryPointFeatures,\n BinaryLineFeatures,\n BinaryPolygonFeatures,\n BinaryAttribute\n} from '@loaders.gl/schema';\nimport type {Feature, Geometry, Position, GeoJsonProperties} from '@loaders.gl/schema';\nimport type {\n Point,\n MultiPoint,\n LineString,\n MultiLineString,\n Polygon,\n MultiPolygon\n} from '@loaders.gl/schema';\n\n// Note:L We do not handle GeometryCollection, define a limited Geometry type that always has coordinates.\n// type FeatureGeometry = Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon;\n\ntype BinaryToGeoJsonOptions = {\n type?: BinaryGeometryType;\n globalFeatureId?: number;\n};\n\n/**\n * Convert binary geometry representation to GeoJSON\n * @param data geometry data in binary representation\n * @param options\n * @param options.type Input data type: Point, LineString, or Polygon\n * @param options.featureId Global feature id. If specified, only a single feature is extracted\n * @return GeoJSON objects\n */\nexport function binaryToGeojson(\n data: BinaryFeatures,\n options?: BinaryToGeoJsonOptions\n): Feature[] | Feature {\n const globalFeatureId = options?.globalFeatureId;\n if (globalFeatureId !== undefined) {\n return getSingleFeature(data, globalFeatureId);\n }\n return parseFeatures(data, options?.type);\n}\n\n/** @deprecated use `binaryToGeojson` or `binaryToGeometry` instead */\nexport function binaryToGeoJson(\n data: BinaryGeometry | BinaryFeatures,\n type?: BinaryGeometryType,\n format: 'feature' | 'geometry' = 'feature'\n): Geometry | Feature[] {\n switch (format) {\n case 'feature':\n return parseFeatures(data as BinaryFeatures, type);\n case 'geometry':\n return binaryToGeometry(data as BinaryGeometry);\n default:\n throw new Error(format);\n }\n}\n\n/**\n * Return a single feature from a binary geometry representation as GeoJSON\n * @param data geometry data in binary representation\n * @return GeoJSON feature\n */\nfunction getSingleFeature(data: BinaryFeatures, globalFeatureId: number): Feature {\n const dataArray = normalizeInput(data);\n for (const data of dataArray) {\n let lastIndex = 0;\n let lastValue = data.featureIds.value[0];\n\n // Scan through data until we find matching feature\n for (let i = 0; i < data.featureIds.value.length; i++) {\n const currValue = data.featureIds.value[i];\n if (currValue === lastValue) {\n // eslint-disable-next-line no-continue\n continue;\n }\n if (globalFeatureId === data.globalFeatureIds.value[lastIndex]) {\n return parseFeature(data, lastIndex, i);\n }\n lastIndex = i;\n lastValue = currValue;\n }\n\n if (globalFeatureId === data.globalFeatureIds.value[lastIndex]) {\n return parseFeature(data, lastIndex, data.featureIds.value.length);\n }\n }\n\n throw new Error(`featureId:${globalFeatureId} not found`);\n}\n\nfunction parseFeatures(data: BinaryFeatures, type?: BinaryGeometryType): Feature[] {\n const dataArray = normalizeInput(data, type);\n return parseFeatureCollection(dataArray);\n}\n\n/** Parse input binary data and return a valid GeoJSON geometry object */\nexport function binaryToGeometry(\n data: BinaryGeometry,\n startIndex?: number,\n endIndex?: number\n): Geometry {\n switch (data.type) {\n case 'Point':\n return pointToGeoJson(data, startIndex, endIndex);\n case 'LineString':\n return lineStringToGeoJson(data, startIndex, endIndex);\n case 'Polygon':\n return polygonToGeoJson(data, startIndex, endIndex);\n default:\n const unexpectedInput: never = data;\n throw new Error(`Unsupported geometry type: ${(unexpectedInput as any)?.type}`);\n }\n}\n\ntype BinaryFeature = BinaryPointFeatures | BinaryLineFeatures | BinaryPolygonFeatures;\ntype BinaryFeaturesArray = BinaryFeature[];\n\n// Normalize features\n// Return an array of data objects, each of which have a type key\nfunction normalizeInput(data: BinaryFeatures, type?: BinaryGeometryType): BinaryFeaturesArray {\n const isHeterogeneousType = Boolean(data.points || data.lines || data.polygons);\n\n if (!isHeterogeneousType) {\n // @ts-expect-error This is a legacy check which allowed `data` to be an instance of the values\n // here. Aka the new data.points, data.lines, or data.polygons.\n data.type = type || parseType(data);\n return [data] as BinaryFeaturesArray;\n }\n\n const features: BinaryFeaturesArray = [];\n if (data.points) {\n data.points.type = 'Point';\n features.push(data.points);\n }\n if (data.lines) {\n data.lines.type = 'LineString';\n features.push(data.lines);\n }\n if (data.polygons) {\n data.polygons.type = 'Polygon';\n features.push(data.polygons);\n }\n\n return features;\n}\n\n/** Parse input binary data and return an array of GeoJSON Features */\nfunction parseFeatureCollection(dataArray): Feature[] {\n const features: Feature[] = [];\n for (const data of dataArray) {\n if (data.featureIds.value.length === 0) {\n // eslint-disable-next-line no-continue\n continue;\n }\n let lastIndex = 0;\n let lastValue = data.featureIds.value[0];\n\n // Need to deduce start, end indices of each feature\n for (let i = 0; i < data.featureIds.value.length; i++) {\n const currValue = data.featureIds.value[i];\n if (currValue === lastValue) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n features.push(parseFeature(data, lastIndex, i));\n lastIndex = i;\n lastValue = currValue;\n }\n\n // Last feature\n features.push(parseFeature(data, lastIndex, data.featureIds.value.length));\n }\n return features;\n}\n\n/** Parse input binary data and return a single GeoJSON Feature */\nfunction parseFeature(data, startIndex?: number, endIndex?: number): Feature {\n const geometry = binaryToGeometry(data, startIndex, endIndex);\n const properties = parseProperties(data, startIndex, endIndex);\n const fields = parseFields(data, startIndex, endIndex);\n return {type: 'Feature', geometry, properties, ...fields};\n}\n\n/** Parse input binary data and return an object of fields */\nfunction parseFields(data, startIndex: number = 0, endIndex?: number): GeoJsonProperties {\n return data.fields && data.fields[data.featureIds.value[startIndex]];\n}\n\n/** Parse input binary data and return an object of properties */\nfunction parseProperties(data, startIndex: number = 0, endIndex?: number): GeoJsonProperties {\n const properties = Object.assign({}, data.properties[data.featureIds.value[startIndex]]);\n for (const key in data.numericProps) {\n properties[key] = data.numericProps[key].value[startIndex];\n }\n return properties;\n}\n\n/** Parse binary data of type Polygon */\nfunction polygonToGeoJson(\n data,\n startIndex: number = -Infinity,\n endIndex: number = Infinity\n): Polygon | MultiPolygon {\n const {positions} = data;\n const polygonIndices = data.polygonIndices.value.filter((x) => x >= startIndex && x <= endIndex);\n const primitivePolygonIndices = data.primitivePolygonIndices.value.filter(\n (x) => x >= startIndex && x <= endIndex\n );\n const multi = polygonIndices.length > 2;\n\n // Polygon\n if (!multi) {\n const coordinates: Position[][] = [];\n for (let i = 0; i < primitivePolygonIndices.length - 1; i++) {\n const startRingIndex = primitivePolygonIndices[i];\n const endRingIndex = primitivePolygonIndices[i + 1];\n const ringCoordinates = ringToGeoJson(positions, startRingIndex, endRingIndex);\n coordinates.push(ringCoordinates);\n }\n\n return {type: 'Polygon', coordinates};\n }\n\n // MultiPolygon\n const coordinates: Position[][][] = [];\n for (let i = 0; i < polygonIndices.length - 1; i++) {\n const startPolygonIndex = polygonIndices[i];\n const endPolygonIndex = polygonIndices[i + 1];\n const polygonCoordinates = polygonToGeoJson(\n data,\n startPolygonIndex,\n endPolygonIndex\n ).coordinates;\n coordinates.push(polygonCoordinates as Position[][]);\n }\n\n return {type: 'MultiPolygon', coordinates};\n}\n\n/** Parse binary data of type LineString */\nfunction lineStringToGeoJson(\n data,\n startIndex: number = -Infinity,\n endIndex: number = Infinity\n): LineString | MultiLineString {\n const {positions} = data;\n const pathIndices = data.pathIndices.value.filter((x) => x >= startIndex && x <= endIndex);\n const multi = pathIndices.length > 2;\n\n if (!multi) {\n const coordinates = ringToGeoJson(positions, pathIndices[0], pathIndices[1]);\n return {type: 'LineString', coordinates};\n }\n\n const coordinates: Position[][] = [];\n for (let i = 0; i < pathIndices.length - 1; i++) {\n const ringCoordinates = ringToGeoJson(positions, pathIndices[i], pathIndices[i + 1]);\n coordinates.push(ringCoordinates);\n }\n\n return {type: 'MultiLineString', coordinates};\n}\n\n/** Parse binary data of type Point */\nfunction pointToGeoJson(data, startIndex, endIndex): Point | MultiPoint {\n const {positions} = data;\n const coordinates = ringToGeoJson(positions, startIndex, endIndex);\n const multi = coordinates.length > 1;\n\n if (multi) {\n return {type: 'MultiPoint', coordinates};\n }\n\n return {type: 'Point', coordinates: coordinates[0]};\n}\n\n/**\n * Parse a linear ring of positions to a GeoJSON linear ring\n *\n * @param positions Positions TypedArray\n * @param startIndex Start index to include in ring\n * @param endIndex End index to include in ring\n * @returns GeoJSON ring\n */\nfunction ringToGeoJson(\n positions: BinaryAttribute,\n startIndex?: number,\n endIndex?: number\n): Position[] {\n startIndex = startIndex || 0;\n endIndex = endIndex || positions.value.length / positions.size;\n\n const ringCoordinates: Position[] = [];\n for (let j = startIndex; j < endIndex; j++) {\n const coord = Array<number>();\n for (let k = j * positions.size; k < (j + 1) * positions.size; k++) {\n coord.push(Number(positions.value[k]));\n }\n ringCoordinates.push(coord);\n }\n return ringCoordinates;\n}\n\n// Deduce geometry type of data object\nfunction parseType(data) {\n if (data.pathIndices) {\n return 'LineString';\n }\n\n if (data.polygonIndices) {\n return 'Polygon';\n }\n\n return 'Point';\n}\n","import type {BinaryFeatures, BinaryGeometry} from '@loaders.gl/schema';\n\ntype TransformCoordinate = (coord: number[]) => number[];\n\n/**\n * Apply transformation to every coordinate of binary features\n * @param binaryFeatures binary features\n * @param transformCoordinate Function to call on each coordinate\n * @return Transformed binary features\n */\nexport function transformBinaryCoords(\n binaryFeatures: BinaryFeatures,\n transformCoordinate: TransformCoordinate\n): BinaryFeatures {\n if (binaryFeatures.points) {\n transformBinaryGeometryPositions(binaryFeatures.points, transformCoordinate);\n }\n if (binaryFeatures.lines) {\n transformBinaryGeometryPositions(binaryFeatures.lines, transformCoordinate);\n }\n if (binaryFeatures.polygons) {\n transformBinaryGeometryPositions(binaryFeatures.polygons, transformCoordinate);\n }\n return binaryFeatures;\n}\n\n/** Transform one binary geometry */\nfunction transformBinaryGeometryPositions(binaryGeometry: BinaryGeometry, fn: TransformCoordinate) {\n const {positions} = binaryGeometry;\n for (let i = 0; i < positions.value.length; i += positions.size) {\n // @ts-ignore inclusion of bigint causes problems\n const coord: Array<number> = Array.from(positions.value.subarray(i, i + positions.size));\n const transformedCoord = fn(coord);\n // @ts-ignore typescript typing for .set seems to require bigint?\n positions.value.set(transformedCoord, i);\n }\n}\n\n/**\n * Apply transformation to every coordinate of GeoJSON features\n *\n * @param features Array of GeoJSON features\n * @param fn Function to call on each coordinate\n * @return Transformed GeoJSON features\n */\nexport function transformGeoJsonCoords(\n features: object[],\n fn: (coord: number[]) => number[]\n): object[] {\n for (const feature of features) {\n // @ts-ignore\n feature.geometry.coordinates = coordMap(feature.geometry.coordinates, fn);\n }\n return features;\n}\n\nfunction coordMap(array, fn) {\n if (isCoord(array)) {\n return fn(array);\n }\n\n return array.map((item) => {\n return coordMap(item, fn);\n });\n}\n\nfunction isCoord(array) {\n return Number.isFinite(array[0]) && Number.isFinite(array[1]);\n}\n","import getHiResTimestamp from '../utils/hi-res-timestamp';\nexport default class Stat {\n constructor(name, type) {\n this.name = name;\n this.type = type;\n this.sampleSize = 1;\n this.reset();\n }\n\n setSampleSize(samples) {\n this.sampleSize = samples;\n return this;\n }\n\n incrementCount() {\n this.addCount(1);\n return this;\n }\n\n decrementCount() {\n this.subtractCount(1);\n return this;\n }\n\n addCount(value) {\n this._count += value;\n this._samples++;\n\n this._checkSampling();\n\n return this;\n }\n\n subtractCount(value) {\n this._count -= value;\n this._samples++;\n\n this._checkSampling();\n\n return this;\n }\n\n addTime(time) {\n this._time += time;\n this.lastTiming = time;\n this._samples++;\n\n this._checkSampling();\n\n return this;\n }\n\n timeStart() {\n this._startTime = getHiResTimestamp();\n this._timerPending = true;\n return this;\n }\n\n timeEnd() {\n if (!this._timerPending) {\n return this;\n }\n\n this.addTime(getHiResTimestamp() - this._startTime);\n this._timerPending = false;\n\n this._checkSampling();\n\n return this;\n }\n\n getSampleAverageCount() {\n return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;\n }\n\n getSampleAverageTime() {\n return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;\n }\n\n getSampleHz() {\n return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;\n }\n\n getAverageCount() {\n return this.samples > 0 ? this.count / this.samples : 0;\n }\n\n getAverageTime() {\n return this.samples > 0 ? this.time / this.samples : 0;\n }\n\n getHz() {\n return this.time > 0 ? this.samples / (this.time / 1000) : 0;\n }\n\n reset() {\n this.time = 0;\n this.count = 0;\n this.samples = 0;\n this.lastTiming = 0;\n this.lastSampleTime = 0;\n this.lastSampleCount = 0;\n this._count = 0;\n this._time = 0;\n this._samples = 0;\n this._startTime = 0;\n this._timerPending = false;\n return this;\n }\n\n _checkSampling() {\n if (this._samples === this.sampleSize) {\n this.lastSampleTime = this._time;\n this.lastSampleCount = this._count;\n this.count += this._count;\n this.time += this._time;\n this.samples += this._samples;\n this._time = 0;\n this._count = 0;\n this._samples = 0;\n }\n }\n\n}\n//# sourceMappingURL=stat.js.map","import Stat from './stat';\nexport default class Stats {\n constructor({\n id,\n stats\n }) {\n this.id = id;\n this.stats = {};\n\n this._initializeStats(stats);\n\n Object.seal(this);\n }\n\n get(name, type = 'count') {\n return this._getOrCreate({\n name,\n type\n });\n }\n\n get size() {\n return Object.keys(this.stats).length;\n }\n\n reset() {\n for (const key in this.stats) {\n this.stats[key].reset();\n }\n\n return this;\n }\n\n forEach(fn) {\n for (const key in this.stats) {\n fn(this.stats[key]);\n }\n }\n\n getTable() {\n const table = {};\n this.forEach(stat => {\n table[stat.name] = {\n time: stat.time || 0,\n count: stat.count || 0,\n average: stat.getAverageTime() || 0,\n hz: stat.getHz() || 0\n };\n });\n return table;\n }\n\n _initializeStats(stats = []) {\n stats.forEach(stat => this._getOrCreate(stat));\n }\n\n _getOrCreate(stat) {\n if (!stat || !stat.name) {\n return null;\n }\n\n const {\n name,\n type\n } = stat;\n\n if (!this.stats[name]) {\n if (stat instanceof Stat) {\n this.stats[name] = stat;\n } else {\n this.stats[name] = new Stat(name, type);\n }\n }\n\n return this.stats[name];\n }\n\n}\n//# sourceMappingURL=stats.js.map"],"sourceRoot":""}
1
+ {"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///../worker-utils/src/lib/env-utils/assert.ts","webpack:////home/user/apps/loaders.gl/node_modules/@probe.gl/stats/dist/esm/utils/hi-res-timestamp.js","webpack:///../worker-utils/src/lib/env-utils/version.ts","webpack:///(webpack)/buildin/global.js","webpack:///../schema/src/lib/schema/index.ts","webpack:////home/user/apps/loaders.gl/node_modules/process/browser.js","webpack:///../worker-utils/src/lib/env-utils/globals.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-thread.ts","webpack:///../worker-utils/src/lib/worker-utils/get-transfer-list.ts","webpack:///./src/lib/jsonpath/jsonpath.ts","webpack:///./src/lib/parse-json.ts","webpack:///./src/lib/parse-json-in-batches.ts","webpack:///../schema/src/lib/table/row-table-batch-aggregator.ts","webpack:///../schema/src/lib/utils/row-utils.ts","webpack:///../schema/src/lib/table/columnar-table-batch-aggregator.ts","webpack:///../loader-utils/src/lib/env-utils/assert.ts","webpack:///../worker-utils/src/index.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-job.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-farm.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-pool.ts","webpack:///../worker-utils/src/lib/worker-farm/worker-body.ts","webpack:///../worker-utils/src/lib/worker-api/get-worker-url.ts","webpack:///../worker-utils/src/lib/async-queue/async-queue.ts","webpack:///../loader-utils/src/lib/binary-utils/get-first-characters.ts","webpack:///../loader-utils/src/lib/binary-utils/array-buffer-utils.ts","webpack:///../loader-utils/src/lib/binary-utils/buffer-utils.ts","webpack:///../loader-utils/src/lib/binary-utils/memory-copy-utils.ts","webpack:///./src/lib/clarinet/clarinet.js","webpack:///./src/bundle.ts","webpack:///./src/index.ts","webpack:///./src/json-loader.ts","webpack:///../schema/src/index.ts","webpack:///../schema/src/lib/table/table-batch-builder.ts","webpack:///../schema/src/lib/table/base-table-batch-aggregator.ts","webpack:///../schema/src/category/mesh/mesh-utils.ts","webpack:///../schema/src/lib/schema/impl/schema.ts","webpack:///../schema/src/lib/utils/assert.ts","webpack:///../schema/src/lib/schema/impl/field.ts","webpack:///../schema/src/lib/schema/impl/type.ts","webpack:///../schema/src/lib/schema/impl/enum.ts","webpack:///../schema/src/lib/schema-utils/deduce-table-schema.ts","webpack:///../schema/src/lib/schema-utils/get-type-info.ts","webpack:///../schema/src/lib/schema-utils/type-utils.ts","webpack:///../schema/src/lib/utils/async-queue.ts","webpack:///../loader-utils/src/index.ts","webpack:///../loader-utils/src/lib/env-utils/globals.ts","webpack:///../loader-utils/src/lib/worker-loader-utils/create-loader-worker.ts","webpack:///../worker-utils/src/lib/worker-utils/get-loadable-worker-url.ts","webpack:///../worker-utils/src/lib/worker-api/process-on-worker.ts","webpack:///../worker-utils/src/lib/worker-utils/remove-nontransferable-options.ts","webpack:///../worker-utils/src/lib/worker-api/create-worker.ts","webpack:///../worker-utils/src/lib/worker-api/validate-worker-version.ts","webpack:///../worker-utils/src/lib/library-utils/library-utils.ts","webpack:///../loader-utils/src/lib/worker-loader-utils/parse-with-worker.ts","webpack:///../loader-utils/src/lib/parser-utils/parse-json.ts","webpack:///../loader-utils/src/lib/binary-utils/binary-copy-utils.ts","webpack:///../loader-utils/src/lib/binary-utils/encode-utils.ts","webpack:///../loader-utils/src/lib/iterators/text-iterators.ts","webpack:///../loader-utils/src/lib/iterators/async-iteration.ts","webpack:///../loader-utils/src/lib/request-utils/request-scheduler.ts","webpack:///../loader-utils/src/lib/path-utils/file-aliases.ts","webpack:///../loader-utils/src/json-loader.ts","webpack:///../loader-utils/src/lib/path-utils/path.ts","webpack:///../loader-utils/src/lib/filesystems/node-filesystem.ts","webpack:///./src/lib/parser/streaming-json-parser.ts","webpack:///./src/lib/parser/json-parser.ts","webpack:///./src/geojson-loader.ts","webpack:///../gis/src/index.ts","webpack:///../gis/src/lib/geojson-to-binary.ts","webpack:///../gis/src/lib/binary-to-geojson.ts","webpack:///../gis/src/lib/transform.ts","webpack:////home/user/apps/loaders.gl/node_modules/@probe.gl/stats/dist/esm/lib/stat.js","webpack:////home/user/apps/loaders.gl/node_modules/@probe.gl/stats/dist/esm/lib/stats.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","condition","message","Error","getHiResTimestamp","timestamp","window","performance","now","process","hrtime","timeParts","Date","g","this","Function","e","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","setTimeout","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","length","concat","drainQueue","timeout","len","run","marker","runClearTimeout","Item","array","noop","nextTick","args","Array","arguments","push","apply","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","globals","self","global","document","self_","window_","global_","document_","isBrowser","String","isWorker","importScripts","isMobile","orientation","matches","exec","nodeVersion","parseFloat","NOOP","WorkerThread","props","source","url","assert","onMessage","onError","error","console","log","worker","_createBrowserWorker","Worker","terminate","terminated","Boolean","data","transferList","getTransferList","postMessage","event","lineno","colno","_loadableURL","getLoadableWorkerURL","onmessage","onerror","_getErrorFromErrorEvent","onmessageerror","isTransferable","ArrayBuffer","MessagePort","ImageBitmap","OffscreenCanvas","recursive","transfers","transfersSet","Set","add","buffer","isView","undefined","from","JSONPath","path","isArray","split","join","pop","other","shift","field","jsonText","options","json","JSON","parse","table","getFirstArray","values","binaryAsyncIterator","asyncIterator","makeTextDecoderIterator","metadata","jsonpaths","isFirstChunk","shape","tableBatchBuilder","TableBatchBuilder","parser","StreamingJSONParser","chunk","rows","write","jsonpath","getStreamingJsonPathAsString","initialBatch","batchType","bytesUsed","container","getPartialResult","row","addRow","batch","getFullBatch","chunkComplete","getFinalBatch","finalBatch","RowTableBatchAggregator","schema","_headers","index","cursor","Number","isFinite","rowObject","convertToObjectRow","addObjectRow","arrayRows","rowArray","convertToArrayRow","addArrayRow","objectRows","slice","arrayRow","headers","objectRow","ColumnarTableBatchAggregator","_reallocateColumns","fieldName","columns","_pruneColumns","allocated","ArrayType","type","Float32Array","oldColumn","typedArray","set","entries","columnName","column","NullWorker","id","VERSION","null","WorkerJob","jobName","workerThread","isRunning","_resolve","_reject","result","Promise","resolve","reject","payload","DEFAULT_PROPS","maxConcurrency","maxMobileConcurrency","onDebug","reuseWorkers","WorkerFarm","Map","setProps","workerPools","isSupported","_workerFarm","destroy","_getWorkerPoolProps","workerPool","WorkerPool","idleQueue","forEach","isDestroyed","job","done","startPromise","onStart","jobQueue","_startQueuedJob","_getAvailableWorker","queuedJob","backlog","returnWorkerToQueue","count","_getMaxConcurrency","toLowerCase","onMessageWrapperMap","WorkerBody","isKnownMessage","onMessageWrapper","addEventListener","removeEventListener","startsWith","warning","workerOptions","workerFile","workerUrl","_workerType","versionTag","AsyncQueue","_values","_settlers","_closed","enqueue","settler","getMagicString","arrayBuffer","byteOffset","byteLength","dataView","DataView","magic","fromCharCode","getUint8","node","isBuffer","bufferToArrayBuffer","text","TextEncoder","encode","_toArrayBuffer","arrayBuffer1","arrayBuffer2","array1","Uint8Array","array2","sources","sourceArrays","map","source2","reduce","offset","sourceArray","typedArrays","arrays","TypedArrayConstructor","constructor","sumLength","acc","subArray","subarray","toBuffer","toArrayBuffer","targetBuffer","sourceBuffer","targetArray","target","targetOffset","srcByteOffset","srcByteLength","padToNBytes","padding","MAX_BUFFER_LENGTH","MAX_SAFE_INTEGER","DEBUG","CDEBUG","buffers","textNode","numberNode","S","STATE","BEGIN","VALUE","OPEN_OBJECT","CLOSE_OBJECT","OPEN_ARRAY","CLOSE_ARRAY","TEXT_ESCAPE","STRING","BACKSLASH","END","OPEN_KEY","CLOSE_KEY","TRUE","TRUE2","TRUE3","FALSE","FALSE2","FALSE3","FALSE4","NULL","NULL2","NULL3","NUMBER_DECIMAL_POINT","NUMBER_DIGIT","s_","Char","stringTokenPattern","ClarinetParser","_initialize","_clearBuffers","bufferCheckPosition","q","closed","closedRoot","sawRoot","tag","state","stack","position","line","slashed","unicodeI","unicodeS","depth","onready","onopenobject","onkey","oncloseobject","onopenarray","onclosearray","onvalue","onend","onchunkparsed","closeValue","end","charCodeAt","isWhitespace","emitNode","starti","STRING_BIGLOOP","parseInt","substring","lastIndex","reResult","indexOf","closeNumber","maxAllowed","Math","max","maxActual","closeText","checkBufferLength","opt","trim","normalize","replace","textopts","er","moduleExports","require","_global","loaders","assign","DEFAULT_JSON_LOADER_OPTIONS","JSONLoader","extensions","mimeTypes","category","parseTextSync","parseInBatches","jsonOptions","TextDecoder","decode","DEFAULT_OPTIONS","batchSize","batchDebounceMs","limit","_limitMB","totalLength","totalBytes","limitReached","rowBytes","_estimateRowMB","aggregator","TableBatchType","_getTableBatchType","isChunkComplete","_isFull","_getBatch","keys","rowCount","lastBatchEmittedMs","normalizedBatch","getBatch","batchCount","BaseTableBatchAggregator","ArrowBatch","attributes","size","attributeName","attribute","BYTES_PER_ELEMENT","minX","Infinity","minY","minZ","maxX","maxY","maxZ","positions","POSITION","x","y","z","Schema","fields","usedNames","warn","checkNames","compareTo","nameMap","columnNames","selectedFields","filter","columnIndices","schemaOrFields","otherSchema","mergeMaps","fieldMap","m1","m2","Field","nullable","typeId","DataType","Type","NONE","Null","Int","Float","Binary","Utf8","Bool","Decimal","Time","Timestamp","Interval","List","Struct","Union","FixedSizeBinary","FixedSizeList","Dictionary","isSigned","bitWidth","Int8","Int16","Int32","Int64","Uint8","Uint16","Uint32","Uint64","Precision","precision","Float16","Float32","Float64","DateUnit","DAY","MILLISECOND","unit","DateDay","DateMillisecond","TimeUnit","SECOND","MICROSECOND","NANOSECOND","TimeSecond","TimeMillisecond","timezone","TimestampSecond","TimestampMillisecond","TimestampMicrosecond","TimestampNanosecond","IntervalUnit","DAY_TIME","YEAR_MONTH","IntervalDayTime","IntervalYearMonth","listSize","child","children","valueType","deduceTypeFromValue","deducedSchema","rowTable","deduceSchemaForRowTable","columnarTable","deduceSchemaForColumnarTable","arrowTypeLike","typeName","toString","typeEnumName","getTypeKey","ReverseType","typeKey","Int8Array","Int16Array","Uint16Array","Int32Array","Uint32Array","Float64Array","ArrayQueue","dequeue","asyncIterable","iterator","next","loader","input","parseData","context","parseOnMainThread","requestId","parseSync","textDecoder","workerURL","workerURLCache","getLoadableWorkerURLFromSource","getLoadableWorkerURLFromURL","workerSource","blob","Blob","URL","createObjectURL","getWorkerName","getWorkerURL","workerFarm","getWorkerFarm","getWorkerPool","startJob","transferableOptions","removeNontransferableOptions","v","cache","stringify","has","err","processInBatches","processOnMainThread","inputBatches","resultIterator","close","coreVersion","workerVersion","loadLibraryPromises","libraryUrl","moduleName","getLibraryUrl","loadLibraryFromFile","library","CDN","endsWith","fetch","response","requireFromFile","scriptSource","loadLibraryFromString","requireFromString","eval","script","createElement","appendChild","createTextNode","body","string","_","getFirstCharacters","stringBuffer","copyPaddedArrayBufferToDataView","paddedLength","padLength","setUint8","byteAlignment","ceil","whitespace","binary","arrayBufferIterator","stream","textIterator","textEncoder","previous","eolIndex","lineIterator","counter","visitor","arrayBuffers","concatenateArrayBuffers","strings","throttleRequests","maxRequests","RequestScheduler","stats","Stats","handle","getPriority","requestMap","request","priority","promise","requestQueue","_issueNewRequests","isDone","activeRequestCount","deferredUpdate","_issueNewRequestsAsync","freeSlots","_updateAllRequests","_issueRequest","_updateRequest","splice","sort","a","b","prefix","pathPrefix","aliases","fileAliases","filename","alias","replacement","_typecheckJSONLoader","slashIndex","lastIndexOf","substr","parts","separator","part","RegExp","NodeFileSystem","_fetch","dirname","fs","readdir","stat","info","isDirectory","fallbackFetch","flags","open","fd","fstat","totalBytesRead","read","bytesRead","jsonPaths","_extendParser","streamingArray","topLevelObject","streamingJsonPath","currentPath","getJsonPath","equals","_matchJSONPath","clone","_openArray","_openObject","JSONParser","reset","_initializeParser","previousStates","currentState","freeze","newContainer","_pushOrSet","_parser","_closeObject","_closeArray","DEFAULT_GEOJSON_LOADER_OPTIONS","geojson","gis","format","GeoJSONWorkerLoader","GeoJSONLoader","geojsonIterator","makeBinaryGeometryIterator","geojsonToBinary","features","firstPassData","firstPass","secondPass","coordLength","numericPropKeys","PositionDataType","TEST_EXPORTS","pointPositionsCount","pointFeaturesCount","linePositionsCount","linePathsCount","lineFeaturesCount","polygonPositionsCount","polygonObjectsCount","polygonRingsCount","polygonFeaturesCount","coordLengths","feature","geometry","coordinates","point","coord","flatten","polygon","properties","val","k","GlobalFeatureIdsDataType","points","globalFeatureIds","featureIds","numericProps","lines","pathIndices","polygons","polygonIndices","primitivePolygonIndices","propName","indexMap","pointPosition","pointFeature","linePosition","linePath","lineFeature","polygonPosition","polygonObject","polygonRing","polygonFeature","handlePoint","keepStringProperties","handleMultiPoint","handleLineString","handleMultiLineString","handlePolygon","handleMultiPolygon","returnObj","geomType","numericProp","makeAccessorObjects","coords","fillNumericProperties","fillCoords","nPositions","fill","ring","numericPropName","numericKeys","includes","startVertex","parseFeatures","dataArray","lastValue","currValue","parseFeature","parseFeatureCollection","normalizeInput","binaryToGeometry","startIndex","endIndex","ringToGeoJson","pointToGeoJson","multi","ringCoordinates","lineStringToGeoJson","polygonToGeoJson","startRingIndex","endRingIndex","startPolygonIndex","endPolygonIndex","polygonCoordinates","unexpectedInput","parseType","parseProperties","parseFields","j","globalFeatureId","getSingleFeature","transformBinaryGeometryPositions","binaryGeometry","fn","transformedCoord","coordMap","isCoord","item","binaryFeatures","transformCoordinate","sampleSize","samples","addCount","subtractCount","_count","_samples","_checkSampling","time","_time","lastTiming","_startTime","_timerPending","addTime","lastSampleCount","lastSampleTime","_initializeStats","seal","_getOrCreate","average","getAverageTime","hz","getHz"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxB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,MACrByL,EAAGvzB,KAAK8nB,MAAMppB,IAIlB,WACE,MAAMwJ,EAAQ,GASd,OARAlI,KAAKkO,QAAQsc,IACXtiB,EAAMsiB,EAAK9sB,MAAQ,CACjB22B,KAAM7J,EAAK6J,MAAQ,EACnBvlB,MAAO0b,EAAK1b,OAAS,EACrBkmB,QAASxK,EAAKyK,kBAAoB,EAClCC,GAAI1K,EAAK2K,SAAW,KAGjBjtB,EAGT,iBAAiB4f,EAAQ,IACvBA,EAAM5Z,QAAQsc,GAAQxqB,KAAK+0B,aAAavK,IAG1C,aAAaA,GACX,IAAKA,IAASA,EAAK9sB,KACjB,OAAO,KAGT,MAAM,KACJA,EAAI,KACJiO,GACE6e,EAUJ,OARKxqB,KAAK8nB,MAAMpqB,KAEZsC,KAAK8nB,MAAMpqB,GADT8sB,aAAgB,EACCA,EAEA,IAAI,EAAK9sB,EAAMiO,IAI/B3L,KAAK8nB,MAAMpqB","file":"dist.es5.min.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 28);\n","// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\n\n/** Throws an `Error` with the optional `message` if `condition` is falsy */\nexport function assert(condition: any, message?: string): void {\n if (!condition) {\n throw new Error(message || 'loaders.gl assertion failed.');\n }\n}\n","export default function getHiResTimestamp() {\n let timestamp;\n\n if (typeof window !== 'undefined' && window.performance) {\n timestamp = window.performance.now();\n } else if (typeof process !== 'undefined' && process.hrtime) {\n const timeParts = process.hrtime();\n timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;\n } else {\n timestamp = Date.now();\n }\n\n return timestamp;\n}\n//# sourceMappingURL=hi-res-timestamp.js.map","// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\n// __VERSION__ is injected by babel-plugin-version-inline\n\n// Change to `latest` on production branches\nconst DEFAULT_VERSION = 'beta';\ndeclare let __VERSION__;\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : DEFAULT_VERSION;\nif (typeof __VERSION__ === 'undefined') {\n // eslint-disable-next-line\n console.error(\n 'loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN.'\n );\n}\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","/*\nexport {\n Schema,\n Field,\n DataType,\n Null,\n Bool,\n Int,\n Int8,\n Int16,\n Int32,\n Int64,\n Uint8,\n Uint16,\n Uint32,\n Uint64,\n Float,\n Float16,\n Float32,\n Float64,\n Binary,\n Utf8,\n Date,\n DateDay,\n DateMillisecond,\n Time,\n TimeSecond,\n TimeMillisecond,\n TimeMicrosecond,\n TimeNanosecond,\n Timestamp,\n TimestampSecond,\n TimestampMillisecond,\n TimestampMicrosecond,\n TimestampNanosecond,\n Interval,\n IntervalDayTime,\n IntervalYearMonth,\n FixedSizeList\n} from 'apache-arrow';\n*/\nexport {default as Schema} from './impl/schema';\nexport {default as Field} from './impl/field';\nexport {Type} from './impl/type';\nexport {\n DataType,\n Null,\n Bool,\n Int,\n Int8,\n Int16,\n Int32,\n Int64,\n Uint8,\n Uint16,\n Uint32,\n Uint64,\n Float,\n Float16,\n Float32,\n Float64,\n Binary,\n Utf8,\n Date,\n DateDay,\n DateMillisecond,\n Time,\n TimeSecond,\n TimeMillisecond,\n // TimeMicrosecond,\n // TimeNanosecond,\n Timestamp,\n TimestampSecond,\n TimestampMillisecond,\n TimestampMicrosecond,\n TimestampNanosecond,\n Interval,\n IntervalDayTime,\n IntervalYearMonth,\n FixedSizeList\n} from './impl/type';\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","// Purpose: include this in your module to avoids adding dependencies on\n// micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\nconst self_: {[key: string]: any} = globals.self || globals.window || globals.global || {};\nconst window_: {[key: string]: any} = globals.window || globals.self || globals.global || {};\nconst global_: {[key: string]: any} = globals.global || globals.self || globals.window || {};\nconst document_: {[key: string]: any} = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\n/** true if running in the browser, false if running in Node.js */\nexport const isBrowser: boolean =\n // @ts-ignore process.browser\n typeof process !== 'object' || String(process) !== '[object process]' || process.browser;\n\n/** true if running on a worker thread */\nexport const isWorker: boolean = typeof importScripts === 'function';\n\n/** true if running on a mobile device */\nexport const isMobile: boolean =\n typeof window !== 'undefined' && typeof window.orientation !== 'undefined';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\n\n/** Version of Node.js if running under Node, otherwise 0 */\nexport const nodeVersion: number = (matches && parseFloat(matches[1])) || 0;\n","import {assert} from '../env-utils/assert';\nimport {getLoadableWorkerURL} from '../worker-utils/get-loadable-worker-url';\nimport {getTransferList} from '../worker-utils/get-transfer-list';\n\nconst NOOP = () => {};\n\nexport type WorkerThreadProps = {\n name: string;\n source?: string;\n url?: string;\n};\n\n/**\n * Represents one worker thread\n */\nexport default class WorkerThread {\n readonly name: string;\n readonly source: string | undefined;\n readonly url: string | undefined;\n terminated: boolean = false;\n worker: Worker;\n onMessage: (message: any) => void;\n onError: (error: Error) => void;\n\n private _loadableURL: string = '';\n\n static isSupported(): boolean {\n return typeof Worker !== 'undefined';\n }\n\n constructor(props: WorkerThreadProps) {\n const {name, source, url} = props;\n assert(source || url); // Either source or url must be defined\n this.name = name;\n this.source = source;\n this.url = url;\n this.onMessage = NOOP;\n this.onError = (error) => console.log(error); // eslint-disable-line\n\n this.worker = this._createBrowserWorker();\n }\n\n /**\n * Terminate this worker thread\n * @note Can free up significant memory\n */\n destroy(): void {\n this.onMessage = NOOP;\n this.onError = NOOP;\n // @ts-ignore\n this.worker.terminate();\n this.terminated = true;\n }\n\n get isRunning() {\n return Boolean(this.onMessage);\n }\n\n /**\n * Send a message to this worker thread\n * @param data any data structure, ideally consisting mostly of transferrable objects\n * @param transferList If not supplied, calculated automatically by traversing data\n */\n postMessage(data: any, transferList?: any[]): void {\n transferList = transferList || getTransferList(data);\n // @ts-ignore\n this.worker.postMessage(data, transferList);\n }\n\n // PRIVATE\n\n /**\n * Generate a standard Error from an ErrorEvent\n * @param {ErrorEvent} event\n */\n _getErrorFromErrorEvent(event) {\n // Note Error object does not have the expected fields if loading failed completely\n // https://developer.mozilla.org/en-US/docs/Web/API/Worker#Event_handlers\n // https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent\n let message = 'Failed to load ';\n message += `worker ${this.name}. `;\n if (event.message) {\n message += `${event.message} in `;\n }\n // const hasFilename = event.filename && !event.filename.startsWith('blob:');\n // message += hasFilename ? event.filename : this.source.slice(0, 100);\n if (event.lineno) {\n message += `:${event.lineno}:${event.colno}`;\n }\n return new Error(message);\n }\n\n /**\n * Creates a worker thread on the browser\n */\n _createBrowserWorker() {\n this._loadableURL = getLoadableWorkerURL({source: this.source, url: this.url});\n const worker = new Worker(this._loadableURL, {name: this.name});\n\n worker.onmessage = (event) => {\n if (!event.data) {\n this.onError(new Error('No data received'));\n } else {\n this.onMessage(event.data);\n }\n };\n // This callback represents an uncaught exception in the worker thread\n worker.onerror = (error) => {\n this.onError(this._getErrorFromErrorEvent(error));\n this.terminated = true;\n };\n // TODO - not clear when this would be called, for now just log in case it happens\n worker.onmessageerror = (event) => console.error(event); // eslint-disable-line\n\n return worker;\n }\n}\n","// NOTE - there is a copy of this function is both in core and loader-utils\n// core does not need all the utils in loader-utils, just this one.\n\n/**\n * Returns an array of Transferrable objects that can be used with postMessage\n * https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage\n * @param object data to be sent via postMessage\n * @param recursive - not for application use\n * @param transfers - not for application use\n * @returns a transfer list that can be passed to postMessage\n */\nexport function getTransferList(\n object: any,\n recursive: boolean = true,\n transfers?: Set<any>\n): Transferable[] {\n // Make sure that items in the transfer list is unique\n const transfersSet = transfers || new Set();\n\n if (!object) {\n // ignore\n } else if (isTransferable(object)) {\n transfersSet.add(object);\n } else if (isTransferable(object.buffer)) {\n // Typed array\n transfersSet.add(object.buffer);\n } else if (ArrayBuffer.isView(object)) {\n // object is a TypeArray viewing into a SharedArrayBuffer (not transferable)\n // Do not iterate through the content in this case\n } else if (recursive && typeof object === 'object') {\n for (const key in object) {\n // Avoid perf hit - only go one level deep\n getTransferList(object[key], recursive, transfersSet);\n }\n }\n\n // If transfers is defined, is internal recursive call\n // Otherwise it's called by the user\n return transfers === undefined ? Array.from(transfersSet) : [];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Transferable\nfunction isTransferable(object) {\n if (!object) {\n return false;\n }\n if (object instanceof ArrayBuffer) {\n return true;\n }\n if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {\n return true;\n }\n if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {\n return true;\n }\n // @ts-ignore\n if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {\n return true;\n }\n return false;\n}\n","/**\n * A parser for a minimal subset of the jsonpath standard\n * Full JSON path parsers for JS exist but are quite large (bundle size)\n *\n * Supports\n *\n * `$.component.component.component`\n */\nexport default class JSONPath {\n path: string[];\n\n constructor(path: JSONPath | string[] | string | null = null) {\n this.path = ['$'];\n\n if (path instanceof JSONPath) {\n // @ts-ignore\n this.path = [...path.path];\n return;\n }\n\n if (Array.isArray(path)) {\n this.path.push(...path);\n return;\n }\n\n // Parse a string as a JSONPath\n if (typeof path === 'string') {\n this.path = path.split('.');\n if (this.path[0] !== '$') {\n throw new Error('JSONPaths must start with $');\n }\n }\n }\n\n clone(): JSONPath {\n return new JSONPath(this);\n }\n\n toString(): string {\n return this.path.join('.');\n }\n\n push(name: string): void {\n this.path.push(name);\n }\n\n pop() {\n return this.path.pop();\n }\n\n set(name: string): void {\n this.path[this.path.length - 1] = name;\n }\n\n equals(other: JSONPath): boolean {\n if (!this || !other || this.path.length !== other.path.length) {\n return false;\n }\n\n for (let i = 0; i < this.path.length; ++i) {\n if (this.path[i] !== other.path[i]) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Sets the value pointed at by path\n * TODO - handle root path\n * @param object\n * @param value\n */\n setFieldAtPath(object, value) {\n const path = [...this.path];\n path.shift();\n const field = path.pop();\n for (const component of path) {\n object = object[component];\n }\n // @ts-ignore\n object[field] = value;\n }\n\n /**\n * Gets the value pointed at by path\n * TODO - handle root path\n * @param object\n */\n getFieldAtPath(object) {\n const path = [...this.path];\n path.shift();\n const field = path.pop();\n for (const component of path) {\n object = object[component];\n }\n // @ts-ignore\n return object[field];\n }\n}\n","import type {JSONLoaderOptions} from '../json-loader';\n\nexport default function parseJSONSync(jsonText: string, options: JSONLoaderOptions) {\n try {\n const json = JSON.parse(jsonText);\n if (options.json?.table) {\n return getFirstArray(json) || json;\n }\n return json;\n } catch (error) {\n throw new Error('JSONLoader: failed to parse JSON');\n }\n}\n\nfunction getFirstArray(json) {\n if (Array.isArray(json)) {\n return json;\n }\n if (json && typeof json === 'object') {\n for (const value of Object.values(json)) {\n const array = getFirstArray(value);\n if (array) {\n return array;\n }\n }\n }\n return null;\n}\n","import type {Batch} from '@loaders.gl/schema';\nimport type {JSONLoaderOptions} from '../json-loader';\nimport {TableBatchBuilder} from '@loaders.gl/schema';\nimport {makeTextDecoderIterator} from '@loaders.gl/loader-utils';\nimport StreamingJSONParser from './parser/streaming-json-parser';\n\n// TODO - support batch size 0 = no batching/single batch?\n// eslint-disable-next-line max-statements, complexity\nexport default async function* parseJSONInBatches(\n binaryAsyncIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>,\n options: JSONLoaderOptions\n): AsyncIterable<Batch> {\n const asyncIterator = makeTextDecoderIterator(binaryAsyncIterator);\n\n const {metadata} = options;\n const {jsonpaths} = options.json || {};\n\n let isFirstChunk: boolean = true;\n\n // TODO fix Schema deduction\n const schema = null; // new Schema([]);\n const shape = options?.json?.shape || 'row-table';\n // @ts-ignore\n const tableBatchBuilder = new TableBatchBuilder(schema, {\n ...options,\n shape\n });\n\n const parser = new StreamingJSONParser({jsonpaths});\n\n for await (const chunk of asyncIterator) {\n const rows = parser.write(chunk);\n\n const jsonpath = rows.length > 0 && parser.getStreamingJsonPathAsString();\n\n if (rows.length > 0 && isFirstChunk) {\n if (metadata) {\n const initialBatch: Batch = {\n // Common fields\n shape,\n batchType: 'partial-result',\n data: [],\n length: 0,\n bytesUsed: 0,\n // JSON additions\n container: parser.getPartialResult(),\n jsonpath\n };\n yield initialBatch;\n }\n isFirstChunk = false;\n // schema = deduceSchema(rows);\n }\n\n // Add the row\n for (const row of rows) {\n tableBatchBuilder.addRow(row);\n // If a batch has been completed, emit it\n const batch = tableBatchBuilder.getFullBatch({jsonpath});\n if (batch) {\n yield batch;\n }\n }\n\n tableBatchBuilder.chunkComplete(chunk);\n const batch = tableBatchBuilder.getFullBatch({jsonpath});\n if (batch) {\n yield batch;\n }\n }\n\n // yield final batch\n const jsonpath = parser.getStreamingJsonPathAsString();\n const batch = tableBatchBuilder.getFinalBatch({jsonpath});\n if (batch) {\n yield batch;\n }\n\n if (metadata) {\n const finalBatch: Batch = {\n shape,\n batchType: 'final-result',\n container: parser.getPartialResult(),\n jsonpath: parser.getStreamingJsonPathAsString(),\n data: [],\n length: 0\n // schema: null\n };\n yield finalBatch;\n }\n}\n","import type {Schema} from '../schema';\nimport type {TableBatch} from '../../category/table';\n// import type {ArrayRowTableBatch, ObjectRowTableBatch} from '../../category/table';\nimport {convertToArrayRow, convertToObjectRow} from '../utils/row-utils';\nimport {TableBatchAggregator, TableBatchOptions} from './table-batch-aggregator';\n\nconst DEFAULT_ROW_COUNT = 100;\n\nexport default class RowTableBatchAggregator implements TableBatchAggregator {\n schema: Schema;\n options: TableBatchOptions;\n\n length: number = 0;\n objectRows: {[columnName: string]: any} | null = null;\n arrayRows: any[] | null = null;\n cursor: number = 0;\n private _headers: string[] = [];\n\n constructor(schema: Schema, options: TableBatchOptions) {\n this.options = options;\n this.schema = schema;\n\n // schema is an array if there're no headers\n // object if there are headers\n if (!Array.isArray(schema)) {\n this._headers = [];\n for (const key in schema) {\n this._headers[schema[key].index] = schema[key].name;\n }\n }\n }\n\n rowCount(): number {\n return this.length;\n }\n\n addArrayRow(row: any[], cursor?: number): void {\n if (Number.isFinite(cursor)) {\n this.cursor = cursor as number;\n }\n\n // eslint-disable-next-line default-case\n switch (this.options.shape) {\n case 'object-row-table':\n const rowObject = convertToObjectRow(row, this._headers);\n this.addObjectRow(rowObject, cursor);\n break;\n case 'array-row-table':\n this.arrayRows = this.arrayRows || new Array(DEFAULT_ROW_COUNT);\n this.arrayRows[this.length] = row;\n this.length++;\n break;\n }\n }\n\n addObjectRow(row: {[columnName: string]: any}, cursor?: number): void {\n if (Number.isFinite(cursor)) {\n this.cursor = cursor as number;\n }\n\n // eslint-disable-next-line default-case\n switch (this.options.shape) {\n case 'array-row-table':\n const rowArray = convertToArrayRow(row, this._headers);\n this.addArrayRow(rowArray, cursor);\n break;\n case 'object-row-table':\n this.objectRows = this.objectRows || new Array(DEFAULT_ROW_COUNT);\n this.objectRows[this.length] = row;\n this.length++;\n break;\n }\n }\n\n getBatch(): TableBatch | null {\n let rows = this.arrayRows || this.objectRows;\n if (!rows) {\n return null;\n }\n\n rows = rows.slice(0, this.length);\n this.arrayRows = null;\n this.objectRows = null;\n\n return {\n shape: this.options.shape,\n batchType: 'data',\n data: rows,\n length: this.length,\n schema: this.schema,\n cursor: this.cursor\n };\n }\n}\n","/** Convert an object row to an array row */\nexport function convertToObjectRow(\n arrayRow: any[],\n headers: string[]\n): {[columnName: string]: any} {\n if (!arrayRow) {\n throw new Error('null row');\n }\n if (!headers) {\n throw new Error('no headers');\n }\n const objectRow = {};\n for (let i = 0; i < headers.length; i++) {\n objectRow[headers[i]] = arrayRow[i];\n }\n return objectRow;\n}\n\n/** Convert an object row to an array row */\nexport function convertToArrayRow(\n objectRow: {[columnName: string]: any},\n headers: string[]\n): any[] {\n if (!objectRow) {\n throw new Error('null row');\n }\n if (!headers) {\n throw new Error('no headers');\n }\n const arrayRow = new Array(headers.length);\n for (let i = 0; i < headers.length; i++) {\n arrayRow[i] = objectRow[headers[i]];\n }\n return arrayRow;\n}\n","import type {Schema} from '../schema';\nimport type {ColumnarTableBatch, ArrowTableBatch} from '../../category/table';\nimport {TableBatchAggregator} from './table-batch-aggregator';\n\ntype ColumnarTableBatchOptions = {};\n\nconst DEFAULT_ROW_COUNT = 100;\n\nexport default class ColumnarTableBatchAggregator implements TableBatchAggregator {\n schema: Schema;\n length: number = 0;\n allocated: number = 0;\n columns: {[columnName: string]: any[]} = {};\n\n constructor(schema: Schema, options: ColumnarTableBatchOptions) {\n this.schema = schema;\n this._reallocateColumns();\n }\n\n rowCount(): number {\n return this.length;\n }\n\n addArrayRow(row: any[]) {\n // If user keeps pushing rows beyond batch size, reallocate\n this._reallocateColumns();\n let i = 0;\n // TODO what if no csv header, columns not populated?\n for (const fieldName in this.columns) {\n this.columns[fieldName][this.length] = row[i++];\n }\n this.length++;\n }\n\n addObjectRow(row: {[columnName: string]: any}): void {\n // If user keeps pushing rows beyond batch size, reallocate\n this._reallocateColumns();\n for (const fieldName in row) {\n this.columns[fieldName][this.length] = row[fieldName];\n }\n this.length++;\n }\n\n getBatch(): ColumnarTableBatch | ArrowTableBatch | null {\n this._pruneColumns();\n const columns = Array.isArray(this.schema) ? this.columns : {};\n\n // schema is an array if there're no headers\n // object if there are headers\n // columns should match schema format\n if (!Array.isArray(this.schema)) {\n for (const fieldName in this.schema) {\n const field = this.schema[fieldName];\n columns[field.name] = this.columns[field.index];\n }\n }\n\n this.columns = {};\n\n const batch: ColumnarTableBatch = {\n shape: 'columnar-table',\n batchType: 'data',\n data: columns,\n schema: this.schema,\n length: this.length\n };\n\n return batch;\n }\n\n // HELPERS\n\n _reallocateColumns() {\n if (this.length < this.allocated) {\n return;\n }\n\n // @ts-ignore TODO\n this.allocated = this.allocated > 0 ? (this.allocated *= 2) : DEFAULT_ROW_COUNT;\n this.columns = {};\n\n for (const fieldName in this.schema) {\n const field = this.schema[fieldName];\n const ArrayType = field.type || Float32Array;\n const oldColumn = this.columns[field.index];\n\n if (oldColumn && ArrayBuffer.isView(oldColumn)) {\n // Copy the old data to the new array\n const typedArray = new ArrayType(this.allocated);\n typedArray.set(oldColumn);\n this.columns[field.index] = typedArray;\n } else if (oldColumn) {\n // Plain array\n oldColumn.length = this.allocated;\n this.columns[field.index] = oldColumn;\n } else {\n // Create new\n this.columns[field.index] = new ArrayType(this.allocated);\n }\n }\n }\n\n _pruneColumns() {\n for (const [columnName, column] of Object.entries(this.columns)) {\n this.columns[columnName] = column.slice(0, this.length);\n }\n }\n}\n","/**\n * Throws an `Error` with the optional `message` if `condition` is falsy\n * @note Replacement for the external assert method to reduce bundle size\n */\nexport function assert(condition: any, message?: string): void {\n if (!condition) {\n throw new Error(message || 'loader assertion failed.');\n }\n}\n","import type {WorkerObject} from './types';\nimport {VERSION} from './lib/env-utils/version';\n\n// TYPES\nexport type {\n WorkerObject,\n WorkerOptions,\n // Protocol\n WorkerMessage,\n WorkerMessageType,\n WorkerMessageData,\n WorkerMessagePayload\n} from './types';\n\n// GENERAL UTILS\nexport {assert} from './lib/env-utils/assert';\nexport {isBrowser, isWorker} from './lib/env-utils/globals';\n\n// WORKER UTILS - TYPES\nexport {default as WorkerJob} from './lib/worker-farm/worker-job';\nexport {default as WorkerThread} from './lib/worker-farm/worker-thread';\n\n// WORKER FARMS\nexport {default as WorkerFarm} from './lib/worker-farm/worker-farm';\nexport {default as WorkerPool} from './lib/worker-farm/worker-pool';\nexport {default as WorkerBody} from './lib/worker-farm/worker-body';\n\nexport {processOnWorker, canProcessOnWorker} from './lib/worker-api/process-on-worker';\nexport {createWorker} from './lib/worker-api/create-worker';\n\n// WORKER UTILS - EXPORTS\nexport {getWorkerURL} from './lib/worker-api/get-worker-url';\nexport {validateWorkerVersion} from './lib/worker-api/validate-worker-version';\nexport {getTransferList} from './lib/worker-utils/get-transfer-list';\n\n// LIBRARY UTILS\nexport {getLibraryUrl, loadLibrary} from './lib/library-utils/library-utils';\n\n// PARSER UTILS\nexport {default as AsyncQueue} from './lib/async-queue/async-queue';\n\n// PROCESS UTILS\nexport {default as ChildProcessProxy} from './lib/process-utils/child-process-proxy';\n\n// WORKER OBJECTS\n\n/** A null worker to test that worker processing is functional */\nexport const NullWorker: WorkerObject = {\n id: 'null',\n name: 'null',\n module: 'worker-utils',\n version: VERSION,\n options: {\n null: {}\n }\n};\n","import type {WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport WorkerThread from './worker-thread';\nimport {assert} from '../env-utils/assert';\n\n/**\n * Represents one Job handled by a WorkerPool or WorkerFarm\n */\nexport default class WorkerJob {\n readonly name: string;\n readonly workerThread: WorkerThread;\n isRunning: boolean;\n /** Promise that resolves when Job is done */\n readonly result: Promise<any>;\n\n private _resolve: (value: any) => void;\n private _reject: (reason?: any) => void;\n\n constructor(jobName: string, workerThread: WorkerThread) {\n this.name = jobName;\n this.workerThread = workerThread;\n this.isRunning = true;\n this._resolve = () => {};\n this._reject = () => {};\n this.result = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n /**\n * Send a message to the job's worker thread\n * @param data any data structure, ideally consisting mostly of transferrable objects\n */\n postMessage(type: WorkerMessageType, payload: WorkerMessagePayload): void {\n this.workerThread.postMessage({\n source: 'loaders.gl', // Lets worker ignore unrelated messages\n type,\n payload\n });\n }\n\n /**\n * Call to resolve the `result` Promise with the supplied value\n */\n done(value): void {\n assert(this.isRunning);\n this.isRunning = false;\n this._resolve(value);\n }\n\n /**\n * Call to reject the `result` Promise with the supplied error\n */\n error(error): void {\n assert(this.isRunning);\n this.isRunning = false;\n this._reject(error);\n }\n}\n","import WorkerPool from './worker-pool';\nimport WorkerThread from './worker-thread';\n\n/**\n * @param maxConcurrency {number} - max count of workers\n */\nexport type WorkerFarmProps = {\n maxConcurrency?: number;\n maxMobileConcurrency?: number;\n reuseWorkers?: boolean;\n onDebug?: () => void;\n};\n\nconst DEFAULT_PROPS: WorkerFarmProps = {\n maxConcurrency: 3,\n maxMobileConcurrency: 1,\n onDebug: () => {},\n reuseWorkers: true\n};\n\n/**\n * Process multiple jobs with a \"farm\" of different workers in worker pools.\n */\nexport default class WorkerFarm {\n private props: WorkerFarmProps;\n private workerPools = new Map<string, WorkerPool>();\n // singleton\n private static _workerFarm?: WorkerFarm;\n\n /** Check if Workers are supported */\n static isSupported(): boolean {\n return WorkerThread.isSupported();\n }\n\n /** Get the singleton instance of the global worker farm */\n static getWorkerFarm(props: WorkerFarmProps = {}): WorkerFarm {\n WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});\n WorkerFarm._workerFarm.setProps(props);\n return WorkerFarm._workerFarm;\n }\n\n /** get global instance with WorkerFarm.getWorkerFarm() */\n private constructor(props: WorkerFarmProps) {\n this.props = {...DEFAULT_PROPS};\n this.setProps(props);\n /** @type Map<string, WorkerPool>} */\n this.workerPools = new Map();\n }\n\n /**\n * Terminate all workers in the farm\n * @note Can free up significant memory\n */\n destroy(): void {\n for (const workerPool of this.workerPools.values()) {\n workerPool.destroy();\n }\n }\n\n /**\n * Set props used when initializing worker pools\n * @param props\n */\n setProps(props: WorkerFarmProps): void {\n this.props = {...this.props, ...props};\n // Update worker pool props\n for (const workerPool of this.workerPools.values()) {\n workerPool.setProps(this._getWorkerPoolProps());\n }\n }\n\n /**\n * Returns a worker pool for the specified worker\n * @param options - only used first time for a specific worker name\n * @param options.name - the name of the worker - used to identify worker pool\n * @param options.url -\n * @param options.source -\n * @example\n * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...);\n */\n getWorkerPool(options: {name: string; source?: string; url?: string}): WorkerPool {\n const {name, source, url} = options;\n let workerPool = this.workerPools.get(name);\n if (!workerPool) {\n workerPool = new WorkerPool({\n name,\n source,\n url\n });\n workerPool.setProps(this._getWorkerPoolProps());\n this.workerPools.set(name, workerPool);\n }\n return workerPool;\n }\n\n _getWorkerPoolProps() {\n return {\n maxConcurrency: this.props.maxConcurrency,\n maxMobileConcurrency: this.props.maxMobileConcurrency,\n reuseWorkers: this.props.reuseWorkers,\n onDebug: this.props.onDebug\n };\n }\n}\n","import type {WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport {isMobile} from '../env-utils/globals';\nimport WorkerThread from './worker-thread';\nimport WorkerJob from './worker-job';\n\n/** WorkerPool onDebug Callback Parameters */\ntype OnDebugParameters = {\n message: string;\n worker: string;\n name: string;\n job: string;\n backlog: number;\n workerThread: WorkerThread;\n};\n\n/** WorkerPool Properties */\nexport type WorkerPoolProps = {\n name?: string;\n source?: string; // | Function;\n url?: string;\n maxConcurrency?: number;\n maxMobileConcurrency?: number;\n onDebug?: (options: OnDebugParameters) => any;\n reuseWorkers?: boolean;\n};\n\n/** Private helper types */\ntype OnMessage = (job: WorkerJob, type: WorkerMessageType, payload: WorkerMessagePayload) => void;\ntype OnError = (job: WorkerJob, error: Error) => void;\n\ntype QueuedJob = {\n name: string;\n onMessage: OnMessage;\n onError: OnError;\n onStart: (value: any) => void; // Resolve job start promise\n};\n\n/**\n * Process multiple data messages with small pool of identical workers\n */\nexport default class WorkerPool {\n name: string = 'unnamed';\n source?: string; // | Function;\n url?: string;\n maxConcurrency: number = 1;\n maxMobileConcurrency: number = 1;\n onDebug: (options: OnDebugParameters) => any = () => {};\n reuseWorkers: boolean = true;\n\n private props: WorkerPoolProps = {};\n private jobQueue: QueuedJob[] = [];\n private idleQueue: WorkerThread[] = [];\n private count = 0;\n private isDestroyed = false;\n\n /**\n * @param processor - worker function\n * @param maxConcurrency - max count of workers\n */\n constructor(props: WorkerPoolProps) {\n this.source = props.source;\n this.url = props.url;\n this.setProps(props);\n }\n\n /**\n * Terminates all workers in the pool\n * @note Can free up significant memory\n */\n destroy(): void {\n // Destroy idle workers, active Workers will be destroyed on completion\n this.idleQueue.forEach((worker) => worker.destroy());\n this.isDestroyed = true;\n }\n\n setProps(props: WorkerPoolProps) {\n this.props = {...this.props, ...props};\n\n if (props.name !== undefined) {\n this.name = props.name;\n }\n if (props.maxConcurrency !== undefined) {\n this.maxConcurrency = props.maxConcurrency;\n }\n if (props.maxMobileConcurrency !== undefined) {\n this.maxMobileConcurrency = props.maxMobileConcurrency;\n }\n if (props.reuseWorkers !== undefined) {\n this.reuseWorkers = props.reuseWorkers;\n }\n if (props.onDebug !== undefined) {\n this.onDebug = props.onDebug;\n }\n }\n\n async startJob(\n name: string,\n onMessage: OnMessage = (job, type, data) => job.done(data),\n onError: OnError = (job, error) => job.error(error)\n ): Promise<WorkerJob> {\n // Promise resolves when thread starts working on this job\n const startPromise = new Promise<WorkerJob>((onStart) => {\n // Promise resolves when thread completes or fails working on this job\n this.jobQueue.push({name, onMessage, onError, onStart});\n return this;\n });\n this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises\n return await startPromise;\n }\n\n // PRIVATE\n\n /**\n * Starts first queued job if worker is available or can be created\n * Called when job is started and whenever a worker returns to the idleQueue\n */\n async _startQueuedJob(): Promise<void> {\n if (!this.jobQueue.length) {\n return;\n }\n\n const workerThread = this._getAvailableWorker();\n if (!workerThread) {\n return;\n }\n\n // We have a worker, dequeue and start the job\n const queuedJob = this.jobQueue.shift();\n if (queuedJob) {\n // Emit a debug event\n // @ts-ignore\n this.onDebug({\n message: 'Starting job',\n name: queuedJob.name,\n workerThread,\n backlog: this.jobQueue.length\n });\n\n // Create a worker job to let the app access thread and manage job completion\n const job = new WorkerJob(queuedJob.name, workerThread);\n\n // Set the worker thread's message handlers\n workerThread.onMessage = (data) => queuedJob.onMessage(job, data.type, data.payload);\n workerThread.onError = (error) => queuedJob.onError(job, error);\n\n // Resolve the start promise so that the app can start sending messages to worker\n queuedJob.onStart(job);\n\n // Wait for the app to signal that the job is complete, then return worker to queue\n try {\n await job.result;\n } finally {\n this.returnWorkerToQueue(workerThread);\n }\n }\n }\n\n /**\n * Returns a worker to the idle queue\n * Destroys the worker if\n * - pool is destroyed\n * - if this pool doesn't reuse workers\n * - if maxConcurrency has been lowered\n * @param worker\n */\n returnWorkerToQueue(worker: WorkerThread) {\n const shouldDestroyWorker =\n this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();\n\n if (shouldDestroyWorker) {\n worker.destroy();\n this.count--;\n } else {\n this.idleQueue.push(worker);\n }\n\n if (!this.isDestroyed) {\n this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises\n }\n }\n\n /**\n * Returns idle worker or creates new worker if maxConcurrency has not been reached\n */\n _getAvailableWorker(): WorkerThread | null {\n // If a worker has completed and returned to the queue, it can be used\n if (this.idleQueue.length > 0) {\n return this.idleQueue.shift() || null;\n }\n\n // Create fresh worker if we haven't yet created the max amount of worker threads for this worker source\n if (this.count < this._getMaxConcurrency()) {\n this.count++;\n const name = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`;\n return new WorkerThread({name, source: this.source, url: this.url});\n }\n\n // No worker available, have to wait\n return null;\n }\n\n _getMaxConcurrency() {\n return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;\n }\n}\n","import type {WorkerMessageData, WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport {getTransferList} from '../worker-utils/get-transfer-list';\n\nconst onMessageWrapperMap = new Map();\n\n/**\n * Type safe wrapper for worker code\n */\nexport default class WorkerBody {\n /*\n * (type: WorkerMessageType, payload: WorkerMessagePayload) => any\n */\n static set onmessage(onMessage: (type: WorkerMessageType, payload: WorkerMessagePayload) => any) {\n // eslint-disable-next-line no-restricted-globals\n self.onmessage = (message) => {\n if (!isKnownMessage(message)) {\n return;\n }\n\n // Confusingly the message itself also has a 'type' field which is always set to 'message'\n const {type, payload} = message.data;\n onMessage(type, payload);\n };\n }\n\n static addEventListener(\n onMessage: (type: WorkerMessageType, payload: WorkerMessagePayload) => any\n ) {\n let onMessageWrapper = onMessageWrapperMap.get(onMessage);\n\n if (!onMessageWrapper) {\n onMessageWrapper = (message) => {\n if (!isKnownMessage(message)) {\n return;\n }\n\n // Confusingly the message itself also has a 'type' field which is always set to 'message'\n const {type, payload} = message.data;\n onMessage(type, payload);\n };\n }\n\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('message', onMessageWrapper);\n }\n\n static removeEventListener(\n onMessage: (type: WorkerMessageType, payload: WorkerMessagePayload) => any\n ) {\n const onMessageWrapper = onMessageWrapperMap.get(onMessage);\n onMessageWrapperMap.delete(onMessage);\n // eslint-disable-next-line no-restricted-globals\n self.removeEventListener('message', onMessageWrapper);\n }\n\n /**\n * Send a message from a worker to creating thread (main thread)\n * @param type\n * @param payload\n */\n static postMessage(type: WorkerMessageType, payload: WorkerMessagePayload): void {\n if (self) {\n const data: WorkerMessageData = {source: 'loaders.gl', type, payload};\n const transferList = getTransferList(payload);\n // eslint-disable-next-line no-restricted-globals\n // @ts-ignore\n self.postMessage(data, transferList);\n }\n }\n}\n\n// Filter out noise messages sent to workers\nfunction isKnownMessage(message) {\n const {type, data} = message;\n return (\n type === 'message' &&\n data &&\n typeof data.source === 'string' &&\n data.source.startsWith('loaders.gl')\n );\n}\n","import type {WorkerObject, WorkerOptions} from '../../types';\nimport {assert} from '../env-utils/assert';\nimport {VERSION as __VERSION__} from '../env-utils/version';\n\nconst NPM_TAG = 'latest';\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : NPM_TAG;\n\n/**\n * Gets worker object's name (for debugging in Chrome thread inspector window)\n */\nexport function getWorkerName(worker: WorkerObject): string {\n const warning = worker.version !== VERSION ? ` (worker-utils@${VERSION})` : '';\n return `${worker.name}@${worker.version}${warning}`;\n}\n\n/**\n * Generate a worker URL based on worker object and options\n * @returns A URL to one of the following:\n * - a published worker on unpkg CDN\n * - a local test worker\n * - a URL provided by the user in options\n */\nexport function getWorkerURL(worker: WorkerObject, options: WorkerOptions = {}): string {\n const workerOptions = options[worker.id] || {};\n\n const workerFile = `${worker.id}-worker.js`;\n\n let url = workerOptions.workerUrl;\n\n // HACK: Allow for non-nested workerUrl for the CompressionWorker.\n // For the compression worker, workerOptions is currently not nested correctly. For most loaders,\n // you'd have options within an object, i.e. `{mvt: {coordinates: ...}}` but the CompressionWorker\n // puts options at the top level, not within a `compression` key (its `id`). For this reason, the\n // above `workerOptions` will always be a string (i.e. `'gzip'`) for the CompressionWorker. To not\n // break backwards compatibility, we allow the CompressionWorker to have options at the top level.\n if (!url && worker.id === 'compression') {\n url = options.workerUrl;\n }\n\n // If URL is test, generate local loaders.gl url\n // @ts-ignore _workerType\n if (options._workerType === 'test') {\n url = `modules/${worker.module}/dist/${workerFile}`;\n }\n\n // If url override is not provided, generate a URL to published version on npm CDN unpkg.com\n if (!url) {\n // GENERATE\n let version = worker.version;\n // On master we need to load npm alpha releases published with the `beta` tag\n if (version === 'latest') {\n // throw new Error('latest worker version specified');\n version = NPM_TAG;\n }\n const versionTag = version ? `@${version}` : '';\n url = `https://unpkg.com/@loaders.gl/${worker.module}${versionTag}/dist/${workerFile}`;\n }\n\n assert(url);\n\n // Allow user to override location\n return url;\n}\n","// From https://github.com/rauschma/async-iter-demo/tree/master/src under MIT license\n// http://2ality.com/2016/10/asynchronous-iteration.html\n\n/**\n * Async Queue\n * - AsyncIterable: An async iterator can be\n * - Values can be pushed onto the queue\n * @example\n * const asyncQueue = new AsyncQueue();\n * setTimeout(() => asyncQueue.enqueue('tick'), 1000);\n * setTimeout(() => asyncQueue.enqueue(new Error('done')), 10000);\n * for await (const value of asyncQueue) {\n * console.log(value); // tick\n * }\n */\nexport default class AsyncQueue<T> {\n private _values: any[];\n private _settlers: any[];\n private _closed: boolean;\n\n constructor() {\n this._values = []; // enqueues > dequeues\n this._settlers = []; // dequeues > enqueues\n this._closed = false;\n }\n\n /** Return an async iterator for this queue */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this;\n }\n\n /** Push a new value - the async iterator will yield a promise resolved to this value */\n push(value: T): void {\n return this.enqueue(value);\n }\n\n /**\n * Push a new value - the async iterator will yield a promise resolved to this value\n * Add an error - the async iterator will yield a promise rejected with this value\n */\n enqueue(value: T | Error): void {\n if (this._closed) {\n throw new Error('Closed');\n }\n\n if (this._settlers.length > 0) {\n if (this._values.length > 0) {\n throw new Error('Illegal internal state');\n }\n const settler = this._settlers.shift();\n if (value instanceof Error) {\n settler.reject(value);\n } else {\n settler.resolve({value});\n }\n } else {\n this._values.push(value);\n }\n }\n\n /** Indicate that we not waiting for more values - The async iterator will be done */\n close(): void {\n while (this._settlers.length > 0) {\n const settler = this._settlers.shift();\n settler.resolve({done: true});\n }\n this._closed = true;\n }\n\n // ITERATOR IMPLEMENTATION\n\n /** @returns a Promise for an IteratorResult */\n next(): Promise<IteratorResult<T, any>> {\n // If values in queue, yield the first value\n if (this._values.length > 0) {\n const value = this._values.shift();\n if (value instanceof Error) {\n return Promise.reject(value);\n }\n return Promise.resolve({done: false, value});\n }\n\n // If queue is closed, the iterator is done\n if (this._closed) {\n if (this._settlers.length > 0) {\n throw new Error('Illegal internal state');\n }\n return Promise.resolve({done: true, value: undefined});\n }\n\n // Yield a promise that waits for new values to be enqueued\n return new Promise((resolve, reject) => {\n this._settlers.push({resolve, reject});\n });\n }\n}\n","export function getFirstCharacters(data, length = 5): string {\n if (typeof data === 'string') {\n return data.slice(0, length);\n } else if (ArrayBuffer.isView(data)) {\n // Typed Arrays can have offsets into underlying buffer\n return getMagicString(data.buffer, data.byteOffset, length);\n } else if (data instanceof ArrayBuffer) {\n const byteOffset = 0;\n return getMagicString(data, byteOffset, length);\n }\n return '';\n}\n\nexport function getMagicString(\n arrayBuffer: ArrayBuffer,\n byteOffset: number,\n length: number\n): string {\n if (arrayBuffer.byteLength <= byteOffset + length) {\n return '';\n }\n const dataView = new DataView(arrayBuffer);\n let magic = '';\n for (let i = 0; i < length; i++) {\n magic += String.fromCharCode(dataView.getUint8(byteOffset + i));\n }\n return magic;\n}\n","import {TypedArray} from '../../types';\nimport * as node from './buffer-utils';\n\n/**\n * Convert an object to an array buffer\n */\nexport function toArrayBuffer(data: any): ArrayBuffer {\n // Note: Should be called first, Buffers can trigger other detections below\n if (node.isBuffer(data)) {\n // TODO - per docs we should just be able to call buffer.buffer, but there are issues\n data = node.bufferToArrayBuffer(data);\n }\n\n if (data instanceof ArrayBuffer) {\n return data;\n }\n\n // Careful - Node Buffers look like Uint8Arrays (keep after isBuffer)\n if (ArrayBuffer.isView(data)) {\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);\n }\n\n if (typeof data === 'string') {\n const text = data;\n const uint8Array = new TextEncoder().encode(text);\n return uint8Array.buffer;\n }\n\n // HACK to support Blob polyfill\n if (data && typeof data === 'object' && data._toArrayBuffer) {\n return data._toArrayBuffer();\n }\n\n throw new Error('toArrayBuffer');\n}\n\n/**\n * compare two binary arrays for equality\n * @param {ArrayBuffer} a\n * @param {ArrayBuffer} b\n * @param {number} byteLength\n */\nexport function compareArrayBuffers(\n arrayBuffer1: ArrayBuffer,\n arrayBuffer2: ArrayBuffer,\n byteLength?: number\n): boolean {\n byteLength = byteLength || arrayBuffer1.byteLength;\n if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {\n return false;\n }\n const array1 = new Uint8Array(arrayBuffer1);\n const array2 = new Uint8Array(arrayBuffer2);\n for (let i = 0; i < array1.length; ++i) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Concatenate a sequence of ArrayBuffers\n * @return A concatenated ArrayBuffer\n */\nexport function concatenateArrayBuffers(...sources: (ArrayBuffer | Uint8Array)[]): ArrayBuffer {\n // Make sure all inputs are wrapped in typed arrays\n const sourceArrays = sources.map((source2) =>\n source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2\n );\n\n // Get length of all inputs\n const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);\n\n // Allocate array with space for all inputs\n const result = new Uint8Array(byteLength);\n\n // Copy the subarrays\n let offset = 0;\n for (const sourceArray of sourceArrays) {\n result.set(sourceArray, offset);\n offset += sourceArray.byteLength;\n }\n\n // We work with ArrayBuffers, discard the typed array wrapper\n return result.buffer;\n}\n\n/**\n * Concatenate arbitrary count of typed arrays\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays\n * @param {...*} arrays - list of arrays. All arrays should be the same type\n * @return A concatenated TypedArray\n */\nexport function concatenateTypedArrays<T>(...typedArrays: T[]): T {\n // @ts-ignore\n const arrays = typedArrays as TypedArray[];\n // @ts-ignore\n const TypedArrayConstructor = (arrays && arrays.length > 1 && arrays[0].constructor) || null;\n if (!TypedArrayConstructor) {\n throw new Error(\n '\"concatenateTypedArrays\" - incorrect quantity of arguments or arguments have incompatible data types'\n );\n }\n\n const sumLength = arrays.reduce((acc, value) => acc + value.length, 0);\n // @ts-ignore typescript does not like dynamic constructors\n const result = new TypedArrayConstructor(sumLength);\n let offset = 0;\n for (const array of arrays) {\n result.set(array, offset);\n offset += array.length;\n }\n return result;\n}\n\n/**\n * Copy a view of an ArrayBuffer into new ArrayBuffer with byteOffset = 0\n * @param arrayBuffer\n * @param byteOffset\n * @param byteLength\n */\nexport function sliceArrayBuffer(\n arrayBuffer: ArrayBuffer,\n byteOffset: number,\n byteLength?: number\n): ArrayBuffer {\n const subArray =\n byteLength !== undefined\n ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength)\n : new Uint8Array(arrayBuffer).subarray(byteOffset);\n const arrayCopy = new Uint8Array(subArray);\n return arrayCopy.buffer;\n}\n","import * as node from '../node/buffer';\n\n/**\n * Check for Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n */\nexport function isBuffer(value: any): boolean {\n return value && typeof value === 'object' && value.isBuffer;\n}\n\n/**\n * Converts to Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n * @todo better data type\n */\nexport function toBuffer(data: any): Buffer {\n return node.toBuffer ? node.toBuffer(data) : data;\n}\n\n/**\n * Converts Node.js `Buffer` to `ArrayBuffer` (without triggering bundler to include Buffer polyfill on browser)\n * @todo better data type\n */\nexport function bufferToArrayBuffer(data: any): ArrayBuffer {\n if (node.toArrayBuffer) {\n // TODO - per docs we should just be able to call buffer.buffer, but there are issues\n return node.toArrayBuffer(data);\n }\n return data;\n}\n","import {assert} from '../env-utils/assert';\n\n/**\n * Calculate new size of an arrayBuffer to be aligned to an n-byte boundary\n * This function increases `byteLength` by the minimum delta,\n * allowing the total length to be divided by `padding`\n * @param byteLength\n * @param padding\n */\nexport function padToNBytes(byteLength: number, padding: number): number {\n assert(byteLength >= 0); // `Incorrect 'byteLength' value: ${byteLength}`\n assert(padding > 0); // `Incorrect 'padding' value: ${padding}`\n return (byteLength + (padding - 1)) & ~(padding - 1);\n}\n\n/**\n * Creates a new Uint8Array based on two different ArrayBuffers\n * @param targetBuffer The first buffer.\n * @param sourceBuffer The second buffer.\n * @return The new ArrayBuffer created out of the two.\n */\nexport function copyArrayBuffer(\n targetBuffer: ArrayBuffer,\n sourceBuffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number = sourceBuffer.byteLength\n): ArrayBuffer {\n const targetArray = new Uint8Array(targetBuffer, byteOffset, byteLength);\n const sourceArray = new Uint8Array(sourceBuffer);\n targetArray.set(sourceArray);\n return targetBuffer;\n}\n\n/**\n * Copy from source to target at the targetOffset\n *\n * @param source - The data to copy\n * @param target - The destination to copy data into\n * @param targetOffset - The start offset into target to place the copied data\n * @returns the new offset taking into account proper padding\n */\nexport function copyToArray(source: ArrayBuffer | any, target: any, targetOffset: number): number {\n let sourceArray;\n\n if (source instanceof ArrayBuffer) {\n sourceArray = new Uint8Array(source);\n } else {\n // Pack buffer onto the big target array\n //\n // 'source.data.buffer' could be a view onto a larger buffer.\n // We MUST use this constructor to ensure the byteOffset and byteLength is\n // set to correct values from 'source.data' and not the underlying\n // buffer for target.set() to work properly.\n const srcByteOffset = source.byteOffset;\n const srcByteLength = source.byteLength;\n // In gltf parser it is set as \"arrayBuffer\" instead of \"buffer\"\n // https://github.com/visgl/loaders.gl/blob/1e3a82a0a65d7b6a67b1e60633453e5edda2960a/modules/gltf/src/lib/parse-gltf.js#L85\n sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);\n }\n\n // Pack buffer onto the big target array\n target.set(sourceArray, targetOffset);\n\n return targetOffset + padToNBytes(sourceArray.byteLength, 4);\n}\n","/* eslint-disable */\n// @ts-nocheck\nconst env = {};\n\nexport const EVENTS = [\n 'value',\n 'string',\n 'key',\n 'openobject',\n 'closeobject',\n 'openarray',\n 'closearray',\n 'error',\n 'end',\n 'ready'\n];\n\n// Removes the MAX_BUFFER_LENGTH, originally set to 64 * 1024\nconst MAX_BUFFER_LENGTH = Number.MAX_SAFE_INTEGER;\nconst DEBUG = env.CDEBUG === 'debug';\n\nconst buffers = {\n textNode: undefined,\n numberNode: ''\n};\n\nlet S = 0;\n\nconst STATE = {\n BEGIN: S++,\n VALUE: S++, // general stuff\n OPEN_OBJECT: S++, // {\n CLOSE_OBJECT: S++, // }\n OPEN_ARRAY: S++, // [\n CLOSE_ARRAY: S++, // ]\n TEXT_ESCAPE: S++, // \\ stuff\n STRING: S++, // \"\"\n BACKSLASH: S++,\n END: S++, // No more stack\n OPEN_KEY: S++, // , \"a\"\n CLOSE_KEY: S++, // :\n TRUE: S++, // r\n TRUE2: S++, // u\n TRUE3: S++, // e\n FALSE: S++, // a\n FALSE2: S++, // l\n FALSE3: S++, // s\n FALSE4: S++, // e\n NULL: S++, // u\n NULL2: S++, // l\n NULL3: S++, // l\n NUMBER_DECIMAL_POINT: S++, // .\n NUMBER_DIGIT: S++ // [0-9]\n};\n\nfor (var s_ in STATE) STATE[STATE[s_]] = s_;\n\n// switcharoo\nS = STATE;\n\nconst Char = {\n tab: 0x09, // \\t\n lineFeed: 0x0a, // \\n\n carriageReturn: 0x0d, // \\r\n space: 0x20, // \" \"\n\n doubleQuote: 0x22, // \"\n plus: 0x2b, // +\n comma: 0x2c, // ,\n minus: 0x2d, // -\n period: 0x2e, // .\n\n _0: 0x30, // 0\n _9: 0x39, // 9\n\n colon: 0x3a, // :\n\n E: 0x45, // E\n\n openBracket: 0x5b, // [\n backslash: 0x5c, // \\\n closeBracket: 0x5d, // ]\n\n a: 0x61, // a\n b: 0x62, // b\n e: 0x65, // e\n f: 0x66, // f\n l: 0x6c, // l\n n: 0x6e, // n\n r: 0x72, // r\n s: 0x73, // s\n t: 0x74, // t\n u: 0x75, // u\n\n openBrace: 0x7b, // {\n closeBrace: 0x7d // }\n};\n\nfunction checkBufferLength(parser) {\n const maxAllowed = Math.max(MAX_BUFFER_LENGTH, 10);\n let maxActual = 0;\n\n for (var buffer in buffers) {\n var len = parser[buffer] === undefined ? 0 : parser[buffer].length;\n if (len > maxAllowed) {\n switch (buffer) {\n case 'text':\n closeText(parser);\n break;\n\n default:\n error(parser, 'Max buffer length exceeded: ' + buffer);\n }\n }\n maxActual = Math.max(maxActual, len);\n }\n parser.bufferCheckPosition = MAX_BUFFER_LENGTH - maxActual + parser.position;\n}\n\nvar stringTokenPattern = /[\\\\\"\\n]/g;\n\nexport default class ClarinetParser {\n constructor(options = {}) {\n this._initialize(options);\n }\n\n _initialize(options) {\n this._clearBuffers(this);\n this.bufferCheckPosition = MAX_BUFFER_LENGTH;\n this.q = '';\n this.c = '';\n this.p = '';\n this.options = options || {};\n this.closed = false;\n this.closedRoot = false;\n this.sawRoot = false;\n this.tag = null;\n this.error = null;\n this.state = S.BEGIN;\n this.stack = new Array();\n // mostly just for error reporting\n this.position = this.column = 0;\n this.line = 1;\n this.slashed = false;\n this.unicodeI = 0;\n this.unicodeS = null;\n this.depth = 0;\n\n // install callbacks\n if ('onready' in options) {\n this.onready = options.onready;\n }\n\n if ('onopenobject' in options) {\n this.onopenobject = options.onopenobject;\n }\n\n if ('onkey' in options) {\n this.onkey = options.onkey;\n }\n\n if ('oncloseobject' in options) {\n this.oncloseobject = options.oncloseobject;\n }\n\n if ('onopenarray' in options) {\n this.onopenarray = options.onopenarray;\n }\n\n if ('onclosearray' in options) {\n this.onclosearray = options.onclosearray;\n }\n\n if ('onvalue' in options) {\n this.onvalue = options.onvalue;\n }\n\n if ('onerror' in options) {\n this.onerror = options.onerror;\n }\n\n if ('onend' in options) {\n this.onend = options.onend;\n }\n\n if ('onchunkparsed' in options) {\n this.onchunkparsed = options.onchunkparsed;\n }\n\n emit(this, 'onready');\n }\n\n _clearBuffers() {\n for (var buffer in buffers) {\n this[buffer] = buffers[buffer];\n }\n }\n\n end() {\n if (this.state !== S.VALUE || this.depth !== 0) error(this, 'Unexpected end');\n\n closeValue(this);\n this.c = '';\n this.closed = true;\n emit(this, 'onend');\n this._initialize(this.options);\n return this;\n }\n\n resume() {\n this.error = null;\n return this;\n }\n\n close() {\n return this.write(null);\n }\n\n write(chunk) {\n if (this.error) {\n throw this.error;\n }\n if (this.closed) {\n return error(this, 'Cannot write after close. Assign an onready handler.');\n }\n if (chunk === null) {\n return this.end();\n }\n var i = 0,\n c = chunk.charCodeAt(0),\n p = this.p;\n if (DEBUG) console.log('write -> [' + chunk + ']');\n while (c) {\n p = c;\n this.c = c = chunk.charCodeAt(i++);\n // if chunk doesnt have next, like streaming char by char\n // this way we need to check if previous is really previous\n // if not we need to reset to what the this says is the previous\n // from buffer\n if (p !== c) {\n this.p = p;\n } else {\n p = this.p;\n }\n\n if (!c) break;\n\n if (DEBUG) console.log(i, c, STATE[this.state]);\n this.position++;\n if (c === Char.lineFeed) {\n this.line++;\n this.column = 0;\n } else this.column++;\n\n switch (this.state) {\n case S.BEGIN:\n if (c === Char.openBrace) this.state = S.OPEN_OBJECT;\n else if (c === Char.openBracket) this.state = S.OPEN_ARRAY;\n else if (!isWhitespace(c)) {\n error(this, 'Non-whitespace before {[.');\n }\n continue;\n\n case S.OPEN_KEY:\n case S.OPEN_OBJECT:\n if (isWhitespace(c)) continue;\n if (this.state === S.OPEN_KEY) this.stack.push(S.CLOSE_KEY);\n else {\n if (c === Char.closeBrace) {\n emit(this, 'onopenobject');\n this.depth++;\n emit(this, 'oncloseobject');\n this.depth--;\n this.state = this.stack.pop() || S.VALUE;\n continue;\n } else this.stack.push(S.CLOSE_OBJECT);\n }\n if (c === Char.doubleQuote) this.state = S.STRING;\n else error(this, 'Malformed object key should start with \"');\n continue;\n\n case S.CLOSE_KEY:\n case S.CLOSE_OBJECT:\n if (isWhitespace(c)) continue;\n var event = this.state === S.CLOSE_KEY ? 'key' : 'object';\n if (c === Char.colon) {\n if (this.state === S.CLOSE_OBJECT) {\n this.stack.push(S.CLOSE_OBJECT);\n closeValue(this, 'onopenobject');\n this.depth++;\n } else closeValue(this, 'onkey');\n this.state = S.VALUE;\n } else if (c === Char.closeBrace) {\n emitNode(this, 'oncloseobject');\n this.depth--;\n this.state = this.stack.pop() || S.VALUE;\n } else if (c === Char.comma) {\n if (this.state === S.CLOSE_OBJECT) this.stack.push(S.CLOSE_OBJECT);\n closeValue(this);\n this.state = S.OPEN_KEY;\n } else error(this, 'Bad object');\n continue;\n\n case S.OPEN_ARRAY: // after an array there always a value\n case S.VALUE:\n if (isWhitespace(c)) continue;\n if (this.state === S.OPEN_ARRAY) {\n emit(this, 'onopenarray');\n this.depth++;\n this.state = S.VALUE;\n if (c === Char.closeBracket) {\n emit(this, 'onclosearray');\n this.depth--;\n this.state = this.stack.pop() || S.VALUE;\n continue;\n } else {\n this.stack.push(S.CLOSE_ARRAY);\n }\n }\n if (c === Char.doubleQuote) this.state = S.STRING;\n else if (c === Char.openBrace) this.state = S.OPEN_OBJECT;\n else if (c === Char.openBracket) this.state = S.OPEN_ARRAY;\n else if (c === Char.t) this.state = S.TRUE;\n else if (c === Char.f) this.state = S.FALSE;\n else if (c === Char.n) this.state = S.NULL;\n else if (c === Char.minus) {\n // keep and continue\n this.numberNode += '-';\n } else if (Char._0 <= c && c <= Char._9) {\n this.numberNode += String.fromCharCode(c);\n this.state = S.NUMBER_DIGIT;\n } else error(this, 'Bad value');\n continue;\n\n case S.CLOSE_ARRAY:\n if (c === Char.comma) {\n this.stack.push(S.CLOSE_ARRAY);\n closeValue(this, 'onvalue');\n this.state = S.VALUE;\n } else if (c === Char.closeBracket) {\n emitNode(this, 'onclosearray');\n this.depth--;\n this.state = this.stack.pop() || S.VALUE;\n } else if (isWhitespace(c)) continue;\n else error(this, 'Bad array');\n continue;\n\n case S.STRING:\n if (this.textNode === undefined) {\n this.textNode = '';\n }\n\n // thanks thejh, this is an about 50% performance improvement.\n var starti = i - 1,\n slashed = this.slashed,\n unicodeI = this.unicodeI;\n STRING_BIGLOOP: while (true) {\n if (DEBUG) console.log(i, c, STATE[this.state], slashed);\n // zero means \"no unicode active\". 1-4 mean \"parse some more\". end after 4.\n while (unicodeI > 0) {\n this.unicodeS += String.fromCharCode(c);\n c = chunk.charCodeAt(i++);\n this.position++;\n if (unicodeI === 4) {\n // TODO this might be slow? well, probably not used too often anyway\n this.textNode += String.fromCharCode(parseInt(this.unicodeS, 16));\n unicodeI = 0;\n starti = i - 1;\n } else {\n unicodeI++;\n }\n // we can just break here: no stuff we skipped that still has to be sliced out or so\n if (!c) break STRING_BIGLOOP;\n }\n if (c === Char.doubleQuote && !slashed) {\n this.state = this.stack.pop() || S.VALUE;\n this.textNode += chunk.substring(starti, i - 1);\n this.position += i - 1 - starti;\n break;\n }\n if (c === Char.backslash && !slashed) {\n slashed = true;\n this.textNode += chunk.substring(starti, i - 1);\n this.position += i - 1 - starti;\n c = chunk.charCodeAt(i++);\n this.position++;\n if (!c) break;\n }\n if (slashed) {\n slashed = false;\n if (c === Char.n) {\n this.textNode += '\\n';\n } else if (c === Char.r) {\n this.textNode += '\\r';\n } else if (c === Char.t) {\n this.textNode += '\\t';\n } else if (c === Char.f) {\n this.textNode += '\\f';\n } else if (c === Char.b) {\n this.textNode += '\\b';\n } else if (c === Char.u) {\n // \\uxxxx. meh!\n unicodeI = 1;\n this.unicodeS = '';\n } else {\n this.textNode += String.fromCharCode(c);\n }\n c = chunk.charCodeAt(i++);\n this.position++;\n starti = i - 1;\n if (!c) break;\n else continue;\n }\n\n stringTokenPattern.lastIndex = i;\n var reResult = stringTokenPattern.exec(chunk);\n if (reResult === null) {\n i = chunk.length + 1;\n this.textNode += chunk.substring(starti, i - 1);\n this.position += i - 1 - starti;\n break;\n }\n i = reResult.index + 1;\n c = chunk.charCodeAt(reResult.index);\n if (!c) {\n this.textNode += chunk.substring(starti, i - 1);\n this.position += i - 1 - starti;\n break;\n }\n }\n this.slashed = slashed;\n this.unicodeI = unicodeI;\n continue;\n\n case S.TRUE:\n if (c === Char.r) this.state = S.TRUE2;\n else error(this, 'Invalid true started with t' + c);\n continue;\n\n case S.TRUE2:\n if (c === Char.u) this.state = S.TRUE3;\n else error(this, 'Invalid true started with tr' + c);\n continue;\n\n case S.TRUE3:\n if (c === Char.e) {\n emit(this, 'onvalue', true);\n this.state = this.stack.pop() || S.VALUE;\n } else error(this, 'Invalid true started with tru' + c);\n continue;\n\n case S.FALSE:\n if (c === Char.a) this.state = S.FALSE2;\n else error(this, 'Invalid false started with f' + c);\n continue;\n\n case S.FALSE2:\n if (c === Char.l) this.state = S.FALSE3;\n else error(this, 'Invalid false started with fa' + c);\n continue;\n\n case S.FALSE3:\n if (c === Char.s) this.state = S.FALSE4;\n else error(this, 'Invalid false started with fal' + c);\n continue;\n\n case S.FALSE4:\n if (c === Char.e) {\n emit(this, 'onvalue', false);\n this.state = this.stack.pop() || S.VALUE;\n } else error(this, 'Invalid false started with fals' + c);\n continue;\n\n case S.NULL:\n if (c === Char.u) this.state = S.NULL2;\n else error(this, 'Invalid null started with n' + c);\n continue;\n\n case S.NULL2:\n if (c === Char.l) this.state = S.NULL3;\n else error(this, 'Invalid null started with nu' + c);\n continue;\n\n case S.NULL3:\n if (c === Char.l) {\n emit(this, 'onvalue', null);\n this.state = this.stack.pop() || S.VALUE;\n } else error(this, 'Invalid null started with nul' + c);\n continue;\n\n case S.NUMBER_DECIMAL_POINT:\n if (c === Char.period) {\n this.numberNode += '.';\n this.state = S.NUMBER_DIGIT;\n } else error(this, 'Leading zero not followed by .');\n continue;\n\n case S.NUMBER_DIGIT:\n if (Char._0 <= c && c <= Char._9) this.numberNode += String.fromCharCode(c);\n else if (c === Char.period) {\n if (this.numberNode.indexOf('.') !== -1) error(this, 'Invalid number has two dots');\n this.numberNode += '.';\n } else if (c === Char.e || c === Char.E) {\n if (this.numberNode.indexOf('e') !== -1 || this.numberNode.indexOf('E') !== -1)\n error(this, 'Invalid number has two exponential');\n this.numberNode += 'e';\n } else if (c === Char.plus || c === Char.minus) {\n if (!(p === Char.e || p === Char.E)) error(this, 'Invalid symbol in number');\n this.numberNode += String.fromCharCode(c);\n } else {\n closeNumber(this);\n i--; // go back one\n this.state = this.stack.pop() || S.VALUE;\n }\n continue;\n\n default:\n error(this, 'Unknown state: ' + this.state);\n }\n }\n if (this.position >= this.bufferCheckPosition) {\n checkBufferLength(this);\n }\n\n emit(this, 'onchunkparsed');\n\n return this;\n }\n}\n\nfunction emit(parser, event, data) {\n if (DEBUG) {\n console.log('-- emit', event, data);\n }\n if (parser[event]) {\n parser[event](data, parser);\n }\n}\n\nfunction emitNode(parser, event, data) {\n closeValue(parser);\n emit(parser, event, data);\n}\n\nfunction closeValue(parser, event) {\n parser.textNode = textopts(parser.options, parser.textNode);\n if (parser.textNode !== undefined) {\n emit(parser, event ? event : 'onvalue', parser.textNode);\n }\n parser.textNode = undefined;\n}\n\nfunction closeNumber(parser) {\n if (parser.numberNode) emit(parser, 'onvalue', parseFloat(parser.numberNode));\n parser.numberNode = '';\n}\n\nfunction textopts(opt, text) {\n if (text === undefined) {\n return text;\n }\n if (opt.trim) text = text.trim();\n if (opt.normalize) text = text.replace(/\\s+/g, ' ');\n return text;\n}\n\nfunction error(parser, er) {\n closeValue(parser);\n er += '\\nLine: ' + parser.line + '\\nColumn: ' + parser.column + '\\nChar: ' + parser.c;\n er = new Error(er);\n parser.error = er;\n emit(parser, 'onerror', er);\n return parser;\n}\n\nfunction isWhitespace(c) {\n return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab;\n}\n","// @ts-nocheck\nconst moduleExports = require('./index');\nconst _global = typeof window === 'undefined' ? global : window;\n_global.loaders = _global.loaders || {};\nmodule.exports = Object.assign(_global.loaders, moduleExports);\n","export type {JSONLoaderOptions} from './json-loader';\nexport {JSONLoader} from './json-loader';\n\n// EXPERIMENTAL EXPORTS - WARNING: MAY BE REMOVED WIHTOUT NOTICE IN FUTURE RELEASES\nexport type {GeoJSONLoaderOptions as _GeoJSONLoaderOptions} from './geojson-loader';\nexport {\n GeoJSONLoader as _GeoJSONLoader,\n GeoJSONWorkerLoader as _GeoJSONWorkerLoader\n} from './geojson-loader';\n\nexport {default as _JSONPath} from './lib/jsonpath/jsonpath';\nexport {default as _ClarinetParser} from './lib/clarinet/clarinet';\n","import type {Batch} from '@loaders.gl/schema';\nimport type {LoaderWithParser, LoaderOptions} from '@loaders.gl/loader-utils';\nimport parseJSONSync from './lib/parse-json';\nimport parseJSONInBatches from './lib/parse-json-in-batches';\n\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n\n/**\n * @param table -\n * @param jsonpaths -\n */\nexport type JSONLoaderOptions = LoaderOptions & {\n json?: {\n shape?: 'row-table';\n table?: false;\n jsonpaths?: string[];\n };\n};\n\nconst DEFAULT_JSON_LOADER_OPTIONS = {\n json: {\n shape: 'row-table',\n table: false,\n jsonpaths: []\n // batchSize: 'auto'\n }\n};\n\nexport const JSONLoader: LoaderWithParser = {\n name: 'JSON',\n id: 'json',\n module: 'json',\n version: VERSION,\n extensions: ['json', 'geojson'],\n mimeTypes: ['application/json'],\n // TODO - support various line based JSON formats\n /*\n extensions: {\n json: null,\n jsonl: {stream: true},\n ndjson: {stream: true}\n },\n mimeTypes: {\n 'application/json': null,\n 'application/json-seq': {stream: true},\n 'application/x-ndjson': {stream: true}\n },\n */\n category: 'table',\n text: true,\n parse,\n parseTextSync,\n parseInBatches,\n options: DEFAULT_JSON_LOADER_OPTIONS\n};\n\nasync function parse(arrayBuffer: ArrayBuffer, options?: JSONLoaderOptions) {\n return parseTextSync(new TextDecoder().decode(arrayBuffer), options);\n}\n\nfunction parseTextSync(text: string, options?: JSONLoaderOptions) {\n const jsonOptions = {...options, json: {...DEFAULT_JSON_LOADER_OPTIONS.json, ...options?.json}};\n return parseJSONSync(text, jsonOptions as JSONLoaderOptions);\n}\n\nfunction parseInBatches(\n asyncIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>,\n options?: JSONLoaderOptions\n): AsyncIterable<Batch> {\n const jsonOptions = {...options, json: {...DEFAULT_JSON_LOADER_OPTIONS.json, ...options?.json}};\n return parseJSONInBatches(asyncIterator, jsonOptions as JSONLoaderOptions);\n}\n","// COMMON CATEGORY\nexport type {TypedArray, NumberArray, AnyArray} from './types';\n\nexport type {Batch} from './category/common';\n\n// TABLE CATEGORY TYPES\n\nexport type {\n Table,\n ArrayRowTable,\n ObjectRowTable,\n ColumnarTable,\n ArrowTable\n} from './category/table';\nexport type {\n TableBatch,\n RowArrayTableBatch,\n RowObjectTableBatch,\n ColumnarTableBatch,\n ArrowTableBatch\n} from './category/table';\n\n// TABLE CATEGORY UTILS\nexport {default as TableBatchBuilder} from './lib/table/table-batch-builder';\nexport type {TableBatchAggregator} from './lib/table/table-batch-aggregator';\nexport {default as RowTableBatchAggregator} from './lib/table/row-table-batch-aggregator';\nexport {default as ColumnarTableBatchAggregator} from './lib/table/columnar-table-batch-aggregator';\n\nexport {convertToObjectRow, convertToArrayRow} from './lib/utils/row-utils';\n\n// MESH CATEGORY\nexport type {MeshTable, MeshArrowTable, Mesh, MeshAttribute} from './category/mesh';\n\n// MESH CATEGORY UTILS\nexport type {Attributes as _Attributes} from './category/mesh/mesh-utils';\nexport {getMeshSize, getMeshBoundingBox} from './category/mesh/mesh-utils';\n\n// TYPES\n// GIS CATEGORY - GEOJSON\nexport type {GeoJSON, Feature, Geometry, Position, GeoJsonProperties} from './category/gis';\nexport type {\n Point,\n MultiPoint,\n LineString,\n MultiLineString,\n Polygon,\n MultiPolygon\n} from './category/gis';\n\n// GIS CATEGORY - BINARY\nexport type {\n BinaryGeometryType,\n BinaryGeometry,\n BinaryPointGeometry,\n BinaryLineGeometry,\n BinaryPolygonGeometry,\n BinaryAttribute\n} from './category/gis';\nexport type {\n BinaryFeatures,\n BinaryPointFeatures,\n BinaryLineFeatures,\n BinaryPolygonFeatures\n} from './category/gis';\n\n// SCHEMA\nexport {\n Schema,\n Field,\n DataType,\n Null,\n Binary,\n Bool,\n Int,\n Int8,\n Int16,\n Int32,\n Int64,\n Uint8,\n Uint16,\n Uint32,\n Uint64,\n Float,\n Float16,\n Float32,\n Float64,\n Utf8,\n Date,\n DateDay,\n DateMillisecond,\n Time,\n TimeMillisecond,\n TimeSecond,\n Timestamp,\n TimestampSecond,\n TimestampMillisecond,\n TimestampMicrosecond,\n TimestampNanosecond,\n Interval,\n IntervalDayTime,\n IntervalYearMonth,\n FixedSizeList\n} from './lib/schema';\n\n// SCHEMA UTILS\nexport {deduceTableSchema} from './lib/schema-utils/deduce-table-schema';\nexport {getTypeInfo} from './lib/schema-utils/get-type-info';\nexport {getArrowTypeFromTypedArray} from './lib/schema-utils/type-utils';\n\n// EXPERIMENTAL APIs\nexport {default as AsyncQueue} from './lib/utils/async-queue';\n","import type {Schema} from '../schema';\nimport type {TableBatch} from '../../category/table';\nimport type {TableBatchAggregator, TableBatchConstructor} from './table-batch-aggregator';\nimport BaseTableBatchAggregator from './base-table-batch-aggregator';\nimport RowTableBatchAggregator from './row-table-batch-aggregator';\nimport ColumnarTableBatchAggregator from './columnar-table-batch-aggregator';\n\n// TODO define interface instead\ntype TableBatchBuilderOptions = {\n shape: 'row-table' | 'array-row-table' | 'object-row-table' | 'columnar-table' | 'arrow-table';\n batchSize?: number | 'auto';\n batchDebounceMs?: number;\n limit: number;\n _limitMB: number;\n};\n\ntype GetBatchOptions = {\n bytesUsed?: number;\n [key: string]: any;\n};\n\nconst DEFAULT_OPTIONS: Required<TableBatchBuilderOptions> = {\n shape: 'array-row-table',\n batchSize: 'auto',\n batchDebounceMs: 0,\n limit: 0,\n _limitMB: 0\n};\n\nconst ERR_MESSAGE = 'TableBatchBuilder';\n\n/** Incrementally builds batches from a stream of rows */\nexport default class TableBatchBuilder {\n schema: Schema;\n options: Required<TableBatchBuilderOptions>;\n\n private aggregator: TableBatchAggregator | null = null;\n private batchCount: number = 0;\n private bytesUsed: number = 0;\n private isChunkComplete: boolean = false;\n private lastBatchEmittedMs: number = Date.now();\n private totalLength: number = 0;\n private totalBytes: number = 0;\n private rowBytes: number = 0;\n\n static ArrowBatch?: TableBatchConstructor;\n\n constructor(schema: Schema, options?: TableBatchBuilderOptions) {\n this.schema = schema;\n this.options = {...DEFAULT_OPTIONS, ...options};\n }\n\n limitReached(): boolean {\n if (Boolean(this.options?.limit) && this.totalLength >= this.options.limit) {\n return true;\n }\n if (Boolean(this.options?._limitMB) && this.totalBytes / 1e6 >= this.options._limitMB) {\n return true;\n }\n return false;\n }\n\n /** @deprecated Use addArrayRow or addObjectRow */\n addRow(row: any[] | {[columnName: string]: any}): void {\n if (this.limitReached()) {\n return;\n }\n this.totalLength++;\n this.rowBytes = this.rowBytes || this._estimateRowMB(row);\n this.totalBytes += this.rowBytes;\n if (Array.isArray(row)) {\n this.addArrayRow(row);\n } else {\n this.addObjectRow(row);\n }\n }\n\n /** Add one row to the batch */\n protected addArrayRow(row: any[]) {\n if (!this.aggregator) {\n const TableBatchType = this._getTableBatchType();\n this.aggregator = new TableBatchType(this.schema, this.options);\n }\n this.aggregator.addArrayRow(row);\n }\n\n /** Add one row to the batch */\n protected addObjectRow(row: {[columnName: string]: any}): void {\n if (!this.aggregator) {\n const TableBatchType = this._getTableBatchType();\n this.aggregator = new TableBatchType(this.schema, this.options);\n }\n this.aggregator.addObjectRow(row);\n }\n\n /** Mark an incoming raw memory chunk has completed */\n chunkComplete(chunk: ArrayBuffer | string): void {\n if (chunk instanceof ArrayBuffer) {\n this.bytesUsed += chunk.byteLength;\n }\n if (typeof chunk === 'string') {\n this.bytesUsed += chunk.length;\n }\n this.isChunkComplete = true;\n }\n\n getFullBatch(options?: GetBatchOptions): TableBatch | null {\n return this._isFull() ? this._getBatch(options) : null;\n }\n\n getFinalBatch(options?: GetBatchOptions): TableBatch | null {\n return this._getBatch(options);\n }\n\n // INTERNAL\n\n _estimateRowMB(row) {\n return Array.isArray(row) ? row.length * 8 : Object.keys(row).length * 8;\n }\n\n private _isFull(): boolean {\n // No batch, not ready\n if (!this.aggregator || this.aggregator.rowCount() === 0) {\n return false;\n }\n\n // if batchSize === 'auto' we wait for chunk to complete\n // if batchSize === number, ensure we have enough rows\n if (this.options.batchSize === 'auto') {\n if (!this.isChunkComplete) {\n return false;\n }\n } else if (this.options.batchSize > this.aggregator.rowCount()) {\n return false;\n }\n\n // Debounce batches\n if (this.options.batchDebounceMs > Date.now() - this.lastBatchEmittedMs) {\n return false;\n }\n\n // Emit batch\n this.isChunkComplete = false;\n this.lastBatchEmittedMs = Date.now();\n return true;\n }\n\n /**\n * bytesUsed can be set via chunkComplete or via getBatch*\n */\n private _getBatch(options?: GetBatchOptions): TableBatch | null {\n if (!this.aggregator) {\n return null;\n }\n\n // TODO - this can overly increment bytes used?\n if (options?.bytesUsed) {\n this.bytesUsed = options.bytesUsed;\n }\n const normalizedBatch = this.aggregator.getBatch() as TableBatch;\n normalizedBatch.count = this.batchCount;\n normalizedBatch.bytesUsed = this.bytesUsed;\n Object.assign(normalizedBatch, options);\n\n this.batchCount++;\n this.aggregator = null;\n return normalizedBatch;\n }\n\n private _getTableBatchType(): TableBatchConstructor {\n switch (this.options.shape) {\n case 'row-table':\n return BaseTableBatchAggregator;\n case 'array-row-table':\n case 'object-row-table':\n return RowTableBatchAggregator;\n case 'columnar-table':\n return ColumnarTableBatchAggregator;\n case 'arrow-table':\n if (!TableBatchBuilder.ArrowBatch) {\n throw new Error(ERR_MESSAGE);\n }\n return TableBatchBuilder.ArrowBatch;\n default:\n throw new Error(ERR_MESSAGE);\n }\n }\n}\n","import type {Schema} from '../schema';\nimport type {TableBatch} from '../../category/table';\nimport {TableBatchAggregator, TableBatchOptions} from './table-batch-aggregator';\n\nconst DEFAULT_ROW_COUNT = 100;\n\nexport default class RowTableBatchAggregator implements TableBatchAggregator {\n schema: Schema;\n options: TableBatchOptions;\n\n length: number = 0;\n rows: any[] | null = null;\n cursor: number = 0;\n private _headers: string[] = [];\n\n constructor(schema: Schema, options: TableBatchOptions) {\n this.options = options;\n this.schema = schema;\n\n // schema is an array if there're no headers\n // object if there are headers\n if (!Array.isArray(schema)) {\n this._headers = [];\n for (const key in schema) {\n this._headers[schema[key].index] = schema[key].name;\n }\n }\n }\n\n rowCount(): number {\n return this.length;\n }\n\n addArrayRow(row: any[], cursor?: number): void {\n if (Number.isFinite(cursor)) {\n this.cursor = cursor as number;\n }\n\n this.rows = this.rows || new Array(DEFAULT_ROW_COUNT);\n this.rows[this.length] = row;\n this.length++;\n }\n\n addObjectRow(row: {[columnName: string]: any}, cursor?: number): void {\n if (Number.isFinite(cursor)) {\n this.cursor = cursor as number;\n }\n\n this.rows = this.rows || new Array(DEFAULT_ROW_COUNT);\n this.rows[this.length] = row;\n this.length++;\n }\n\n getBatch(): TableBatch | null {\n let rows = this.rows;\n if (!rows) {\n return null;\n }\n\n rows = rows.slice(0, this.length);\n this.rows = null;\n\n const batch: TableBatch = {\n shape: this.options.shape,\n batchType: 'data',\n data: rows,\n length: this.length,\n schema: this.schema,\n cursor: this.cursor\n };\n\n return batch;\n }\n}\n","// Mesh category utilities\n// TODO - move to mesh category module, or to math.gl/geometry module\nimport {TypedArray} from '../../types';\n\ntype Attribute = {\n size?: number;\n type?: number;\n normalized?: boolean;\n value: TypedArray;\n};\n\ntype TypedArrays = {[key: string]: TypedArray};\nexport type Attributes = {[key: string]: Attribute};\n\n/**\n * Holds an axis aligned bounding box\n * TODO - make sure AxisAlignedBoundingBox in math.gl/culling understands this format (or change this format)\n */\ntype BoundingBox = [[number, number, number], [number, number, number]];\n\n/**\n * Get number of vertices in mesh\n * @param attributes\n */\nexport function getMeshSize(attributes: TypedArrays): number {\n let size = 0;\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n if (ArrayBuffer.isView(attribute)) {\n // @ts-ignore DataView doesn't have BYTES_PER_ELEMENT\n size += attribute.byteLength * attribute.BYTES_PER_ELEMENT;\n }\n }\n return size;\n}\n\n/**\n * Get the (axis aligned) bounding box of a mesh\n * @param attributes\n * @returns array of two vectors representing the axis aligned bounding box\n */\n// eslint-disable-next-line complexity\nexport function getMeshBoundingBox(attributes: Attributes): BoundingBox {\n let minX = Infinity;\n let minY = Infinity;\n let minZ = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n let maxZ = -Infinity;\n\n const positions = attributes.POSITION ? attributes.POSITION.value : [];\n const len = positions && positions.length;\n\n for (let i = 0; i < len; i += 3) {\n const x = positions[i];\n const y = positions[i + 1];\n const z = positions[i + 2];\n\n minX = x < minX ? x : minX;\n minY = y < minY ? y : minY;\n minZ = z < minZ ? z : minZ;\n\n maxX = x > maxX ? x : maxX;\n maxY = y > maxY ? y : maxY;\n maxZ = z > maxZ ? z : maxZ;\n }\n return [\n [minX, minY, minZ],\n [maxX, maxY, maxZ]\n ];\n}\n","import {assert} from '../../utils/assert';\nimport Field from './field';\n\nexport type SchemaMetadata = Map<string, any>;\n\n/**\n * ArrowJS `Schema` API-compatible class for row-based tables (returned from `DataTable`)\n * https://loaders.gl/arrowjs/docs/api-reference/schema\n */\nexport default class Schema {\n fields: Field[];\n // TODO - Arrow just allows Map<string, string>\n metadata: SchemaMetadata;\n\n constructor(fields: Field[], metadata?: SchemaMetadata) {\n assert(Array.isArray(fields));\n checkNames(fields);\n // For kepler fields, create arrow compatible `Fields` that have kepler fields as `metadata`\n this.fields = fields;\n this.metadata = metadata || new Map();\n }\n\n // TODO - arrow only seems to compare fields, not metadata\n compareTo(other: Schema): boolean {\n if (this.metadata !== other.metadata) {\n return false;\n }\n if (this.fields.length !== other.fields.length) {\n return false;\n }\n for (let i = 0; i < this.fields.length; ++i) {\n if (!this.fields[i].compareTo(other.fields[i])) {\n return false;\n }\n }\n return true;\n }\n\n select(...columnNames: string[]): Schema {\n // Ensure column names reference valid fields\n const nameMap = Object.create(null);\n for (const name of columnNames) {\n nameMap[name] = true;\n }\n const selectedFields = this.fields.filter((field) => nameMap[field.name]);\n return new Schema(selectedFields, this.metadata);\n }\n\n selectAt(...columnIndices: number[]): Schema {\n // Ensure column indices reference valid fields\n const selectedFields = columnIndices.map((index) => this.fields[index]).filter(Boolean);\n return new Schema(selectedFields, this.metadata);\n }\n\n assign(schemaOrFields: Schema | Field[]): Schema {\n let fields: Field[];\n let metadata: SchemaMetadata = this.metadata;\n\n if (schemaOrFields instanceof Schema) {\n const otherSchema = schemaOrFields;\n fields = otherSchema.fields;\n metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);\n } else {\n fields = schemaOrFields;\n }\n\n // Create a merged list of fields, overwrite fields in place, new fields at end\n const fieldMap: {[key: string]: Field} = Object.create(null);\n\n for (const field of this.fields) {\n fieldMap[field.name] = field;\n }\n\n for (const field of fields) {\n fieldMap[field.name] = field;\n }\n\n const mergedFields = Object.values(fieldMap);\n\n return new Schema(mergedFields, metadata);\n }\n}\n\n// Warn if any duplicated field names\nfunction checkNames(fields) {\n const usedNames = {};\n for (const field of fields) {\n if (usedNames[field.name]) {\n // eslint-disable-next-line\n console.warn('Schema: duplicated field name', field.name, field);\n }\n usedNames[field.name] = true;\n }\n}\n\nfunction mergeMaps<T>(m1: T, m2: T): T {\n // @ts-ignore\n return new Map([...(m1 || new Map()), ...(m2 || new Map())]);\n}\n","// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\nexport function assert(condition: boolean, message?: string) {\n if (!condition) {\n throw new Error(message || 'loader assertion failed.');\n }\n}\n","import {DataType} from './type';\n\n/**\n * ArrowJS `Field` API-compatible class for row-based tables\n * https://loaders.gl/arrowjs/docs/api-reference/field\n * A field holds name, nullable, and metadata information about a table \"column\"\n * A Schema is essentially a list of fields\n */\nexport default class Field {\n name: string;\n type: DataType;\n nullable: boolean;\n metadata: Map<string, string>;\n\n constructor(\n name: string,\n type: DataType,\n nullable = false,\n metadata: Map<string, string> = new Map()\n ) {\n this.name = name;\n this.type = type;\n this.nullable = nullable;\n this.metadata = metadata;\n }\n\n get typeId(): number {\n return this.type && this.type.typeId;\n }\n\n clone(): Field {\n return new Field(this.name, this.type, this.nullable, this.metadata);\n }\n\n compareTo(other: this): boolean {\n return (\n this.name === other.name &&\n this.type === other.type &&\n this.nullable === other.nullable &&\n this.metadata === other.metadata\n );\n }\n\n toString(): string {\n return `${this.type}${this.nullable ? ', nullable' : ''}${\n this.metadata ? `, metadata: ${this.metadata}` : ''\n }`;\n }\n}\n","// This code is adapted from ArrowJS https://github.com/apache/arrow\n// under Apache license http://www.apache.org/licenses/LICENSE-2.0\n\nimport {Type} from './enum';\n\nimport Field from './field';\n\nexport {Type} from './enum';\n\nexport type TypedIntArray =\n | Int8Array\n | Uint8Array\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Int32Array\n | Uint32Array\n | Uint8ClampedArray;\n\nexport type TypedFloatArray = Float32Array | Float64Array;\n\nexport type TypedArray = TypedIntArray | TypedFloatArray;\n\nexport type AnyArrayType = Array<any> | TypedIntArray | TypedFloatArray;\n\nexport class DataType {\n static isNull(x: any): boolean {\n return x && x.typeId === Type.Null;\n }\n static isInt(x: any): boolean {\n return x && x.typeId === Type.Int;\n }\n static isFloat(x: any): boolean {\n return x && x.typeId === Type.Float;\n }\n static isBinary(x: any): boolean {\n return x && x.typeId === Type.Binary;\n }\n static isUtf8(x: any): boolean {\n return x && x.typeId === Type.Utf8;\n }\n static isBool(x: any): boolean {\n return x && x.typeId === Type.Bool;\n }\n static isDecimal(x: any): boolean {\n return x && x.typeId === Type.Decimal;\n }\n static isDate(x: any): boolean {\n return x && x.typeId === Type.Date;\n }\n static isTime(x: any): boolean {\n return x && x.typeId === Type.Time;\n }\n static isTimestamp(x: any): boolean {\n return x && x.typeId === Type.Timestamp;\n }\n static isInterval(x: any): boolean {\n return x && x.typeId === Type.Interval;\n }\n static isList(x: any): boolean {\n return x && x.typeId === Type.List;\n }\n static isStruct(x: any): boolean {\n return x && x.typeId === Type.Struct;\n }\n static isUnion(x: any): boolean {\n return x && x.typeId === Type.Union;\n }\n static isFixedSizeBinary(x: any): boolean {\n return x && x.typeId === Type.FixedSizeBinary;\n }\n static isFixedSizeList(x: any): boolean {\n return x && x.typeId === Type.FixedSizeList;\n }\n static isMap(x: any): boolean {\n return x && x.typeId === Type.Map;\n }\n static isDictionary(x: any): boolean {\n return x && x.typeId === Type.Dictionary;\n }\n\n get typeId(): Type {\n return Type.NONE;\n }\n\n // get ArrayType(): AnyArrayType {\n // return Int8Array;\n // }\n\n // get ArrayType() { return Array; }\n compareTo(other: DataType): boolean {\n // TODO\n return this === other; // comparer.visit(this, other);\n }\n}\n\n// NULL\n\nexport class Null extends DataType {\n get typeId(): Type {\n return Type.Null;\n }\n get [Symbol.toStringTag](): string {\n return 'Null';\n }\n toString(): string {\n return 'Null';\n }\n}\n\n// BOOLEANS\n\nexport class Bool extends DataType {\n get typeId(): Type {\n return Type.Bool;\n }\n // get ArrayType() {\n // return Uint8Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Bool';\n }\n toString(): string {\n return 'Bool';\n }\n}\n\n// INTS\n\nexport class Int extends DataType {\n readonly isSigned: boolean;\n readonly bitWidth: number;\n constructor(isSigned, bitWidth) {\n super();\n this.isSigned = isSigned;\n this.bitWidth = bitWidth;\n }\n get typeId(): Type {\n return Type.Int;\n }\n // get ArrayType() {\n // switch (this.bitWidth) {\n // case 8:\n // return this.isSigned ? Int8Array : Uint8Array;\n // case 16:\n // return this.isSigned ? Int16Array : Uint16Array;\n // case 32:\n // return this.isSigned ? Int32Array : Uint32Array;\n // case 64:\n // return this.isSigned ? Int32Array : Uint32Array;\n // default:\n // throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);\n // }\n // }\n get [Symbol.toStringTag](): string {\n return 'Int';\n }\n toString(): string {\n return `${this.isSigned ? 'I' : 'Ui'}nt${this.bitWidth}`;\n }\n}\n\nexport class Int8 extends Int {\n constructor() {\n super(true, 8);\n }\n}\nexport class Int16 extends Int {\n constructor() {\n super(true, 16);\n }\n}\nexport class Int32 extends Int {\n constructor() {\n super(true, 32);\n }\n}\nexport class Int64 extends Int {\n constructor() {\n super(true, 64);\n }\n}\nexport class Uint8 extends Int {\n constructor() {\n super(false, 8);\n }\n}\nexport class Uint16 extends Int {\n constructor() {\n super(false, 16);\n }\n}\nexport class Uint32 extends Int {\n constructor() {\n super(false, 32);\n }\n}\nexport class Uint64 extends Int {\n constructor() {\n super(false, 64);\n }\n}\n\n// FLOATS\n\nconst Precision = {\n HALF: 16,\n SINGLE: 32,\n DOUBLE: 64\n};\n\nexport class Float extends DataType {\n readonly precision: number;\n constructor(precision) {\n super();\n this.precision = precision;\n }\n get typeId(): Type {\n return Type.Float;\n }\n // get ArrayType() {\n // switch (this.precision) {\n // case Precision.HALF:\n // return Uint16Array;\n // case Precision.SINGLE:\n // return Float32Array;\n // case Precision.DOUBLE:\n // return Float64Array;\n // default:\n // throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);\n // }\n // }\n get [Symbol.toStringTag](): string {\n return 'Float';\n }\n toString(): string {\n return `Float${this.precision}`;\n }\n}\n\nexport class Float16 extends Float {\n constructor() {\n super(Precision.HALF);\n }\n}\nexport class Float32 extends Float {\n constructor() {\n super(Precision.SINGLE);\n }\n}\nexport class Float64 extends Float {\n constructor() {\n super(Precision.DOUBLE);\n }\n}\n\nexport class Binary extends DataType {\n constructor() {\n super();\n }\n get typeId() {\n return Type.Binary;\n }\n toString() {\n return 'Binary';\n }\n get [Symbol.toStringTag]() {\n return 'Binary';\n }\n}\n\n// STRINGS\n\nexport class Utf8 extends DataType {\n get typeId(): Type {\n return Type.Utf8;\n }\n // get ArrayType() {\n // return Uint8Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Utf8';\n }\n toString(): string {\n return 'Utf8';\n }\n}\n\n// DATES, TIMES AND INTERVALS\n\nconst DateUnit = {\n DAY: 0,\n MILLISECOND: 1\n};\n\nexport class Date extends DataType {\n readonly unit: number;\n constructor(unit) {\n super();\n this.unit = unit;\n }\n get typeId(): Type {\n return Type.Date;\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Date';\n }\n toString(): string {\n return `Date${(this.unit + 1) * 32}<${DateUnit[this.unit]}>`;\n }\n}\n\nexport class DateDay extends Date {\n constructor() {\n super(DateUnit.DAY);\n }\n}\nexport class DateMillisecond extends Date {\n constructor() {\n super(DateUnit.MILLISECOND);\n }\n}\n\nconst TimeUnit = {\n SECOND: 1,\n MILLISECOND: 1e3,\n MICROSECOND: 1e6,\n NANOSECOND: 1e9\n};\n\nexport class Time extends DataType {\n readonly unit: number;\n readonly bitWidth: number;\n\n constructor(unit, bitWidth) {\n super();\n this.unit = unit;\n this.bitWidth = bitWidth;\n }\n get typeId(): Type {\n return Type.Time;\n }\n toString(): string {\n return `Time${this.bitWidth}<${TimeUnit[this.unit]}>`;\n }\n get [Symbol.toStringTag](): string {\n return 'Time';\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n}\n\nexport class TimeSecond extends Time {\n constructor() {\n super(TimeUnit.SECOND, 32);\n }\n}\nexport class TimeMillisecond extends Time {\n constructor() {\n super(TimeUnit.MILLISECOND, 32);\n }\n}\n// export class TimeMicrosecond extends Time { constructor() { super(TimeUnit.MICROSECOND, 64); } }\n// export class TimeNanosecond extends Time { constructor() { super(TimeUnit.NANOSECOND, 64); } }\n\nexport class Timestamp extends DataType {\n readonly unit: any;\n readonly timezone: any;\n\n constructor(unit: any, timezone = null) {\n super();\n this.unit = unit;\n this.timezone = timezone;\n }\n get typeId(): Type {\n return Type.Timestamp;\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Timestamp';\n }\n toString(): string {\n return `Timestamp<${TimeUnit[this.unit]}${this.timezone ? `, ${this.timezone}` : ''}>`;\n }\n}\n\nexport class TimestampSecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.SECOND, timezone);\n }\n}\nexport class TimestampMillisecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.MILLISECOND, timezone);\n }\n}\nexport class TimestampMicrosecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.MICROSECOND, timezone);\n }\n}\nexport class TimestampNanosecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.NANOSECOND, timezone);\n }\n}\n\nconst IntervalUnit = {\n DAY_TIME: 0,\n YEAR_MONTH: 1\n};\n\nexport class Interval extends DataType {\n readonly unit: number;\n constructor(unit: number) {\n super();\n this.unit = unit;\n }\n get typeId(): Type {\n return Type.Interval;\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Interval';\n }\n toString(): string {\n return `Interval<${IntervalUnit[this.unit]}>`;\n }\n}\n\nexport class IntervalDayTime extends Interval {\n constructor() {\n super(IntervalUnit.DAY_TIME);\n }\n}\nexport class IntervalYearMonth extends Interval {\n constructor() {\n super(IntervalUnit.YEAR_MONTH);\n }\n}\n\nexport class FixedSizeList extends DataType {\n readonly listSize: number;\n readonly children: Field[];\n\n constructor(listSize: number, child: Field) {\n super();\n this.listSize = listSize;\n this.children = [child];\n }\n get typeId(): Type {\n return Type.FixedSizeList;\n }\n get valueType() {\n return this.children[0].type;\n }\n get valueField() {\n return this.children[0];\n }\n // get ArrayType() {\n // return this.valueType.ArrayType;\n // }\n get [Symbol.toStringTag](): string {\n return 'FixedSizeList';\n }\n toString(): string {\n return `FixedSizeList[${this.listSize}]<${this.valueType}>`;\n }\n}\n","// This code is adapted from ArrowJS https://github.com/apache/arrow\n// under Apache license http://www.apache.org/licenses/LICENSE-2.0\n\n/**\n * Main data type enumeration.\n *\n * Data types in this library are all *logical*. They can be expressed as\n * either a primitive physical type (bytes or bits of some fixed size), a\n * nested type consisting of other data types, or another data type (e.g. a\n * timestamp encoded as an int64).\n *\n * **Note**: Only enum values 0-17 (NONE through Map) are written to an Arrow\n * IPC payload.\n *\n * The rest of the values are specified here so TypeScript can narrow the type\n * signatures further beyond the base Arrow Types. The Arrow DataTypes include\n * metadata like `bitWidth` that impact the type signatures of the values we\n * accept and return.\n *\n * For example, the `Int8Vector` reads 1-byte numbers from an `Int8Array`, an\n * `Int32Vector` reads a 4-byte number from an `Int32Array`, and an `Int64Vector`\n * reads a pair of 4-byte lo, hi 32-bit integers as a zero-copy slice from the\n * underlying `Int32Array`.\n *\n * Library consumers benefit by knowing the narrowest type, since we can ensure\n * the types across all public methods are propagated, and never bail to `any`.\n * These values are _never_ used at runtime, and they will _never_ be written\n * to the flatbuffers metadata of serialized Arrow IPC payloads.\n */\nexport enum Type {\n /** The default placeholder type */\n NONE = 0,\n /** A NULL type having no physical storage */\n Null = 1,\n /** Signed or unsigned 8, 16, 32, or 64-bit little-endian integer */\n Int = 2,\n /** 2, 4, or 8-byte floating point value */\n Float = 3,\n /** Variable-length bytes (no guarantee of UTF8-ness) */\n Binary = 4,\n /** UTF8 variable-length string as List<Char> */\n Utf8 = 5,\n /** Boolean as 1 bit, LSB bit-packed ordering */\n Bool = 6,\n /** Precision-and-scale-based decimal type. Storage type depends on the parameters. */\n Decimal = 7,\n /** int32_t days or int64_t milliseconds since the UNIX epoch */\n Date = 8,\n /** Time as signed 32 or 64-bit integer, representing either seconds, milliseconds, microseconds, or nanoseconds since midnight since midnight */\n Time = 9,\n /** Exact timestamp encoded with int64 since UNIX epoch (Default unit millisecond) */\n Timestamp = 10,\n /** YEAR_MONTH or DAY_TIME interval in SQL style */\n Interval = 11,\n /** A list of some logical data type */\n List = 12,\n /** Struct of logical types */\n Struct = 13,\n /** Union of logical types */\n Union = 14,\n /** Fixed-size binary. Each value occupies the same number of bytes */\n FixedSizeBinary = 15,\n /** Fixed-size list. Each value occupies the same number of bytes */\n FixedSizeList = 16,\n /** Map of named logical types */\n Map = 17,\n\n /** Dictionary aka Category type */\n Dictionary = -1,\n Int8 = -2,\n Int16 = -3,\n Int32 = -4,\n Int64 = -5,\n Uint8 = -6,\n Uint16 = -7,\n Uint32 = -8,\n Uint64 = -9,\n Float16 = -10,\n Float32 = -11,\n Float64 = -12,\n DateDay = -13,\n DateMillisecond = -14,\n TimestampSecond = -15,\n TimestampMillisecond = -16,\n TimestampMicrosecond = -17,\n TimestampNanosecond = -18,\n TimeSecond = -19,\n TimeMillisecond = -20,\n TimeMicrosecond = -21,\n TimeNanosecond = -22,\n DenseUnion = -23,\n SparseUnion = -24,\n IntervalDayTime = -25,\n IntervalYearMonth = -26\n}\n","// Type deduction\nimport {\n Schema\n // Int,\n // Int8,\n // Int16,\n // Int32,\n // Uint8,\n // Uint16,\n // Uint32,\n // Float32,\n // Float64\n // Bool,\n // Utf8,\n // TimestampMillisecond,\n // Null\n} from '../schema';\n\n// const TYPED_ARRAY_TO_TYPE = {\n// Int8Array: new Int8(),\n// Int16Array: new Int16(),\n// Int32Array: new Int32(),\n// Uint8Array: new Uint8(),\n// Uint8ClampedArray: new Uint8(),\n// Uint16Array: new Uint16(),\n// Uint32Array: new Uint32(),\n// Float32Array: new Float32(),\n// Float64Array: new Float64()\n// };\n\n// if (typeof BigInt64Array !== 'undefined') {\n// TYPED_ARRAY_TO_TYPE.BigInt64Array = new Int64();\n// TYPED_ARRAY_TO_TYPE.BigUint64Array = new Uint64();\n// }\n\n/**\n * SCHEMA SUPPORT - AUTODEDUCTION\n * @param {*} table\n * @param {*} schema\n * @returns\n */\nexport function deduceTableSchema(table, schema?: Schema) {\n const deducedSchema = Array.isArray(table)\n ? deduceSchemaForRowTable(table)\n : deduceSchemaForColumnarTable(table);\n // Deduced schema will fill in missing info from partial options.schema, if provided\n return Object.assign(deducedSchema, schema);\n}\n\nfunction deduceSchemaForColumnarTable(columnarTable) {\n const schema = {};\n for (const field in columnarTable) {\n const column = columnarTable[field];\n // Check if column is typed, if so we are done\n if (ArrayBuffer.isView(column)) {\n schema[field] = column.constructor;\n // else we need data\n } else if (column.length) {\n const value = column[0];\n schema[field] = deduceTypeFromValue(value);\n // TODO - support nested schemas?\n }\n // else we mark as present but unknow\n schema[field] = schema[field] || null;\n }\n return schema;\n}\n\nfunction deduceSchemaForRowTable(rowTable) {\n const schema = {};\n if (rowTable.length) {\n const row = rowTable[0];\n // TODO - Could look at additional rows if nulls in first row\n for (const field in row) {\n const value = row[field];\n schema[field] = deduceTypeFromValue(value);\n }\n }\n return schema;\n}\n\nfunction deduceTypeFromValue(value) {\n if (value instanceof Date) {\n return Date;\n } else if (value instanceof Number) {\n return Float32Array;\n } else if (typeof value === 'string') {\n return String;\n }\n return null;\n}\n\n/*\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction deduceSchema(rows) {\n const row = rows[0];\n\n const schema = {};\n let i = 0;\n for (const columnName in row) {\n const value = row[columnName];\n switch (typeof value) {\n case 'number':\n case 'boolean':\n // TODO - booleans could be handled differently...\n schema[columnName] = {name: String(columnName), index: i, type: Float32Array};\n break;\n\n case 'object':\n schema[columnName] = {name: String(columnName), index: i, type: Array};\n break;\n\n case 'string':\n default:\n schema[columnName] = {name: String(columnName), index: i, type: Array};\n // We currently only handle numeric rows\n // TODO we could offer a function to map strings to numbers?\n }\n i++;\n }\n return schema;\n}\n*/\n","import {Type} from '../schema';\nimport {AnyArray} from '../../types';\n\n/**\n * Gets type information from an Arrow type object or \"mock\" Arrow type object\n * @param arrowTypeLike Arrow Type or type object of similar shape\n */\nexport function getTypeInfo(arrowTypeLike: any): {\n typeId: Type;\n ArrayType: AnyArray;\n typeName: string;\n typeEnumName?: string;\n precision?: number;\n} {\n return {\n typeId: arrowTypeLike.typeId,\n ArrayType: arrowTypeLike.ArrayType,\n typeName: arrowTypeLike.toString(),\n typeEnumName: getTypeKey(arrowTypeLike.typeId),\n precision: arrowTypeLike.precision\n };\n}\n\nlet ReverseType: {[key: string]: string} | null = null;\n\nfunction getTypeKey(typeKey) {\n if (!ReverseType) {\n ReverseType = {};\n for (const key in Type) {\n ReverseType[Type[key]] = key;\n }\n }\n\n return ReverseType[typeKey];\n}\n","import type {TypedArray} from '../../types';\nimport {DataType, Float32, Float64, Int16, Int32, Int8, Uint16, Uint32, Uint8} from '../schema';\n\nexport function getArrowTypeFromTypedArray(array: TypedArray): DataType {\n switch (array.constructor) {\n case Int8Array:\n return new Int8();\n case Uint8Array:\n return new Uint8();\n case Int16Array:\n return new Int16();\n case Uint16Array:\n return new Uint16();\n case Int32Array:\n return new Int32();\n case Uint32Array:\n return new Uint32();\n case Float32Array:\n return new Float32();\n case Float64Array:\n return new Float64();\n default:\n throw new Error('array type not supported');\n }\n}\n","// From https://github.com/rauschma/async-iter-demo/tree/master/src under MIT license\n// http://2ality.com/2016/10/asynchronous-iteration.html\n\nclass ArrayQueue<T> extends Array<T> {\n enqueue(value) {\n // Add at the end\n return this.push(value);\n }\n dequeue(): T {\n // Remove first element\n return this.shift() as T;\n }\n}\n\nexport default class AsyncQueue<T> {\n private _values: ArrayQueue<T>;\n private _settlers: ArrayQueue<{resolve; reject}>;\n private _closed: boolean;\n\n constructor() {\n // enqueues > dequeues\n this._values = new ArrayQueue<T>();\n // dequeues > enqueues\n this._settlers = new ArrayQueue<{resolve; reject}>();\n this._closed = false;\n }\n\n close(): void {\n while (this._settlers.length > 0) {\n this._settlers.dequeue().resolve({done: true});\n }\n this._closed = true;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this;\n }\n\n enqueue(value: T | Error): void {\n if (this._closed) {\n throw new Error('Closed');\n }\n\n if (this._settlers.length > 0) {\n if (this._values.length > 0) {\n throw new Error('Illegal internal state');\n }\n const settler = this._settlers.dequeue();\n if (value instanceof Error) {\n settler.reject(value);\n } else {\n settler.resolve({value});\n }\n } else {\n this._values.enqueue(value);\n }\n }\n\n /**\n * @returns a Promise for an IteratorResult\n */\n next(): Promise<any> {\n if (this._values.length > 0) {\n const value = this._values.dequeue();\n if (value instanceof Error) {\n return Promise.reject(value);\n }\n return Promise.resolve({value});\n }\n\n if (this._closed) {\n if (this._settlers.length > 0) {\n throw new Error('Illegal internal state');\n }\n return Promise.resolve({done: true});\n }\n // Wait for new values to be enqueued\n return new Promise((resolve, reject) => {\n this._settlers.enqueue({resolve, reject});\n });\n }\n}\n\n/**\n * @returns a Promise for an Array with the elements in `asyncIterable`\n */\nexport async function takeAsync(\n asyncIterable: AsyncIterable<any>,\n count = Infinity\n): Promise<any[]> {\n const result: Array<any> = [];\n const iterator = asyncIterable[Symbol.asyncIterator]();\n while (result.length < count) {\n const {value, done} = await iterator.next();\n if (done) {\n break;\n }\n result.push(value);\n }\n return result;\n}\n","// TYPES\nexport type {\n Loader,\n LoaderWithParser,\n LoaderContext,\n LoaderOptions,\n Writer,\n WriterOptions,\n DataType,\n SyncDataType,\n BatchableDataType,\n IFileSystem,\n IRandomAccessReadFileSystem\n} from './types';\n\n// GENERAL UTILS\nexport {assert} from './lib/env-utils/assert';\nexport {\n isBrowser,\n isWorker,\n nodeVersion,\n self,\n window,\n global,\n document\n} from './lib/env-utils/globals';\n\n// LOADERS.GL-SPECIFIC WORKER UTILS\nexport {createLoaderWorker} from './lib/worker-loader-utils/create-loader-worker';\nexport {parseWithWorker, canParseWithWorker} from './lib/worker-loader-utils/parse-with-worker';\n\n// PARSER UTILS\nexport {parseJSON} from './lib/parser-utils/parse-json';\n\n// MEMORY COPY UTILS\nexport {\n toArrayBuffer,\n sliceArrayBuffer,\n concatenateArrayBuffers,\n concatenateTypedArrays,\n compareArrayBuffers\n} from './lib/binary-utils/array-buffer-utils';\nexport {padToNBytes, copyToArray, copyArrayBuffer} from './lib/binary-utils/memory-copy-utils';\nexport {\n copyPaddedArrayBufferToDataView,\n copyPaddedStringToDataView\n} from './lib/binary-utils/binary-copy-utils';\nexport {\n padStringToByteAlignment,\n copyStringToDataView,\n copyBinaryToDataView\n} from './lib/binary-utils/encode-utils';\nexport {getFirstCharacters, getMagicString} from './lib/binary-utils/get-first-characters';\n\n// ITERATOR UTILS\nexport {\n makeTextEncoderIterator,\n makeTextDecoderIterator,\n makeLineIterator,\n makeNumberedLineIterator\n} from './lib/iterators/text-iterators';\nexport {forEach, concatenateArrayBuffersAsync} from './lib/iterators/async-iteration';\n\n// REQUEST UTILS\nexport {default as RequestScheduler} from './lib/request-utils/request-scheduler';\n\n// PATH HELPERS\nexport {setPathPrefix, getPathPrefix, resolvePath} from './lib/path-utils/file-aliases';\nexport {addAliases as _addAliases} from './lib/path-utils/file-aliases';\n\n// MICRO LOADERS\nexport {JSONLoader} from './json-loader';\n\n// NODE support\n\n// Node.js emulation (can be used in browser)\n\n// `path` replacement (avoids bundling big path polyfill)\nimport * as path from './lib/path-utils/path';\nexport {path};\n\n// Avoid direct use of `Buffer` which pulls in 50KB polyfill\nexport {isBuffer, toBuffer, bufferToArrayBuffer} from './lib/binary-utils/buffer-utils';\n\n// Note.js wrappers (can be safely imported, but not used in browser)\n\n// Use instead of importing 'util'\nimport * as util from './lib/node/util';\nexport {util};\n// TODO - remove\nexport {promisify} from './lib/node/util';\n\n// Use instead of importing 'fs';`\nimport * as fs from './lib/node/fs';\nexport {fs};\n\n// EXPERIMENTAL\nexport {default as _NodeFileSystem} from './lib/filesystems/node-filesystem';\n","// Purpose: include this in your module to avoid\n// dependencies on micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\ntype obj = {[key: string]: any};\nconst self_: obj = globals.self || globals.window || globals.global || {};\nconst window_: obj = globals.window || globals.self || globals.global || {};\nconst global_: obj = globals.global || globals.self || globals.window || {};\nconst document_: obj = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\n/** true if running in a browser */\nexport const isBrowser: boolean =\n // @ts-ignore process does not exist on browser\n typeof process !== 'object' || String(process) !== '[object process]' || process.browser;\n\n/** true if running in a worker thread */\nexport const isWorker: boolean = typeof importScripts === 'function';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\n/** Major Node version (as a number) */\nexport const nodeVersion: number = (matches && parseFloat(matches[1])) || 0;\n","/* eslint-disable no-restricted-globals */\nimport type {LoaderWithParser} from '../../types';\nimport {WorkerBody} from '@loaders.gl/worker-utils';\n// import {validateLoaderVersion} from './validate-loader-version';\n\nlet requestId = 0;\n\n/**\n * Set up a WebWorkerGlobalScope to talk with the main thread\n * @param loader\n */\nexport function createLoaderWorker(loader: LoaderWithParser) {\n // Check that we are actually in a worker thread\n if (typeof self === 'undefined') {\n return;\n }\n\n WorkerBody.onmessage = async (type, payload) => {\n switch (type) {\n case 'process':\n try {\n // validateLoaderVersion(loader, data.source.split('@')[1]);\n\n const {input, options = {}} = payload;\n\n const result = await parseData({\n loader,\n arrayBuffer: input,\n options,\n context: {\n parse: parseOnMainThread\n }\n });\n WorkerBody.postMessage('done', {result});\n } catch (error) {\n const message = error instanceof Error ? error.message : '';\n WorkerBody.postMessage('error', {error: message});\n }\n break;\n default:\n }\n };\n}\n\nfunction parseOnMainThread(arrayBuffer: ArrayBuffer, options: {[key: string]: any}): Promise<void> {\n return new Promise((resolve, reject) => {\n const id = requestId++;\n\n /**\n */\n const onMessage = (type, payload) => {\n if (payload.id !== id) {\n // not ours\n return;\n }\n\n switch (type) {\n case 'done':\n WorkerBody.removeEventListener(onMessage);\n resolve(payload.result);\n break;\n\n case 'error':\n WorkerBody.removeEventListener(onMessage);\n reject(payload.error);\n break;\n\n default:\n // ignore\n }\n };\n\n WorkerBody.addEventListener(onMessage);\n\n // Ask the main thread to decode data\n const payload = {id, input: arrayBuffer, options};\n WorkerBody.postMessage('process', payload);\n });\n}\n\n// TODO - Support byteOffset and byteLength (enabling parsing of embedded binaries without copies)\n// TODO - Why not support async loader.parse* funcs here?\n// TODO - Why not reuse a common function instead of reimplementing loader.parse* selection logic? Keeping loader small?\n// TODO - Lack of appropriate parser functions can be detected when we create worker, no need to wait until parse\nasync function parseData({loader, arrayBuffer, options, context}) {\n let data;\n let parser;\n if (loader.parseSync || loader.parse) {\n data = arrayBuffer;\n parser = loader.parseSync || loader.parse;\n } else if (loader.parseTextSync) {\n const textDecoder = new TextDecoder();\n data = textDecoder.decode(arrayBuffer);\n parser = loader.parseTextSync;\n } else {\n throw new Error(`Could not load data with ${loader.name} loader`);\n }\n\n // TODO - proper merge in of loader options...\n options = {\n ...options,\n modules: (loader && loader.options && loader.options.modules) || {},\n worker: false\n };\n\n return await parser(data, {...options}, context, loader);\n}\n","import {assert} from '../env-utils/assert';\n\nconst workerURLCache = new Map();\n\n/**\n * Creates a loadable URL from worker source or URL\n * that can be used to create `Worker` instances.\n * Due to CORS issues it may be necessary to wrap a URL in a small importScripts\n * @param props\n * @param props.source Worker source\n * @param props.url Worker URL\n * @returns loadable url\n */\nexport function getLoadableWorkerURL(props: {source?: string; url?: string}) {\n assert((props.source && !props.url) || (!props.source && props.url)); // Either source or url must be defined\n\n let workerURL = workerURLCache.get(props.source || props.url);\n if (!workerURL) {\n // Differentiate worker urls from worker source code\n if (props.url) {\n workerURL = getLoadableWorkerURLFromURL(props.url);\n workerURLCache.set(props.url, workerURL);\n }\n\n if (props.source) {\n workerURL = getLoadableWorkerURLFromSource(props.source);\n workerURLCache.set(props.source, workerURL);\n }\n }\n\n assert(workerURL);\n return workerURL;\n}\n\n/**\n * Build a loadable worker URL from worker URL\n * @param url\n * @returns loadable URL\n */\nfunction getLoadableWorkerURLFromURL(url: string): string {\n // A local script url, we can use it to initialize a Worker directly\n if (!url.startsWith('http')) {\n return url;\n }\n\n // A remote script, we need to use `importScripts` to load from different origin\n const workerSource = buildScriptSource(url);\n return getLoadableWorkerURLFromSource(workerSource);\n}\n\n/**\n * Build a loadable worker URL from worker source\n * @param workerSource\n * @returns loadable url\n */\nfunction getLoadableWorkerURLFromSource(workerSource: string): string {\n // NOTE: webworkify was previously used\n // const blob = webworkify(workerSource, {bare: true});\n const blob = new Blob([workerSource], {type: 'application/javascript'});\n return URL.createObjectURL(blob);\n}\n\n/**\n * Per spec, worker cannot be initialized with a script from a different origin\n * However a local worker script can still import scripts from other origins,\n * so we simply build a wrapper script.\n *\n * @param workerUrl\n * @returns source\n */\nfunction buildScriptSource(workerUrl: string): string {\n return `\\\ntry {\n importScripts('${workerUrl}');\n} catch (error) {\n console.error(error);\n throw error;\n}`;\n}\n","import type {\n WorkerObject,\n WorkerOptions,\n WorkerContext,\n WorkerMessageType,\n WorkerMessagePayload\n} from '../../types';\nimport type WorkerJob from '../worker-farm/worker-job';\nimport WorkerFarm from '../worker-farm/worker-farm';\nimport {removeNontransferableOptions} from '../worker-utils/remove-nontransferable-options';\nimport {getWorkerURL, getWorkerName} from './get-worker-url';\n\ntype ProcessOnWorkerOptions = WorkerOptions & {\n jobName?: string;\n [key: string]: any;\n};\n\n/**\n * Determines if we can parse with worker\n * @param loader\n * @param data\n * @param options\n */\nexport function canProcessOnWorker(worker: WorkerObject, options?: WorkerOptions) {\n if (!WorkerFarm.isSupported()) {\n return false;\n }\n\n return worker.worker && options?.worker;\n}\n\n/**\n * This function expects that the worker thread sends certain messages,\n * Creating such a worker can be automated if the worker is wrapper by a call to\n * createWorker in @loaders.gl/worker-utils.\n */\nexport async function processOnWorker(\n worker: WorkerObject,\n data: any,\n options: ProcessOnWorkerOptions = {},\n context: WorkerContext = {}\n): Promise<any> {\n const name = getWorkerName(worker);\n const url = getWorkerURL(worker, options);\n\n const workerFarm = WorkerFarm.getWorkerFarm(options);\n const workerPool = workerFarm.getWorkerPool({name, url});\n\n const jobName = options.jobName || worker.name;\n const job = await workerPool.startJob(\n jobName,\n // eslint-disable-next-line\n onMessage.bind(null, context)\n );\n\n // Kick off the processing in the worker\n const transferableOptions = removeNontransferableOptions(options);\n job.postMessage('process', {input: data, options: transferableOptions});\n\n const result = await job.result;\n return result.result;\n}\n\n/**\n * Job completes when we receive the result\n * @param job\n * @param message\n */\nasync function onMessage(\n context: WorkerContext,\n job: WorkerJob,\n type: WorkerMessageType,\n payload: WorkerMessagePayload\n) {\n switch (type) {\n case 'done':\n // Worker is done\n job.done(payload);\n break;\n\n case 'error':\n // Worker encountered an error\n job.error(payload.error);\n break;\n\n case 'process':\n // Worker is asking for us (main thread) to process something\n const {id, input, options} = payload;\n try {\n if (!context.process) {\n job.postMessage('error', {id, error: 'Worker not set up to process on main thread'});\n return;\n }\n const result = await context.process(input, options);\n job.postMessage('done', {id, result});\n } catch (error) {\n const message = error instanceof Error ? error.message : 'unknown error';\n job.postMessage('error', {id, error: message});\n }\n break;\n\n default:\n // eslint-disable-next-line\n console.warn(`process-on-worker: unknown message ${type}`);\n }\n}\n","/**\n * Safely stringify JSON (drop non serializable values like functions and regexps)\n * @param value\n */\nexport function removeNontransferableOptions(object: object): object {\n // options.log object contains functions which cannot be transferred\n // TODO - decide how to handle logging on workers\n // TODO - warn if options stringification is long\n return JSON.parse(stringifyJSON(object));\n}\n\nfunction stringifyJSON(v) {\n const cache = new Set();\n return JSON.stringify(v, (key, value) => {\n if (typeof value === 'object' && value !== null) {\n if (cache.has(value)) {\n // Circular reference found\n try {\n // If this value does not reference a parent it can be deduped\n return JSON.parse(JSON.stringify(value));\n } catch (err) {\n // discard key if value cannot be deduped\n return undefined;\n }\n }\n // Store value in our set\n cache.add(value);\n }\n return value;\n });\n}\n","import type {\n WorkerMessageType,\n WorkerMessagePayload,\n WorkerContext,\n Process,\n ProcessInBatches\n} from '../../types';\nimport AsyncQueue from '../async-queue/async-queue';\nimport WorkerBody from '../worker-farm/worker-body';\n// import {validateWorkerVersion} from './validate-worker-version';\n\n/** Counter for jobs */\nlet requestId = 0;\nlet inputBatches;\nlet options;\n\nexport type ProcessOnMainThread = (data: any, options?: {[key: string]: any}, context?) => any;\n\n/**\n * Set up a WebWorkerGlobalScope to talk with the main thread\n */\nexport function createWorker(process: Process, processInBatches?: ProcessInBatches): void {\n // Check that we are actually in a worker thread\n if (typeof self === 'undefined') {\n return;\n }\n\n const context: WorkerContext = {\n process: processOnMainThread\n };\n\n // eslint-disable-next-line complexity\n WorkerBody.onmessage = async (type: WorkerMessageType, payload: WorkerMessagePayload) => {\n try {\n switch (type) {\n case 'process':\n if (!process) {\n throw new Error('Worker does not support atomic processing');\n }\n const result = await process(payload.input, payload.options || {}, context);\n WorkerBody.postMessage('done', {result});\n break;\n\n case 'process-in-batches':\n if (!processInBatches) {\n throw new Error('Worker does not support batched processing');\n }\n inputBatches = new AsyncQueue();\n options = payload.options || {};\n const resultIterator = processInBatches(inputBatches, options, context?.processInBatches);\n for await (const batch of resultIterator) {\n WorkerBody.postMessage('output-batch', {result: batch});\n }\n WorkerBody.postMessage('done', {});\n break;\n\n case 'input-batch':\n inputBatches.push(payload.input);\n break;\n\n case 'input-done':\n inputBatches.close();\n break;\n\n default:\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : '';\n WorkerBody.postMessage('error', {error: message});\n }\n };\n}\n\nfunction processOnMainThread(arrayBuffer, options = {}) {\n return new Promise((resolve, reject) => {\n const id = requestId++;\n\n /**\n */\n const onMessage = (type, payload) => {\n if (payload.id !== id) {\n // not ours\n return;\n }\n\n switch (type) {\n case 'done':\n WorkerBody.removeEventListener(onMessage);\n resolve(payload.result);\n break;\n\n case 'error':\n WorkerBody.removeEventListener(onMessage);\n reject(payload.error);\n break;\n\n default:\n // ignore\n }\n };\n\n WorkerBody.addEventListener(onMessage);\n\n // Ask the main thread to decode data\n const payload = {id, input: arrayBuffer, options};\n WorkerBody.postMessage('process', payload);\n });\n}\n","import type {WorkerObject} from '../../types';\nimport {assert} from '../env-utils/assert';\nimport {VERSION} from '../env-utils/version';\n\n/**\n * Check if worker is compatible with this library version\n * @param worker\n * @param libVersion\n * @returns `true` if the two versions are compatible\n */\nexport function validateWorkerVersion(\n worker: WorkerObject,\n coreVersion: string = VERSION\n): boolean {\n assert(worker, 'no worker provided');\n\n const workerVersion = worker.version;\n if (!coreVersion || !workerVersion) {\n return false;\n }\n\n // TODO enable when fix the __version__ injection\n // const coreVersions = parseVersion(coreVersion);\n // const workerVersions = parseVersion(workerVersion);\n // assert(\n // coreVersion.major === workerVersion.major && coreVersion.minor <= workerVersion.minor,\n // `worker: ${worker.name} is not compatible. ${coreVersion.major}.${\n // coreVersion.minor\n // }+ is required.`\n // );\n\n return true;\n}\n\n// @ts-ignore\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction parseVersion(version) {\n const parts = version.split('.').map(Number);\n return {major: parts[0], minor: parts[1]};\n}\n","/* global importScripts */\nimport {global, isBrowser, isWorker} from '../env-utils/globals';\nimport * as node from '../node/require-utils.node';\nimport {assert} from '../env-utils/assert';\nimport {VERSION as __VERSION__} from '../env-utils/version';\n\n// TODO - unpkg.com doesn't seem to have a `latest` specifier for alpha releases...\nconst LATEST = 'beta';\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : LATEST;\n\nconst loadLibraryPromises = {}; // promises\n\n/**\n * Dynamically loads a library (\"module\")\n *\n * - wasm library: Array buffer is returned\n * - js library: Parse JS is returned\n *\n * Method depends on environment\n * - browser - script element is created and installed on document\n * - worker - eval is called on global context\n * - node - file is required\n *\n * @param libraryUrl\n * @param moduleName\n * @param options\n */\nexport async function loadLibrary(\n libraryUrl: string,\n moduleName: string | null = null,\n options: object = {}\n): Promise<any> {\n if (moduleName) {\n libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);\n }\n\n // Ensure libraries are only loaded once\n loadLibraryPromises[libraryUrl] =\n loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);\n return await loadLibraryPromises[libraryUrl];\n}\n\n// TODO - sort out how to resolve paths for main/worker and dev/prod\nexport function getLibraryUrl(library, moduleName?: string, options?): string {\n // Check if already a URL\n if (library.startsWith('http')) {\n return library;\n }\n\n // Allow application to import and supply libraries through `options.modules`\n const modules = options.modules || {};\n if (modules[library]) {\n return modules[library];\n }\n\n // Load from local files, not from CDN scripts in Node.js\n // TODO - needs to locate the modules directory when installed!\n if (!isBrowser) {\n return `modules/${moduleName}/dist/libs/${library}`;\n }\n\n // In browser, load from external scripts\n if (options.CDN) {\n assert(options.CDN.startsWith('http'));\n return `${options.CDN}/${moduleName}@${VERSION}/dist/libs/${library}`;\n }\n\n // TODO - loading inside workers requires paths relative to worker script location...\n if (isWorker) {\n return `../src/libs/${library}`;\n }\n\n return `modules/${moduleName}/src/libs/${library}`;\n}\n\nasync function loadLibraryFromFile(libraryUrl) {\n if (libraryUrl.endsWith('wasm')) {\n const response = await fetch(libraryUrl);\n return await response.arrayBuffer();\n }\n\n if (!isBrowser) {\n return node.requireFromFile && (await node.requireFromFile(libraryUrl));\n }\n if (isWorker) {\n return importScripts(libraryUrl);\n }\n // TODO - fix - should be more secure than string parsing since observes CORS\n // if (isBrowser) {\n // return await loadScriptFromFile(libraryUrl);\n // }\n\n const response = await fetch(libraryUrl);\n const scriptSource = await response.text();\n return loadLibraryFromString(scriptSource, libraryUrl);\n}\n\n/*\nasync function loadScriptFromFile(libraryUrl) {\n const script = document.createElement('script');\n script.src = libraryUrl;\n return await new Promise((resolve, reject) => {\n script.onload = data => {\n resolve(data);\n };\n script.onerror = reject;\n });\n}\n*/\n\n// TODO - Needs security audit...\n// - Raw eval call\n// - Potentially bypasses CORS\n// Upside is that this separates fetching and parsing\n// we could create a`LibraryLoader` or`ModuleLoader`\nfunction loadLibraryFromString(scriptSource, id) {\n if (!isBrowser) {\n return node.requireFromString && node.requireFromString(scriptSource, id);\n }\n\n if (isWorker) {\n // Use lvalue trick to make eval run in global scope\n eval.call(global, scriptSource); // eslint-disable-line no-eval\n // https://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript\n // http://perfectionkills.com/global-eval-what-are-the-options/\n return null;\n }\n\n const script = document.createElement('script');\n script.id = id;\n // most browsers like a separate text node but some throw an error. The second method covers those.\n try {\n script.appendChild(document.createTextNode(scriptSource));\n } catch (e) {\n script.text = scriptSource;\n }\n document.body.appendChild(script);\n return null;\n}\n\n// TODO - technique for module injection into worker, from THREE.DracoLoader...\n/*\nfunction combineWorkerWithLibrary(worker, jsContent) {\n var fn = wWorker.toString();\n var body = [\n '// injected',\n jsContent,\n '',\n '// worker',\n fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))\n ].join('\\n');\n this.workerSourceURL = URL.createObjectURL(new Blob([body]));\n}\n*/\n","import type {WorkerJob, WorkerMessageType, WorkerMessagePayload} from '@loaders.gl/worker-utils';\nimport type {Loader, LoaderOptions, LoaderContext} from '../../types';\nimport {WorkerFarm, getWorkerURL} from '@loaders.gl/worker-utils';\n\n/**\n * Determines if a loader can parse with worker\n * @param loader\n * @param options\n */\nexport function canParseWithWorker(loader: Loader, options?: LoaderOptions) {\n if (!WorkerFarm.isSupported()) {\n return false;\n }\n\n return loader.worker && options?.worker;\n}\n\n/**\n * this function expects that the worker function sends certain messages,\n * this can be automated if the worker is wrapper by a call to createLoaderWorker in @loaders.gl/loader-utils.\n */\nexport async function parseWithWorker(\n loader: Loader,\n data,\n options?: LoaderOptions,\n context?: LoaderContext,\n parseOnMainThread?: (arrayBuffer: ArrayBuffer, options: {[key: string]: any}) => Promise<void>\n) {\n const name = loader.id; // TODO\n const url = getWorkerURL(loader, options);\n\n const workerFarm = WorkerFarm.getWorkerFarm(options);\n const workerPool = workerFarm.getWorkerPool({name, url});\n\n // options.log object contains functions which cannot be transferred\n // TODO - decide how to handle logging on workers\n options = JSON.parse(JSON.stringify(options));\n\n const job = await workerPool.startJob(\n 'process-on-worker',\n // eslint-disable-next-line\n onMessage.bind(null, parseOnMainThread)\n );\n\n job.postMessage('process', {\n // @ts-ignore\n input: data,\n options\n });\n\n const result = await job.result;\n return await result.result;\n}\n\n/**\n * Handle worker's responses to the main thread\n * @param job\n * @param type\n * @param payload\n */\nasync function onMessage(\n parseOnMainThread,\n job: WorkerJob,\n type: WorkerMessageType,\n payload: WorkerMessagePayload\n) {\n switch (type) {\n case 'done':\n job.done(payload);\n break;\n\n case 'error':\n job.error(payload.error);\n break;\n\n case 'process':\n // Worker is asking for main thread to parseO\n const {id, input, options} = payload;\n try {\n const result = await parseOnMainThread(input, options);\n job.postMessage('done', {id, result});\n } catch (error) {\n const message = error instanceof Error ? error.message : 'unknown error';\n job.postMessage('error', {id, error: message});\n }\n break;\n\n default:\n // eslint-disable-next-line\n console.warn(`parse-with-worker unknown message ${type}`);\n }\n}\n","import {getFirstCharacters} from '../binary-utils/get-first-characters';\n\n/**\n * Minimal JSON parser that throws more meaningful error messages\n */\nexport function parseJSON(string: string): any {\n try {\n return JSON.parse(string);\n } catch (_) {\n throw new Error(`Failed to parse JSON from data starting with \"${getFirstCharacters(string)}\"`);\n }\n}\n","import {TypedArray} from '../../types';\nimport {padToNBytes} from './memory-copy-utils';\n\n/**\n * Copy sourceBuffer to dataView with some padding\n *\n * @param {DataView | null} dataView - destination data container. If null - only new offset is calculated\n * @param {number} byteOffset - destination byte offset to copy to\n * @param {Array | TypedArray} sourceBuffer - source data buffer\n * @param {number} padding - pad the resulting array to multiple of \"padding\" bytes. Additional bytes are filled with 0x20 (ASCII space)\n *\n * @return new byteOffset of resulting dataView\n */\nexport function copyPaddedArrayBufferToDataView(\n dataView: DataView | null,\n byteOffset: number,\n sourceBuffer: TypedArray,\n padding: number\n) {\n const paddedLength = padToNBytes(sourceBuffer.byteLength, padding);\n const padLength = paddedLength - sourceBuffer.byteLength;\n\n if (dataView) {\n // Copy array\n const targetArray = new Uint8Array(\n dataView.buffer,\n dataView.byteOffset + byteOffset,\n sourceBuffer.byteLength\n );\n const sourceArray = new Uint8Array(sourceBuffer);\n targetArray.set(sourceArray);\n\n // Add PADDING\n for (let i = 0; i < padLength; ++i) {\n // json chunk is padded with spaces (ASCII 0x20)\n dataView.setUint8(byteOffset + sourceBuffer.byteLength + i, 0x20);\n }\n }\n byteOffset += paddedLength;\n return byteOffset;\n}\n\n/**\n * Copy string to dataView with some padding\n *\n * @param {DataView | null} dataView - destination data container. If null - only new offset is calculated\n * @param {number} byteOffset - destination byte offset to copy to\n * @param {string} string - source string\n * @param {number} padding - pad the resulting array to multiple of \"padding\" bytes. Additional bytes are filled with 0x20 (ASCII space)\n *\n * @return new byteOffset of resulting dataView\n */\nexport function copyPaddedStringToDataView(\n dataView: DataView | null,\n byteOffset: number,\n string: string,\n padding: number\n): number {\n const textEncoder = new TextEncoder();\n // PERFORMANCE IDEA: We encode twice, once to get size and once to store\n // PERFORMANCE IDEA: Use TextEncoder.encodeInto() to avoid temporary copy\n const stringBuffer = textEncoder.encode(string);\n\n byteOffset = copyPaddedArrayBufferToDataView(dataView, byteOffset, stringBuffer, padding);\n\n return byteOffset;\n}\n","// Note: These were broken out from gltf loader...\n// eslint-disable-next-line complexity\n\n// PERFORMANCE IDEA: No need to copy string twice...\nexport function padStringToByteAlignment(string, byteAlignment) {\n const length = string.length;\n const paddedLength = Math.ceil(length / byteAlignment) * byteAlignment; // Round up to the required alignment\n const padding = paddedLength - length;\n let whitespace = '';\n for (let i = 0; i < padding; ++i) {\n whitespace += ' ';\n }\n return string + whitespace;\n}\n\nexport function copyStringToDataView(dataView, byteOffset, string, byteLength) {\n if (dataView) {\n for (let i = 0; i < byteLength; i++) {\n dataView.setUint8(byteOffset + i, string.charCodeAt(i));\n }\n }\n return byteOffset + byteLength;\n}\n\nexport function copyBinaryToDataView(dataView, byteOffset, binary, byteLength) {\n if (dataView) {\n for (let i = 0; i < byteLength; i++) {\n dataView.setUint8(byteOffset + i, binary[i]);\n }\n }\n return byteOffset + byteLength;\n}\n","// TextDecoder iterators\n// TextDecoder will keep any partial undecoded bytes between calls to `decode`\n\nexport async function* makeTextDecoderIterator(\n arrayBufferIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>,\n options: TextDecoderOptions = {}\n): AsyncIterable<string> {\n const textDecoder = new TextDecoder(undefined, options);\n for await (const arrayBuffer of arrayBufferIterator) {\n yield typeof arrayBuffer === 'string'\n ? arrayBuffer\n : textDecoder.decode(arrayBuffer, {stream: true});\n }\n}\n\n// TextEncoder iterator\n// TODO - this is not useful unless min chunk size is given\n// TextEncoder will keep any partial undecoded bytes between calls to `encode`\n// If iterator does not yield strings, assume arrayBuffer and return unencoded\n\nexport async function* makeTextEncoderIterator(\n textIterator: AsyncIterable<string> | Iterable<ArrayBuffer>\n): AsyncIterable<ArrayBuffer> {\n const textEncoder = new TextEncoder();\n for await (const text of textIterator) {\n yield typeof text === 'string' ? textEncoder.encode(text) : text;\n }\n}\n\n/**\n * @param textIterator async iterable yielding strings\n * @returns an async iterable over lines\n * See http://2ality.com/2018/04/async-iter-nodejs.html\n */\n\nexport async function* makeLineIterator(\n textIterator: AsyncIterable<string>\n): AsyncIterable<string> {\n let previous = '';\n for await (const textChunk of textIterator) {\n previous += textChunk;\n let eolIndex;\n while ((eolIndex = previous.indexOf('\\n')) >= 0) {\n // line includes the EOL\n const line = previous.slice(0, eolIndex + 1);\n previous = previous.slice(eolIndex + 1);\n yield line;\n }\n }\n\n if (previous.length > 0) {\n yield previous;\n }\n}\n\n/**\n * @param lineIterator async iterable yielding lines\n * @returns async iterable yielding numbered lines\n *\n * See http://2ality.com/2018/04/async-iter-nodejs.html\n */\nexport async function* makeNumberedLineIterator(\n lineIterator: AsyncIterable<string>\n): AsyncIterable<{counter: number; line: string}> {\n let counter = 1;\n for await (const line of lineIterator) {\n yield {counter, line};\n counter++;\n }\n}\n","import {concatenateArrayBuffers} from '../binary-utils/array-buffer-utils';\n\n// GENERAL UTILITIES\n\n/**\n * Iterate over async iterator, without resetting iterator if end is not reached\n * - forEach intentionally does not reset iterator if exiting loop prematurely\n * so that iteration can continue in a second loop\n * - It is recommended to use a standard for-await as last loop to ensure\n * iterator gets properly reset\n *\n * TODO - optimize using sync iteration if argument is an Iterable?\n *\n * @param iterator\n * @param visitor\n */\nexport async function forEach(iterator, visitor) {\n // eslint-disable-next-line\n while (true) {\n const {done, value} = await iterator.next();\n if (done) {\n iterator.return();\n return;\n }\n const cancel = visitor(value);\n if (cancel) {\n return;\n }\n }\n}\n\n// Breaking big data into iterable chunks, concatenating iterable chunks into big data objects\n\n/**\n * Concatenates all data chunks yielded by an (async) iterator\n * This function can e.g. be used to enable atomic parsers to work on (async) iterator inputs\n */\n\nexport async function concatenateArrayBuffersAsync(\n asyncIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>\n): Promise<ArrayBuffer> {\n const arrayBuffers: ArrayBuffer[] = [];\n for await (const chunk of asyncIterator) {\n arrayBuffers.push(chunk);\n }\n return concatenateArrayBuffers(...arrayBuffers);\n}\n\nexport async function concatenateStringsAsync(\n asyncIterator: AsyncIterable<string> | Iterable<string>\n): Promise<string> {\n const strings: string[] = [];\n for await (const chunk of asyncIterator) {\n strings.push(chunk);\n }\n return strings.join('');\n}\n","import {Stats} from '@probe.gl/stats';\n\ntype Handle = any;\ntype DoneFunction = () => any;\ntype GetPriorityFunction = () => number;\ntype RequestResult = {\n done: DoneFunction;\n} | null;\n\n/** RequestScheduler Options */\nexport type RequestSchedulerProps = {\n id?: string;\n throttleRequests?: boolean;\n maxRequests?: number;\n};\n\nconst STAT_QUEUED_REQUESTS = 'Queued Requests';\nconst STAT_ACTIVE_REQUESTS = 'Active Requests';\nconst STAT_CANCELLED_REQUESTS = 'Cancelled Requests';\nconst STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';\nconst STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';\n\nconst DEFAULT_PROPS: Required<RequestSchedulerProps> = {\n id: 'request-scheduler',\n // Specifies if the request scheduler should throttle incoming requests, mainly for comparative testing\n throttleRequests: true,\n // The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.\n maxRequests: 6\n};\n\n/** Tracks one request */\ntype Request = {\n handle: Handle;\n priority: number;\n getPriority: GetPriorityFunction;\n resolve?: (value: any) => any;\n};\n\n/**\n * Used to issue a request, without having them \"deeply queued\" by the browser.\n * @todo - Track requests globally, across multiple servers\n */\nexport default class RequestScheduler {\n readonly props: Required<RequestSchedulerProps>;\n readonly stats: Stats;\n activeRequestCount: number = 0;\n\n /** Tracks the number of active requests and prioritizes/cancels queued requests. */\n private requestQueue: Request[] = [];\n private requestMap: Map<Handle, Promise<RequestResult>> = new Map();\n private deferredUpdate: any = null;\n\n constructor(props: RequestSchedulerProps = {}) {\n this.props = {...DEFAULT_PROPS, ...props};\n\n // Returns the statistics used by the request scheduler.\n this.stats = new Stats({id: this.props.id});\n this.stats.get(STAT_QUEUED_REQUESTS);\n this.stats.get(STAT_ACTIVE_REQUESTS);\n this.stats.get(STAT_CANCELLED_REQUESTS);\n this.stats.get(STAT_QUEUED_REQUESTS_EVER);\n this.stats.get(STAT_ACTIVE_REQUESTS_EVER);\n }\n\n /**\n * Called by an application that wants to issue a request, without having it deeply queued by the browser\n *\n * When the returned promise resolved, it is OK for the application to issue a request.\n * The promise resolves to an object that contains a `done` method.\n * When the application's request has completed (or failed), the application must call the `done` function\n *\n * @param handle\n * @param getPriority will be called when request \"slots\" open up,\n * allowing the caller to update priority or cancel the request\n * Highest priority executes first, priority < 0 cancels the request\n * @returns a promise\n * - resolves to a object (with a `done` field) when the request can be issued without queueing,\n * - resolves to `null` if the request has been cancelled (by the callback return < 0).\n * In this case the application should not issue the request\n */\n scheduleRequest(\n handle: Handle,\n getPriority: GetPriorityFunction = () => 0\n ): Promise<RequestResult> {\n // Allows throttling to be disabled\n if (!this.props.throttleRequests) {\n return Promise.resolve({done: () => {}});\n }\n\n // dedupe\n if (this.requestMap.has(handle)) {\n return this.requestMap.get(handle) as Promise<any>;\n }\n\n const request: Request = {handle, priority: 0, getPriority};\n const promise = new Promise<RequestResult>((resolve) => {\n // @ts-ignore\n request.resolve = resolve;\n return request;\n });\n\n this.requestQueue.push(request);\n this.requestMap.set(handle, promise);\n this._issueNewRequests();\n return promise;\n }\n\n // PRIVATE\n\n _issueRequest(request: Request): Promise<any> {\n const {handle, resolve} = request;\n let isDone = false;\n\n const done = () => {\n // can only be called once\n if (!isDone) {\n isDone = true;\n\n // Stop tracking a request - it has completed, failed, cancelled etc\n this.requestMap.delete(handle);\n this.activeRequestCount--;\n // A slot just freed up, see if any queued requests are waiting\n this._issueNewRequests();\n }\n };\n\n // Track this request\n this.activeRequestCount++;\n\n return resolve ? resolve({done}) : Promise.resolve({done});\n }\n\n /** We check requests asynchronously, to prevent multiple updates */\n _issueNewRequests(): void {\n if (!this.deferredUpdate) {\n this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);\n }\n }\n\n /** Refresh all requests */\n _issueNewRequestsAsync() {\n // TODO - shouldn't we clear the timeout?\n this.deferredUpdate = null;\n\n const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);\n\n if (freeSlots === 0) {\n return;\n }\n\n this._updateAllRequests();\n\n // Resolve pending promises for the top-priority requests\n for (let i = 0; i < freeSlots; ++i) {\n const request = this.requestQueue.shift();\n if (request) {\n this._issueRequest(request); // eslint-disable-line @typescript-eslint/no-floating-promises\n }\n }\n\n // Uncomment to debug\n // console.log(`${freeSlots} free slots, ${this.requestQueue.length} queued requests`);\n }\n\n /** Ensure all requests have updated priorities, and that no longer valid requests are cancelled */\n _updateAllRequests() {\n const requestQueue = this.requestQueue;\n for (let i = 0; i < requestQueue.length; ++i) {\n const request = requestQueue[i];\n if (!this._updateRequest(request)) {\n // Remove the element and make sure to adjust the counter to account for shortened array\n requestQueue.splice(i, 1);\n this.requestMap.delete(request.handle);\n i--;\n }\n }\n\n // Sort the remaining requests based on priority\n requestQueue.sort((a, b) => a.priority - b.priority);\n }\n\n /** Update a single request by calling the callback */\n _updateRequest(request) {\n request.priority = request.getPriority(request.handle); // eslint-disable-line callback-return\n\n // by returning a negative priority, the callback cancels the request\n if (request.priority < 0) {\n request.resolve(null);\n return false;\n }\n return true;\n }\n}\n","// Simple file alias mechanisms for tests.\n\nlet pathPrefix = '';\nconst fileAliases: {[aliasPath: string]: string} = {};\n\n/*\n * Set a relative path prefix\n */\nexport function setPathPrefix(prefix: string): void {\n pathPrefix = prefix;\n}\n\n/*\n * Get the relative path prefix\n */\nexport function getPathPrefix(): string {\n return pathPrefix;\n}\n\n/**\n *\n * @param aliases\n *\n * Note: addAliases are an experimental export, they are only for testing of loaders.gl loaders\n * not intended as a generic aliasing mechanism\n */\nexport function addAliases(aliases: {[aliasPath: string]: string}): void {\n Object.assign(fileAliases, aliases);\n}\n\n/**\n * Resolves aliases and adds path-prefix to paths\n */\nexport function resolvePath(filename: string): string {\n for (const alias in fileAliases) {\n if (filename.startsWith(alias)) {\n const replacement = fileAliases[alias];\n filename = filename.replace(alias, replacement);\n }\n }\n if (!filename.startsWith('http://') && !filename.startsWith('https://')) {\n filename = `${pathPrefix}${filename}`;\n }\n return filename;\n}\n","import type {LoaderWithParser} from './types';\n\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n\n/**\n * A JSON Micro loader (minimal bundle size)\n * Alternative to `@loaders.gl/json`\n */\nexport const JSONLoader = {\n name: 'JSON',\n id: 'json',\n module: 'json',\n version: VERSION,\n extensions: ['json', 'geojson'],\n mimeTypes: ['application/json'],\n category: 'json',\n text: true,\n parseTextSync,\n parse: async (arrayBuffer) => parseTextSync(new TextDecoder().decode(arrayBuffer)),\n options: {}\n};\n\n// TODO - deprecated\nfunction parseTextSync(text) {\n return JSON.parse(text);\n}\n\nexport const _typecheckJSONLoader: LoaderWithParser = JSONLoader;\n","// Beginning of a minimal implementation of the Node.js path API, that doesn't pull in big polyfills.\n\n/**\n * Replacement for Node.js path.dirname\n * @param url\n */\nexport function dirname(url: string): string {\n const slashIndex = url && url.lastIndexOf('/');\n return slashIndex >= 0 ? url.substr(0, slashIndex as number) : '';\n}\n\n/**\n * Replacement for Node.js path.join\n * @param parts\n */\nexport function join(...parts: string[]): string {\n const separator = '/';\n parts = parts.map((part, index) => {\n if (index) {\n part = part.replace(new RegExp(`^${separator}`), '');\n }\n if (index !== parts.length - 1) {\n part = part.replace(new RegExp(`${separator}$`), '');\n }\n return part;\n });\n return parts.join(separator);\n}\n","import * as fs from '../node/fs';\nimport {IFileSystem, IRandomAccessReadFileSystem} from '@loaders.gl/loader-utils';\n// import {fetchFile} from \"../fetch/fetch-file\"\n// import {selectLoader} from \"../api/select-loader\";\n\ntype Stat = {\n size: number;\n isDirectory: () => boolean;\n info?: fs.Stats;\n};\n\ntype ReadOptions = {\n buffer?: Buffer;\n offset?: number;\n length?: number;\n position?: number;\n};\n\n/**\n * FileSystem pass-through for Node.js\n * Compatible with BrowserFileSystem.\n * @param options\n */\nexport default class NodeFileSystem implements IFileSystem, IRandomAccessReadFileSystem {\n // implements IFileSystem\n constructor(options: {[key: string]: any}) {\n this.fetch = options._fetch;\n }\n\n async readdir(dirname = '.', options?: {}): Promise<any[]> {\n return await fs.readdir(dirname, options);\n }\n\n async stat(path: string, options?: {}): Promise<Stat> {\n const info = await fs.stat(path, options);\n return {size: Number(info.size), isDirectory: () => false, info};\n }\n\n async fetch(path: string, options: {[key: string]: any}) {\n // Falls back to handle https:/http:/data: etc fetches\n // eslint-disable-next-line\n const fallbackFetch = options.fetch || this.fetch;\n return fallbackFetch(path, options);\n }\n\n // implements IRandomAccessFileSystem\n async open(path: string, flags: string | number, mode?: any): Promise<number> {\n return await fs.open(path, flags);\n }\n\n async close(fd: number): Promise<void> {\n return await fs.close(fd);\n }\n\n async fstat(fd: number): Promise<Stat> {\n const info = await fs.fstat(fd);\n return info;\n }\n\n async read(\n fd: number,\n // @ts-ignore Possibly null\n {buffer = null, offset = 0, length = buffer.byteLength, position = null}: ReadOptions\n ): Promise<{bytesRead: number; buffer: Buffer}> {\n let totalBytesRead = 0;\n // Read in loop until we get required number of bytes\n while (totalBytesRead < length) {\n const {bytesRead} = await fs.read(\n fd,\n buffer,\n offset + totalBytesRead,\n length - totalBytesRead,\n position + totalBytesRead\n );\n totalBytesRead += bytesRead;\n }\n return {bytesRead: totalBytesRead, buffer};\n }\n}\n","import {default as JSONParser} from './json-parser';\nimport JSONPath from '../jsonpath/jsonpath';\n\n/**\n * The `StreamingJSONParser` looks for the first array in the JSON structure.\n * and emits an array of chunks\n */\nexport default class StreamingJSONParser extends JSONParser {\n private jsonPaths: JSONPath[];\n private streamingJsonPath: JSONPath | null = null;\n private streamingArray: any[] | null = null;\n private topLevelObject: object | null = null;\n\n constructor(options: {[key: string]: any} = {}) {\n super();\n const jsonpaths = options.jsonpaths || [];\n this.jsonPaths = jsonpaths.map((jsonpath) => new JSONPath(jsonpath));\n this._extendParser();\n }\n\n /**\n * write REDEFINITION\n * - super.write() chunk to parser\n * - get the contents (so far) of \"topmost-level\" array as batch of rows\n * - clear top-level array\n * - return the batch of rows\\\n */\n write(chunk) {\n super.write(chunk);\n let array: any[] = [];\n if (this.streamingArray) {\n array = [...this.streamingArray];\n this.streamingArray.length = 0;\n }\n return array;\n }\n\n /**\n * Returns a partially formed result object\n * Useful for returning the \"wrapper\" object when array is not top level\n * e.g. GeoJSON\n */\n getPartialResult() {\n return this.topLevelObject;\n }\n\n getStreamingJsonPath() {\n return this.streamingJsonPath;\n }\n\n getStreamingJsonPathAsString() {\n return this.streamingJsonPath && this.streamingJsonPath.toString();\n }\n\n getJsonPath() {\n return this.jsonpath;\n }\n\n // PRIVATE METHODS\n\n /**\n * Checks is this.getJsonPath matches the jsonpaths provided in options\n */\n _matchJSONPath() {\n const currentPath = this.getJsonPath();\n // console.debug(`Testing JSONPath`, currentPath);\n\n // Backwards compatibility, match any array\n // TODO implement using wildcard once that is supported\n if (this.jsonPaths.length === 0) {\n return true;\n }\n\n for (const jsonPath of this.jsonPaths) {\n if (jsonPath.equals(currentPath)) {\n return true;\n }\n }\n\n return false;\n }\n\n _extendParser() {\n // Redefine onopenarray to locate and inject value for top-level array\n this.parser.onopenarray = () => {\n if (!this.streamingArray) {\n if (this._matchJSONPath()) {\n // @ts-ignore\n this.streamingJsonPath = this.getJsonPath().clone();\n this.streamingArray = [];\n this._openArray(this.streamingArray as []);\n return;\n }\n }\n\n this._openArray();\n };\n\n // Redefine onopenarray to inject value for top-level object\n this.parser.onopenobject = (name) => {\n if (!this.topLevelObject) {\n this.topLevelObject = {};\n this._openObject(this.topLevelObject);\n } else {\n this._openObject({});\n }\n if (typeof name !== 'undefined') {\n this.parser.onkey(name);\n }\n };\n }\n}\n","// @ts-nocheck\n\nimport ClarinetParser from '../clarinet/clarinet';\nimport JSONPath from '../jsonpath/jsonpath';\n\n// JSONParser builds a JSON object using the events emitted by the Clarinet parser\n\nexport default class JSONParser {\n jsonpath: JSONPath;\n _parser?: ClarinetParser;\n\n constructor() {\n this.reset();\n this._initializeParser();\n }\n\n reset(): void {\n this.result = undefined;\n this.previousStates = [];\n this.currentState = Object.freeze({container: [], key: null});\n this.jsonpath = new JSONPath();\n }\n\n write(chunk): void {\n this.parser.write(chunk);\n }\n\n close(): void {\n this.parser.close();\n }\n\n // PRIVATE METHODS\n\n _pushOrSet(value): void {\n const {container, key} = this.currentState;\n if (key !== null) {\n container[key] = value;\n this.currentState.key = null;\n } else {\n container.push(value);\n }\n }\n\n _openArray(newContainer = []): void {\n this.jsonpath.push(null);\n this._pushOrSet(newContainer);\n this.previousStates.push(this.currentState);\n this.currentState = {container: newContainer, isArray: true, key: null};\n }\n\n _closeArray(): void {\n this.jsonpath.pop();\n this.currentState = this.previousStates.pop();\n }\n\n _openObject(newContainer = {}): void {\n this.jsonpath.push(null);\n this._pushOrSet(newContainer);\n this.previousStates.push(this.currentState);\n this.currentState = {container: newContainer, isArray: false, key: null};\n }\n\n _closeObject(): void {\n this.jsonpath.pop();\n this.currentState = this.previousStates.pop();\n }\n\n _initializeParser(): void {\n this._parser = new ClarinetParser({\n onready: () => {\n this.jsonpath = new JSONPath();\n this.previousStates.length = 0;\n this.currentState.container.length = 0;\n },\n\n onopenobject: (name) => {\n this._openObject({});\n if (typeof name !== 'undefined') {\n this.parser.onkey(name);\n }\n },\n\n onkey: (name) => {\n this.jsonpath.set(name);\n this.currentState.key = name;\n },\n\n oncloseobject: () => {\n this._closeObject();\n },\n\n onopenarray: () => {\n this._openArray();\n },\n\n onclosearray: () => {\n this._closeArray();\n },\n\n onvalue: (value) => {\n this._pushOrSet(value);\n },\n\n onerror: (error) => {\n throw error;\n },\n\n onend: () => {\n this.result = this.currentState.container.pop();\n }\n });\n }\n\n protected get parser(): ClarinetParser {\n return this._parser as ClarinetParser;\n }\n}\n","import type {Loader, LoaderWithParser} from '@loaders.gl/loader-utils';\nimport type {JSONLoaderOptions} from './json-loader';\nimport {geojsonToBinary} from '@loaders.gl/gis';\nimport parseJSONSync from './lib/parse-json';\nimport parseJSONInBatches from './lib/parse-json-in-batches';\n\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n\nexport type GeoJSONLoaderOptions = JSONLoaderOptions & {\n geojson?: {\n shape?: 'object-row-table';\n };\n gis?: {\n format: 'geojson';\n };\n};\n\nconst DEFAULT_GEOJSON_LOADER_OPTIONS = {\n geojson: {\n shape: 'object-row-table'\n },\n json: {\n jsonpaths: ['$', '$.features']\n },\n gis: {\n format: 'geojson'\n }\n};\n\n/**\n * GeoJSON loader\n */\nexport const GeoJSONWorkerLoader: Loader = {\n name: 'GeoJSON',\n id: 'geojson',\n module: 'geojson',\n version: VERSION,\n worker: true,\n extensions: ['geojson'],\n mimeTypes: ['application/geo+json'],\n category: 'geometry',\n text: true,\n options: DEFAULT_GEOJSON_LOADER_OPTIONS\n};\n\nexport const GeoJSONLoader: LoaderWithParser = {\n ...GeoJSONWorkerLoader,\n parse,\n parseTextSync,\n parseInBatches\n};\n\nasync function parse(arrayBuffer, options) {\n return parseTextSync(new TextDecoder().decode(arrayBuffer), options);\n}\n\nfunction parseTextSync(text, options) {\n // Apps can call the parse method directly, we so apply default options here\n options = {...DEFAULT_GEOJSON_LOADER_OPTIONS, ...options};\n options.json = {...DEFAULT_GEOJSON_LOADER_OPTIONS.geojson, ...options.geojson};\n options.gis = options.gis || {};\n const json = parseJSONSync(text, options);\n switch (options.gis.format) {\n case 'binary':\n return geojsonToBinary(json);\n default:\n return json;\n }\n}\n\nfunction parseInBatches(asyncIterator, options): AsyncIterable<any> {\n // Apps can call the parse method directly, we so apply default options here\n options = {...DEFAULT_GEOJSON_LOADER_OPTIONS, ...options};\n options.json = {...DEFAULT_GEOJSON_LOADER_OPTIONS.geojson, ...options.geojson};\n\n const geojsonIterator = parseJSONInBatches(asyncIterator, options);\n\n switch (options.gis.format) {\n case 'binary':\n return makeBinaryGeometryIterator(geojsonIterator);\n default:\n return geojsonIterator;\n }\n}\n\nasync function* makeBinaryGeometryIterator(geojsonIterator) {\n for await (const batch of geojsonIterator) {\n batch.data = geojsonToBinary(batch.data);\n yield batch;\n }\n}\n","// Types from `@loaders.gl/schema`\n\n// Functions\nexport {geojsonToBinary} from './lib/geojson-to-binary';\nexport {binaryToGeojson, binaryToGeoJson, binaryToGeometry} from './lib/binary-to-geojson';\nexport {transformBinaryCoords, transformGeoJsonCoords} from './lib/transform';\n","import {Feature, GeoJsonProperties} from '@loaders.gl/schema';\nimport type {BinaryFeatures} from '@loaders.gl/schema';\n\nexport type GeojsonToBinaryOptions = {\n coordLength?: number;\n numericPropKeys?: string[];\n PositionDataType?: Function;\n};\n\n/** Convert GeoJSON features to flat binary arrays */\nexport function geojsonToBinary(\n features: Feature[],\n options: GeojsonToBinaryOptions = {}\n): BinaryFeatures {\n const firstPassData = firstPass(features);\n return secondPass(features, firstPassData, {\n coordLength: options.coordLength || firstPassData.coordLength,\n numericPropKeys: options.numericPropKeys || firstPassData.numericPropKeys,\n PositionDataType: options.PositionDataType || Float32Array\n });\n}\n\nexport const TEST_EXPORTS = {\n firstPass,\n secondPass\n};\n\ntype FirstPassData = {\n coordLength: number;\n numericPropKeys: string[];\n\n pointPositionsCount: number;\n pointFeaturesCount: number;\n linePositionsCount: number;\n linePathsCount: number;\n lineFeaturesCount: number;\n polygonPositionsCount: number;\n polygonObjectsCount: number;\n polygonRingsCount: number;\n polygonFeaturesCount: number;\n};\n\n/**\n * Initial scan over GeoJSON features\n * Counts number of coordinates of each geometry type and\n * keeps track of the max coordinate dimensions\n */\n// eslint-disable-next-line complexity, max-statements\nfunction firstPass(features: Feature[]): FirstPassData {\n // Counts the number of _positions_, so [x, y, z] counts as one\n let pointPositionsCount = 0;\n let pointFeaturesCount = 0;\n let linePositionsCount = 0;\n let linePathsCount = 0;\n let lineFeaturesCount = 0;\n let polygonPositionsCount = 0;\n let polygonObjectsCount = 0;\n let polygonRingsCount = 0;\n let polygonFeaturesCount = 0;\n const coordLengths = new Set<number>();\n const numericPropKeys = {};\n\n for (const feature of features) {\n const geometry = feature.geometry;\n switch (geometry.type) {\n case 'Point':\n pointFeaturesCount++;\n pointPositionsCount++;\n coordLengths.add(geometry.coordinates.length);\n break;\n case 'MultiPoint':\n pointFeaturesCount++;\n pointPositionsCount += geometry.coordinates.length;\n for (const point of geometry.coordinates) {\n coordLengths.add(point.length);\n }\n break;\n case 'LineString':\n lineFeaturesCount++;\n linePositionsCount += geometry.coordinates.length;\n linePathsCount++;\n\n for (const coord of geometry.coordinates) {\n coordLengths.add(coord.length);\n }\n break;\n case 'MultiLineString':\n lineFeaturesCount++;\n for (const line of geometry.coordinates) {\n linePositionsCount += line.length;\n linePathsCount++;\n\n // eslint-disable-next-line max-depth\n for (const coord of line) {\n coordLengths.add(coord.length);\n }\n }\n break;\n case 'Polygon':\n polygonFeaturesCount++;\n polygonObjectsCount++;\n polygonRingsCount += geometry.coordinates.length;\n polygonPositionsCount += flatten(geometry.coordinates).length;\n\n for (const coord of flatten(geometry.coordinates)) {\n coordLengths.add(coord.length);\n }\n break;\n case 'MultiPolygon':\n polygonFeaturesCount++;\n for (const polygon of geometry.coordinates) {\n polygonObjectsCount++;\n polygonRingsCount += polygon.length;\n polygonPositionsCount += flatten(polygon).length;\n\n // eslint-disable-next-line max-depth\n for (const coord of flatten(polygon)) {\n coordLengths.add(coord.length);\n }\n }\n break;\n default:\n throw new Error(`Unsupported geometry type: ${geometry.type}`);\n }\n\n if (feature.properties) {\n for (const key in feature.properties) {\n const val = feature.properties[key];\n\n // If property has not been seen before, or if property has been numeric\n // in all previous features, check if numeric in this feature\n // If not numeric, false is stored to prevent rechecking in the future\n numericPropKeys[key] =\n numericPropKeys[key] || numericPropKeys[key] === undefined\n ? isNumeric(val)\n : numericPropKeys[key];\n }\n }\n }\n\n return {\n coordLength: coordLengths.size > 0 ? Math.max(...coordLengths) : 2,\n\n pointPositionsCount,\n pointFeaturesCount,\n linePositionsCount,\n linePathsCount,\n lineFeaturesCount,\n polygonPositionsCount,\n polygonObjectsCount,\n polygonRingsCount,\n polygonFeaturesCount,\n\n // Array of keys whose values are always numeric\n numericPropKeys: Object.keys(numericPropKeys).filter((k) => numericPropKeys[k])\n };\n}\n\n/**\n * Second scan over GeoJSON features\n * Fills coordinates into pre-allocated typed arrays\n */\n// eslint-disable-next-line complexity\nfunction secondPass(\n features,\n firstPassData: FirstPassData,\n options: Required<GeojsonToBinaryOptions>\n) {\n const {\n pointPositionsCount,\n pointFeaturesCount,\n linePositionsCount,\n linePathsCount,\n lineFeaturesCount,\n polygonPositionsCount,\n polygonObjectsCount,\n polygonRingsCount,\n polygonFeaturesCount\n } = firstPassData;\n const {coordLength, numericPropKeys, PositionDataType = Float32Array} = options;\n const GlobalFeatureIdsDataType = features.length > 65535 ? Uint32Array : Uint16Array;\n const points = {\n // @ts-ignore Typescript doesn't like dynamic constructors\n positions: new PositionDataType(pointPositionsCount * coordLength),\n globalFeatureIds: new GlobalFeatureIdsDataType(pointPositionsCount),\n featureIds:\n pointFeaturesCount > 65535\n ? new Uint32Array(pointPositionsCount)\n : new Uint16Array(pointPositionsCount),\n numericProps: {},\n properties: Array<any>(),\n fields: Array<any>()\n };\n const lines = {\n // @ts-ignore Typescript doesn't like dynamic constructors\n positions: new PositionDataType(linePositionsCount * coordLength),\n pathIndices:\n linePositionsCount > 65535\n ? new Uint32Array(linePathsCount + 1)\n : new Uint16Array(linePathsCount + 1),\n globalFeatureIds: new GlobalFeatureIdsDataType(linePositionsCount),\n featureIds:\n lineFeaturesCount > 65535\n ? new Uint32Array(linePositionsCount)\n : new Uint16Array(linePositionsCount),\n numericProps: {},\n properties: Array<any>(),\n fields: Array<any>()\n };\n const polygons = {\n // @ts-ignore Typescript doesn't like dynamic constructors\n positions: new PositionDataType(polygonPositionsCount * coordLength),\n polygonIndices:\n polygonPositionsCount > 65535\n ? new Uint32Array(polygonObjectsCount + 1)\n : new Uint16Array(polygonObjectsCount + 1),\n primitivePolygonIndices:\n polygonPositionsCount > 65535\n ? new Uint32Array(polygonRingsCount + 1)\n : new Uint16Array(polygonRingsCount + 1),\n globalFeatureIds: new GlobalFeatureIdsDataType(polygonPositionsCount),\n featureIds:\n polygonFeaturesCount > 65535\n ? new Uint32Array(polygonPositionsCount)\n : new Uint16Array(polygonPositionsCount),\n numericProps: {},\n properties: Array<any>(),\n fields: Array<any>()\n };\n\n // Instantiate numeric properties arrays; one value per vertex\n for (const object of [points, lines, polygons]) {\n for (const propName of numericPropKeys || []) {\n // If property has been numeric in all previous features in which the property existed, check\n // if numeric in this feature\n object.numericProps[propName] = new Float32Array(object.positions.length / coordLength);\n }\n }\n\n // Set last element of path/polygon indices as positions length\n lines.pathIndices[linePathsCount] = linePositionsCount;\n polygons.polygonIndices[polygonObjectsCount] = polygonPositionsCount;\n polygons.primitivePolygonIndices[polygonRingsCount] = polygonPositionsCount;\n\n const indexMap = {\n pointPosition: 0,\n pointFeature: 0,\n linePosition: 0,\n linePath: 0,\n lineFeature: 0,\n polygonPosition: 0,\n polygonObject: 0,\n polygonRing: 0,\n polygonFeature: 0,\n feature: 0\n };\n\n for (const feature of features) {\n const geometry = feature.geometry;\n const properties: GeoJsonProperties = feature.properties || {};\n\n switch (geometry.type) {\n case 'Point':\n handlePoint(geometry.coordinates, points, indexMap, coordLength, properties);\n points.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.pointFeature++;\n break;\n case 'MultiPoint':\n handleMultiPoint(geometry.coordinates, points, indexMap, coordLength, properties);\n points.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.pointFeature++;\n break;\n case 'LineString':\n handleLineString(geometry.coordinates, lines, indexMap, coordLength, properties);\n lines.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.lineFeature++;\n break;\n case 'MultiLineString':\n handleMultiLineString(geometry.coordinates, lines, indexMap, coordLength, properties);\n lines.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.lineFeature++;\n break;\n case 'Polygon':\n handlePolygon(geometry.coordinates, polygons, indexMap, coordLength, properties);\n polygons.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.polygonFeature++;\n break;\n case 'MultiPolygon':\n handleMultiPolygon(geometry.coordinates, polygons, indexMap, coordLength, properties);\n polygons.properties.push(keepStringProperties(properties, numericPropKeys));\n indexMap.polygonFeature++;\n break;\n default:\n throw new Error('Invalid geometry type');\n }\n\n indexMap.feature++;\n }\n\n // Wrap each array in an accessor object with value and size keys\n return makeAccessorObjects(points, lines, polygons, coordLength);\n}\n\n/** Fills Point coordinates into points object of arrays */\nfunction handlePoint(coords, points, indexMap, coordLength, properties) {\n points.positions.set(coords, indexMap.pointPosition * coordLength);\n points.globalFeatureIds[indexMap.pointPosition] = indexMap.feature;\n points.featureIds[indexMap.pointPosition] = indexMap.pointFeature;\n\n fillNumericProperties(points, properties, indexMap.pointPosition, 1);\n indexMap.pointPosition++;\n}\n\n/** Fills MultiPoint coordinates into points object of arrays */\nfunction handleMultiPoint(coords, points, indexMap, coordLength, properties) {\n for (const point of coords) {\n handlePoint(point, points, indexMap, coordLength, properties);\n }\n}\n\n/** Fills LineString coordinates into lines object of arrays */\nfunction handleLineString(coords, lines, indexMap, coordLength, properties) {\n lines.pathIndices[indexMap.linePath] = indexMap.linePosition;\n indexMap.linePath++;\n\n fillCoords(lines.positions, coords, indexMap.linePosition, coordLength);\n\n const nPositions = coords.length;\n fillNumericProperties(lines, properties, indexMap.linePosition, nPositions);\n\n lines.globalFeatureIds.set(\n new Uint32Array(nPositions).fill(indexMap.feature),\n indexMap.linePosition\n );\n lines.featureIds.set(\n new Uint32Array(nPositions).fill(indexMap.lineFeature),\n indexMap.linePosition\n );\n indexMap.linePosition += nPositions;\n}\n\n/** Fills MultiLineString coordinates into lines object of arrays */\nfunction handleMultiLineString(coords, lines, indexMap, coordLength, properties) {\n for (const line of coords) {\n handleLineString(line, lines, indexMap, coordLength, properties);\n }\n}\n\n/** Fills Polygon coordinates into polygons object of arrays */\nfunction handlePolygon(coords, polygons, indexMap, coordLength, properties) {\n polygons.polygonIndices[indexMap.polygonObject] = indexMap.polygonPosition;\n indexMap.polygonObject++;\n\n for (const ring of coords) {\n polygons.primitivePolygonIndices[indexMap.polygonRing] = indexMap.polygonPosition;\n indexMap.polygonRing++;\n\n fillCoords(polygons.positions, ring, indexMap.polygonPosition, coordLength);\n\n const nPositions = ring.length;\n fillNumericProperties(polygons, properties, indexMap.polygonPosition, nPositions);\n\n polygons.globalFeatureIds.set(\n new Uint32Array(nPositions).fill(indexMap.feature),\n indexMap.polygonPosition\n );\n polygons.featureIds.set(\n new Uint32Array(nPositions).fill(indexMap.polygonFeature),\n indexMap.polygonPosition\n );\n indexMap.polygonPosition += nPositions;\n }\n}\n\n/** Fills MultiPolygon coordinates into polygons object of arrays */\nfunction handleMultiPolygon(coords, polygons, indexMap, coordLength, properties) {\n for (const polygon of coords) {\n handlePolygon(polygon, polygons, indexMap, coordLength, properties);\n }\n}\n\n/** Wrap each array in an accessor object with value and size keys */\nfunction makeAccessorObjects(points, lines, polygons, coordLength): BinaryFeatures {\n const returnObj = {\n points: {\n ...points,\n positions: {value: points.positions, size: coordLength},\n globalFeatureIds: {value: points.globalFeatureIds, size: 1},\n featureIds: {value: points.featureIds, size: 1},\n type: 'Point'\n },\n lines: {\n ...lines,\n pathIndices: {value: lines.pathIndices, size: 1},\n positions: {value: lines.positions, size: coordLength},\n globalFeatureIds: {value: lines.globalFeatureIds, size: 1},\n featureIds: {value: lines.featureIds, size: 1},\n type: 'LineString'\n },\n polygons: {\n ...polygons,\n polygonIndices: {value: polygons.polygonIndices, size: 1},\n primitivePolygonIndices: {value: polygons.primitivePolygonIndices, size: 1},\n positions: {value: polygons.positions, size: coordLength},\n globalFeatureIds: {value: polygons.globalFeatureIds, size: 1},\n featureIds: {value: polygons.featureIds, size: 1},\n type: 'Polygon'\n }\n };\n\n for (const geomType in returnObj) {\n for (const numericProp in returnObj[geomType].numericProps) {\n returnObj[geomType].numericProps[numericProp] = {\n value: returnObj[geomType].numericProps[numericProp],\n size: 1\n };\n }\n }\n\n return returnObj as unknown as BinaryFeatures;\n}\n\n/** Add numeric properties to object */\nfunction fillNumericProperties(object, properties, index, length) {\n for (const numericPropName in object.numericProps) {\n if (numericPropName in properties) {\n object.numericProps[numericPropName].set(\n new Array(length).fill(properties[numericPropName]),\n index\n );\n }\n }\n}\n\n/** Keep string properties in object */\nfunction keepStringProperties(properties, numericKeys: string[]): GeoJsonProperties {\n const props = {};\n for (const key in properties) {\n if (!numericKeys.includes(key)) {\n props[key] = properties[key];\n }\n }\n return props;\n}\n\n/** @param coords is expected to be a list of arrays, each with length 2-3 */\nfunction fillCoords(array, coords, startVertex, coordLength): void {\n let index = startVertex * coordLength;\n for (const coord of coords) {\n array.set(coord, index);\n index += coordLength;\n }\n}\n\n// TODO - how does this work? Different `coordinates` have different nesting\nfunction flatten(arrays): number[][] {\n return [].concat(...arrays);\n}\n\nfunction isNumeric(x: any): boolean {\n return Number.isFinite(x);\n}\n","import type {\n BinaryGeometry,\n BinaryFeatures,\n BinaryGeometryType,\n BinaryPointFeatures,\n BinaryLineFeatures,\n BinaryPolygonFeatures,\n BinaryAttribute\n} from '@loaders.gl/schema';\nimport type {Feature, Geometry, Position, GeoJsonProperties} from '@loaders.gl/schema';\nimport type {\n Point,\n MultiPoint,\n LineString,\n MultiLineString,\n Polygon,\n MultiPolygon\n} from '@loaders.gl/schema';\n\n// Note:L We do not handle GeometryCollection, define a limited Geometry type that always has coordinates.\n// type FeatureGeometry = Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon;\n\ntype BinaryToGeoJsonOptions = {\n type?: BinaryGeometryType;\n globalFeatureId?: number;\n};\n\n/**\n * Convert binary geometry representation to GeoJSON\n * @param data geometry data in binary representation\n * @param options\n * @param options.type Input data type: Point, LineString, or Polygon\n * @param options.featureId Global feature id. If specified, only a single feature is extracted\n * @return GeoJSON objects\n */\nexport function binaryToGeojson(\n data: BinaryFeatures,\n options?: BinaryToGeoJsonOptions\n): Feature[] | Feature {\n const globalFeatureId = options?.globalFeatureId;\n if (globalFeatureId !== undefined) {\n return getSingleFeature(data, globalFeatureId);\n }\n return parseFeatures(data, options?.type);\n}\n\n/** @deprecated use `binaryToGeojson` or `binaryToGeometry` instead */\nexport function binaryToGeoJson(\n data: BinaryGeometry | BinaryFeatures,\n type?: BinaryGeometryType,\n format: 'feature' | 'geometry' = 'feature'\n): Geometry | Feature[] {\n switch (format) {\n case 'feature':\n return parseFeatures(data as BinaryFeatures, type);\n case 'geometry':\n return binaryToGeometry(data as BinaryGeometry);\n default:\n throw new Error(format);\n }\n}\n\n/**\n * Return a single feature from a binary geometry representation as GeoJSON\n * @param data geometry data in binary representation\n * @return GeoJSON feature\n */\nfunction getSingleFeature(data: BinaryFeatures, globalFeatureId: number): Feature {\n const dataArray = normalizeInput(data);\n for (const data of dataArray) {\n let lastIndex = 0;\n let lastValue = data.featureIds.value[0];\n\n // Scan through data until we find matching feature\n for (let i = 0; i < data.featureIds.value.length; i++) {\n const currValue = data.featureIds.value[i];\n if (currValue === lastValue) {\n // eslint-disable-next-line no-continue\n continue;\n }\n if (globalFeatureId === data.globalFeatureIds.value[lastIndex]) {\n return parseFeature(data, lastIndex, i);\n }\n lastIndex = i;\n lastValue = currValue;\n }\n\n if (globalFeatureId === data.globalFeatureIds.value[lastIndex]) {\n return parseFeature(data, lastIndex, data.featureIds.value.length);\n }\n }\n\n throw new Error(`featureId:${globalFeatureId} not found`);\n}\n\nfunction parseFeatures(data: BinaryFeatures, type?: BinaryGeometryType): Feature[] {\n const dataArray = normalizeInput(data, type);\n return parseFeatureCollection(dataArray);\n}\n\n/** Parse input binary data and return a valid GeoJSON geometry object */\nexport function binaryToGeometry(\n data: BinaryGeometry,\n startIndex?: number,\n endIndex?: number\n): Geometry {\n switch (data.type) {\n case 'Point':\n return pointToGeoJson(data, startIndex, endIndex);\n case 'LineString':\n return lineStringToGeoJson(data, startIndex, endIndex);\n case 'Polygon':\n return polygonToGeoJson(data, startIndex, endIndex);\n default:\n const unexpectedInput: never = data;\n throw new Error(`Unsupported geometry type: ${(unexpectedInput as any)?.type}`);\n }\n}\n\ntype BinaryFeature = BinaryPointFeatures | BinaryLineFeatures | BinaryPolygonFeatures;\ntype BinaryFeaturesArray = BinaryFeature[];\n\n// Normalize features\n// Return an array of data objects, each of which have a type key\nfunction normalizeInput(data: BinaryFeatures, type?: BinaryGeometryType): BinaryFeaturesArray {\n const isHeterogeneousType = Boolean(data.points || data.lines || data.polygons);\n\n if (!isHeterogeneousType) {\n // @ts-expect-error This is a legacy check which allowed `data` to be an instance of the values\n // here. Aka the new data.points, data.lines, or data.polygons.\n data.type = type || parseType(data);\n return [data] as BinaryFeaturesArray;\n }\n\n const features: BinaryFeaturesArray = [];\n if (data.points) {\n data.points.type = 'Point';\n features.push(data.points);\n }\n if (data.lines) {\n data.lines.type = 'LineString';\n features.push(data.lines);\n }\n if (data.polygons) {\n data.polygons.type = 'Polygon';\n features.push(data.polygons);\n }\n\n return features;\n}\n\n/** Parse input binary data and return an array of GeoJSON Features */\nfunction parseFeatureCollection(dataArray): Feature[] {\n const features: Feature[] = [];\n for (const data of dataArray) {\n if (data.featureIds.value.length === 0) {\n // eslint-disable-next-line no-continue\n continue;\n }\n let lastIndex = 0;\n let lastValue = data.featureIds.value[0];\n\n // Need to deduce start, end indices of each feature\n for (let i = 0; i < data.featureIds.value.length; i++) {\n const currValue = data.featureIds.value[i];\n if (currValue === lastValue) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n features.push(parseFeature(data, lastIndex, i));\n lastIndex = i;\n lastValue = currValue;\n }\n\n // Last feature\n features.push(parseFeature(data, lastIndex, data.featureIds.value.length));\n }\n return features;\n}\n\n/** Parse input binary data and return a single GeoJSON Feature */\nfunction parseFeature(data, startIndex?: number, endIndex?: number): Feature {\n const geometry = binaryToGeometry(data, startIndex, endIndex);\n const properties = parseProperties(data, startIndex, endIndex);\n const fields = parseFields(data, startIndex, endIndex);\n return {type: 'Feature', geometry, properties, ...fields};\n}\n\n/** Parse input binary data and return an object of fields */\nfunction parseFields(data, startIndex: number = 0, endIndex?: number): GeoJsonProperties {\n return data.fields && data.fields[data.featureIds.value[startIndex]];\n}\n\n/** Parse input binary data and return an object of properties */\nfunction parseProperties(data, startIndex: number = 0, endIndex?: number): GeoJsonProperties {\n const properties = Object.assign({}, data.properties[data.featureIds.value[startIndex]]);\n for (const key in data.numericProps) {\n properties[key] = data.numericProps[key].value[startIndex];\n }\n return properties;\n}\n\n/** Parse binary data of type Polygon */\nfunction polygonToGeoJson(\n data,\n startIndex: number = -Infinity,\n endIndex: number = Infinity\n): Polygon | MultiPolygon {\n const {positions} = data;\n const polygonIndices = data.polygonIndices.value.filter((x) => x >= startIndex && x <= endIndex);\n const primitivePolygonIndices = data.primitivePolygonIndices.value.filter(\n (x) => x >= startIndex && x <= endIndex\n );\n const multi = polygonIndices.length > 2;\n\n // Polygon\n if (!multi) {\n const coordinates: Position[][] = [];\n for (let i = 0; i < primitivePolygonIndices.length - 1; i++) {\n const startRingIndex = primitivePolygonIndices[i];\n const endRingIndex = primitivePolygonIndices[i + 1];\n const ringCoordinates = ringToGeoJson(positions, startRingIndex, endRingIndex);\n coordinates.push(ringCoordinates);\n }\n\n return {type: 'Polygon', coordinates};\n }\n\n // MultiPolygon\n const coordinates: Position[][][] = [];\n for (let i = 0; i < polygonIndices.length - 1; i++) {\n const startPolygonIndex = polygonIndices[i];\n const endPolygonIndex = polygonIndices[i + 1];\n const polygonCoordinates = polygonToGeoJson(\n data,\n startPolygonIndex,\n endPolygonIndex\n ).coordinates;\n coordinates.push(polygonCoordinates as Position[][]);\n }\n\n return {type: 'MultiPolygon', coordinates};\n}\n\n/** Parse binary data of type LineString */\nfunction lineStringToGeoJson(\n data,\n startIndex: number = -Infinity,\n endIndex: number = Infinity\n): LineString | MultiLineString {\n const {positions} = data;\n const pathIndices = data.pathIndices.value.filter((x) => x >= startIndex && x <= endIndex);\n const multi = pathIndices.length > 2;\n\n if (!multi) {\n const coordinates = ringToGeoJson(positions, pathIndices[0], pathIndices[1]);\n return {type: 'LineString', coordinates};\n }\n\n const coordinates: Position[][] = [];\n for (let i = 0; i < pathIndices.length - 1; i++) {\n const ringCoordinates = ringToGeoJson(positions, pathIndices[i], pathIndices[i + 1]);\n coordinates.push(ringCoordinates);\n }\n\n return {type: 'MultiLineString', coordinates};\n}\n\n/** Parse binary data of type Point */\nfunction pointToGeoJson(data, startIndex, endIndex): Point | MultiPoint {\n const {positions} = data;\n const coordinates = ringToGeoJson(positions, startIndex, endIndex);\n const multi = coordinates.length > 1;\n\n if (multi) {\n return {type: 'MultiPoint', coordinates};\n }\n\n return {type: 'Point', coordinates: coordinates[0]};\n}\n\n/**\n * Parse a linear ring of positions to a GeoJSON linear ring\n *\n * @param positions Positions TypedArray\n * @param startIndex Start index to include in ring\n * @param endIndex End index to include in ring\n * @returns GeoJSON ring\n */\nfunction ringToGeoJson(\n positions: BinaryAttribute,\n startIndex?: number,\n endIndex?: number\n): Position[] {\n startIndex = startIndex || 0;\n endIndex = endIndex || positions.value.length / positions.size;\n\n const ringCoordinates: Position[] = [];\n for (let j = startIndex; j < endIndex; j++) {\n const coord = Array<number>();\n for (let k = j * positions.size; k < (j + 1) * positions.size; k++) {\n coord.push(Number(positions.value[k]));\n }\n ringCoordinates.push(coord);\n }\n return ringCoordinates;\n}\n\n// Deduce geometry type of data object\nfunction parseType(data) {\n if (data.pathIndices) {\n return 'LineString';\n }\n\n if (data.polygonIndices) {\n return 'Polygon';\n }\n\n return 'Point';\n}\n","import type {BinaryFeatures, BinaryGeometry} from '@loaders.gl/schema';\n\ntype TransformCoordinate = (coord: number[]) => number[];\n\n/**\n * Apply transformation to every coordinate of binary features\n * @param binaryFeatures binary features\n * @param transformCoordinate Function to call on each coordinate\n * @return Transformed binary features\n */\nexport function transformBinaryCoords(\n binaryFeatures: BinaryFeatures,\n transformCoordinate: TransformCoordinate\n): BinaryFeatures {\n if (binaryFeatures.points) {\n transformBinaryGeometryPositions(binaryFeatures.points, transformCoordinate);\n }\n if (binaryFeatures.lines) {\n transformBinaryGeometryPositions(binaryFeatures.lines, transformCoordinate);\n }\n if (binaryFeatures.polygons) {\n transformBinaryGeometryPositions(binaryFeatures.polygons, transformCoordinate);\n }\n return binaryFeatures;\n}\n\n/** Transform one binary geometry */\nfunction transformBinaryGeometryPositions(binaryGeometry: BinaryGeometry, fn: TransformCoordinate) {\n const {positions} = binaryGeometry;\n for (let i = 0; i < positions.value.length; i += positions.size) {\n // @ts-ignore inclusion of bigint causes problems\n const coord: Array<number> = Array.from(positions.value.subarray(i, i + positions.size));\n const transformedCoord = fn(coord);\n // @ts-ignore typescript typing for .set seems to require bigint?\n positions.value.set(transformedCoord, i);\n }\n}\n\n/**\n * Apply transformation to every coordinate of GeoJSON features\n *\n * @param features Array of GeoJSON features\n * @param fn Function to call on each coordinate\n * @return Transformed GeoJSON features\n */\nexport function transformGeoJsonCoords(\n features: object[],\n fn: (coord: number[]) => number[]\n): object[] {\n for (const feature of features) {\n // @ts-ignore\n feature.geometry.coordinates = coordMap(feature.geometry.coordinates, fn);\n }\n return features;\n}\n\nfunction coordMap(array, fn) {\n if (isCoord(array)) {\n return fn(array);\n }\n\n return array.map((item) => {\n return coordMap(item, fn);\n });\n}\n\nfunction isCoord(array) {\n return Number.isFinite(array[0]) && Number.isFinite(array[1]);\n}\n","import getHiResTimestamp from '../utils/hi-res-timestamp';\nexport default class Stat {\n constructor(name, type) {\n this.name = name;\n this.type = type;\n this.sampleSize = 1;\n this.reset();\n }\n\n setSampleSize(samples) {\n this.sampleSize = samples;\n return this;\n }\n\n incrementCount() {\n this.addCount(1);\n return this;\n }\n\n decrementCount() {\n this.subtractCount(1);\n return this;\n }\n\n addCount(value) {\n this._count += value;\n this._samples++;\n\n this._checkSampling();\n\n return this;\n }\n\n subtractCount(value) {\n this._count -= value;\n this._samples++;\n\n this._checkSampling();\n\n return this;\n }\n\n addTime(time) {\n this._time += time;\n this.lastTiming = time;\n this._samples++;\n\n this._checkSampling();\n\n return this;\n }\n\n timeStart() {\n this._startTime = getHiResTimestamp();\n this._timerPending = true;\n return this;\n }\n\n timeEnd() {\n if (!this._timerPending) {\n return this;\n }\n\n this.addTime(getHiResTimestamp() - this._startTime);\n this._timerPending = false;\n\n this._checkSampling();\n\n return this;\n }\n\n getSampleAverageCount() {\n return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;\n }\n\n getSampleAverageTime() {\n return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;\n }\n\n getSampleHz() {\n return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;\n }\n\n getAverageCount() {\n return this.samples > 0 ? this.count / this.samples : 0;\n }\n\n getAverageTime() {\n return this.samples > 0 ? this.time / this.samples : 0;\n }\n\n getHz() {\n return this.time > 0 ? this.samples / (this.time / 1000) : 0;\n }\n\n reset() {\n this.time = 0;\n this.count = 0;\n this.samples = 0;\n this.lastTiming = 0;\n this.lastSampleTime = 0;\n this.lastSampleCount = 0;\n this._count = 0;\n this._time = 0;\n this._samples = 0;\n this._startTime = 0;\n this._timerPending = false;\n return this;\n }\n\n _checkSampling() {\n if (this._samples === this.sampleSize) {\n this.lastSampleTime = this._time;\n this.lastSampleCount = this._count;\n this.count += this._count;\n this.time += this._time;\n this.samples += this._samples;\n this._time = 0;\n this._count = 0;\n this._samples = 0;\n }\n }\n\n}\n//# sourceMappingURL=stat.js.map","import Stat from './stat';\nexport default class Stats {\n constructor({\n id,\n stats\n }) {\n this.id = id;\n this.stats = {};\n\n this._initializeStats(stats);\n\n Object.seal(this);\n }\n\n get(name, type = 'count') {\n return this._getOrCreate({\n name,\n type\n });\n }\n\n get size() {\n return Object.keys(this.stats).length;\n }\n\n reset() {\n for (const key in this.stats) {\n this.stats[key].reset();\n }\n\n return this;\n }\n\n forEach(fn) {\n for (const key in this.stats) {\n fn(this.stats[key]);\n }\n }\n\n getTable() {\n const table = {};\n this.forEach(stat => {\n table[stat.name] = {\n time: stat.time || 0,\n count: stat.count || 0,\n average: stat.getAverageTime() || 0,\n hz: stat.getHz() || 0\n };\n });\n return table;\n }\n\n _initializeStats(stats = []) {\n stats.forEach(stat => this._getOrCreate(stat));\n }\n\n _getOrCreate(stat) {\n if (!stat || !stat.name) {\n return null;\n }\n\n const {\n name,\n type\n } = stat;\n\n if (!this.stats[name]) {\n if (stat instanceof Stat) {\n this.stats[name] = stat;\n } else {\n this.stats[name] = new Stat(name, type);\n }\n }\n\n return this.stats[name];\n }\n\n}\n//# sourceMappingURL=stats.js.map"],"sourceRoot":""}