@mapbox/mapbox-sdk
Advanced tools
Comparing version 0.7.0 to 0.7.1
# Changelog | ||
## 0.7.1 | ||
- **Fix:** add missing `geometry` key to Tilequery service. | ||
## 0.7.0 | ||
- **Fix:** filter empty waypoints from map matching requests. | ||
- **Fix:** fix url token placement for service with clients. | ||
- **Fix:** filter empty waypoints from map matching requests. | ||
- **Fix:** fix url token placement for service with clients. | ||
@@ -8,0 +12,0 @@ ## 0.6.0 |
{ | ||
"name": "@mapbox/mapbox-sdk", | ||
"version": "0.7.0", | ||
"version": "0.7.1", | ||
"description": "JS SDK for accessing Mapbox APIs", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -51,3 +51,4 @@ 'use strict'; | ||
dedupe: false, | ||
layers: ['egg', 'sandwich'] | ||
layers: ['egg', 'sandwich'], | ||
geometry: 'point' | ||
}); | ||
@@ -65,3 +66,4 @@ expect(tu.requestConfig(tilequery)).toEqual({ | ||
dedupe: false, | ||
layers: ['egg', 'sandwich'] | ||
layers: ['egg', 'sandwich'], | ||
geometry: 'point' | ||
} | ||
@@ -68,0 +70,0 @@ }); |
@@ -47,2 +47,3 @@ 'use strict'; | ||
dedupe: v.boolean, | ||
geometry: v.oneOf('polygon', 'linestring', 'point'), | ||
layers: v.arrayOf(v.string) | ||
@@ -58,3 +59,3 @@ })(config); | ||
}, | ||
query: pick(config, ['radius', 'limit', 'dedupe', 'layers']) | ||
query: pick(config, ['radius', 'limit', 'dedupe', 'layers', 'geometry']) | ||
}); | ||
@@ -61,0 +62,0 @@ }; |
@@ -1,1 +0,1 @@ | ||
(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):global.mapboxSdk=factory()})(this,function(){"use strict";function parseParam(param){var parts=param.match(/\s*(.+)\s*=\s*"?([^"]+)"?/);if(!parts)return null;return{key:parts[1],value:parts[2]}}function parseLink(link){var parts=link.match(/<?([^>]*)>(.*)/);if(!parts)return null;var linkUrl=parts[1];var linkParams=parts[2].split(";");var rel=null;var parsedLinkParams=linkParams.reduce(function(result,param){var parsed=parseParam(param);if(!parsed)return result;if(parsed.key==="rel"){if(!rel){rel=parsed.value}return result}result[parsed.key]=parsed.value;return result},{});if(!rel)return null;return{url:linkUrl,rel:rel,params:parsedLinkParams}}function parseLinkHeader(linkHeader){if(!linkHeader)return{};return linkHeader.split(/,\s*</).reduce(function(result,link){var parsed=parseLink(link);if(!parsed)return result;var splitRel=parsed.rel.split(/\s+/);splitRel.forEach(function(rel){if(!result[rel]){result[rel]={url:parsed.url,params:parsed.params}}});return result},{})}var parseLinkHeader_1=parseLinkHeader;function MapiResponse(request,responseData){this.request=request;this.headers=responseData.headers;this.rawBody=responseData.body;this.statusCode=responseData.statusCode;try{this.body=JSON.parse(responseData.body||"{}")}catch(parseError){this.body=responseData.body}this.links=parseLinkHeader_1(this.headers.link)}MapiResponse.prototype.hasNextPage=function hasNextPage(){return!!this.links.next};MapiResponse.prototype.nextPage=function nextPage(){if(!this.hasNextPage())return null;return this.request._extend({path:this.links.next.url})};var mapiResponse=MapiResponse;var constants={API_ORIGIN:"https://api.mapbox.com",EVENT_PROGRESS_DOWNLOAD:"downloadProgress",EVENT_PROGRESS_UPLOAD:"uploadProgress",EVENT_ERROR:"error",EVENT_RESPONSE:"response",ERROR_HTTP:"HttpError",ERROR_REQUEST_ABORTED:"RequestAbortedError"};function MapiError(options){var errorType=options.type||constants.ERROR_HTTP;var body;if(options.body){try{body=JSON.parse(options.body)}catch(e){body=options.body}}else{body=null}var message=options.message||null;if(!message){if(typeof body==="string"){message=body}else if(body&&typeof body.message==="string"){message=body.message}else if(errorType===constants.ERROR_REQUEST_ABORTED){message="Request aborted"}}this.message=message;this.type=errorType;this.statusCode=options.statusCode||null;this.request=options.request;this.body=body}var mapiError=MapiError;function parseSingleHeader(raw){var boundary=raw.indexOf(":");var name=raw.substring(0,boundary).trim().toLowerCase();var value=raw.substring(boundary+1).trim();return{name:name,value:value}}function parseHeaders(raw){var headers={};if(!raw){return headers}raw.trim().split(/[\r|\n]+/).forEach(function(rawHeader){var parsed=parseSingleHeader(rawHeader);headers[parsed.name]=parsed.value});return headers}var parseHeaders_1=parseHeaders;var requestsUnderway={};function browserAbort(request){var xhr=requestsUnderway[request.id];if(!xhr)return;xhr.abort();delete requestsUnderway[request.id]}function createResponse(request,xhr){return new mapiResponse(request,{body:xhr.response,headers:parseHeaders_1(xhr.getAllResponseHeaders()),statusCode:xhr.status})}function normalizeBrowserProgressEvent(event){var total=event.total;var transferred=event.loaded;var percent=100*transferred/total;return{total:total,transferred:transferred,percent:percent}}function sendRequestXhr(request,xhr){return new Promise(function(resolve,reject){xhr.onprogress=function(event){request.emitter.emit(constants.EVENT_PROGRESS_DOWNLOAD,normalizeBrowserProgressEvent(event))};var file=request.file;if(file){xhr.upload.onprogress=function(event){request.emitter.emit(constants.EVENT_PROGRESS_UPLOAD,normalizeBrowserProgressEvent(event))}}xhr.onerror=function(error){reject(error)};xhr.onabort=function(){var mapiError$$1=new mapiError({request:request,type:constants.ERROR_REQUEST_ABORTED});reject(mapiError$$1)};xhr.onload=function(){delete requestsUnderway[request.id];if(xhr.status<200||xhr.status>=400){var mapiError$$1=new mapiError({request:request,body:xhr.response,statusCode:xhr.status});reject(mapiError$$1);return}resolve(xhr)};var body=request.body;if(typeof body==="string"){xhr.send(body)}else if(body){xhr.send(JSON.stringify(body))}else if(file){xhr.send(file)}else{xhr.send()}requestsUnderway[request.id]=xhr}).then(function(xhr){return createResponse(request,xhr)})}function createRequestXhr(request,accessToken){var url=request.url(accessToken);var xhr=new window.XMLHttpRequest;xhr.open(request.method,url);Object.keys(request.headers).forEach(function(key){xhr.setRequestHeader(key,request.headers[key])});return xhr}function browserSend(request){return Promise.resolve().then(function(){var xhr=createRequestXhr(request,request.client.accessToken);return sendRequestXhr(request,xhr)})}var browserLayer={browserAbort:browserAbort,sendRequestXhr:sendRequestXhr,browserSend:browserSend,createRequestXhr:createRequestXhr};var commonjsGlobal=typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports}var base64=createCommonjsModule(function(module,exports){(function(root){var freeExports=exports;var freeModule=module&&module.exports==freeExports&&module;var freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var InvalidCharacterError=function(message){this.message=message};InvalidCharacterError.prototype=new Error;InvalidCharacterError.prototype.name="InvalidCharacterError";var error=function(message){throw new InvalidCharacterError(message)};var TABLE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var REGEX_SPACE_CHARACTERS=/[\t\n\f\r ]/g;var decode=function(input){input=String(input).replace(REGEX_SPACE_CHARACTERS,"");var length=input.length;if(length%4==0){input=input.replace(/==?$/,"");length=input.length}if(length%4==1||/[^+a-zA-Z0-9/]/.test(input)){error("Invalid character: the string to be decoded is not correctly encoded.")}var bitCounter=0;var bitStorage;var buffer;var output="";var position=-1;while(++position<length){buffer=TABLE.indexOf(input.charAt(position));bitStorage=bitCounter%4?bitStorage*64+buffer:buffer;if(bitCounter++%4){output+=String.fromCharCode(255&bitStorage>>(-2*bitCounter&6))}}return output};var encode=function(input){input=String(input);if(/[^\0-\xFF]/.test(input)){error("The string to be encoded contains characters outside of the "+"Latin1 range.")}var padding=input.length%3;var output="";var position=-1;var a;var b;var c;var buffer;var length=input.length-padding;while(++position<length){a=input.charCodeAt(position)<<16;b=input.charCodeAt(++position)<<8;c=input.charCodeAt(++position);buffer=a+b+c;output+=TABLE.charAt(buffer>>18&63)+TABLE.charAt(buffer>>12&63)+TABLE.charAt(buffer>>6&63)+TABLE.charAt(buffer&63)}if(padding==2){a=input.charCodeAt(position)<<8;b=input.charCodeAt(++position);buffer=a+b;output+=TABLE.charAt(buffer>>10)+TABLE.charAt(buffer>>4&63)+TABLE.charAt(buffer<<2&63)+"="}else if(padding==1){buffer=input.charCodeAt(position);output+=TABLE.charAt(buffer>>2)+TABLE.charAt(buffer<<4&63)+"=="}return output};var base64={encode:encode,decode:decode,version:"0.1.0"};if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=base64}else{for(var key in base64){base64.hasOwnProperty(key)&&(freeExports[key]=base64[key])}}}else{root.base64=base64}})(commonjsGlobal)});var tokenCache={};function parseToken(token){if(tokenCache[token]){return tokenCache[token]}var parts=token.split(".");var usage=parts[0];var rawPayload=parts[1];if(!rawPayload){throw new Error("Invalid token")}var parsedPayload=parsePaylod(rawPayload);var result={usage:usage,user:parsedPayload.u};if(has(parsedPayload,"a"))result.authorization=parsedPayload.a;if(has(parsedPayload,"exp"))result.expires=parsedPayload.exp*1e3;if(has(parsedPayload,"iat"))result.created=parsedPayload.iat*1e3;if(has(parsedPayload,"scopes"))result.scopes=parsedPayload.scopes;if(has(parsedPayload,"client"))result.client=parsedPayload.client;if(has(parsedPayload,"ll"))result.lastLogin=parsedPayload.ll;if(has(parsedPayload,"iu"))result.impersonator=parsedPayload.iu;tokenCache[token]=result;return result}function parsePaylod(rawPayload){try{return JSON.parse(base64.decode(rawPayload))}catch(parseError){throw new Error("Invalid token")}}function has(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}var parseMapboxToken=parseToken;var immutable=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target}var eventemitter3=createCommonjsModule(function(module){var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)prefix=false}function EE(fn,context,once){this.fn=fn;this.context=context;this.once=once||false}function addListener(emitter,event,fn,context,once){if(typeof fn!=="function"){throw new TypeError("The listener must be a function")}var listener=new EE(fn,context||emitter,once),evt=prefix?prefix+event:event;if(!emitter._events[evt])emitter._events[evt]=listener,emitter._eventsCount++;else if(!emitter._events[evt].fn)emitter._events[evt].push(listener);else emitter._events[evt]=[emitter._events[evt],listener];return emitter}function clearEvent(emitter,evt){if(--emitter._eventsCount===0)emitter._events=new Events;else delete emitter._events[evt]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events){if(has.call(events,name))names.push(prefix?name.slice(1):name)}if(Object.getOwnPropertySymbols){return names.concat(Object.getOwnPropertySymbols(events))}return names};EventEmitter.prototype.listeners=function listeners(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++){ee[i]=handlers[i].fn}return ee};EventEmitter.prototype.listenerCount=function listenerCount(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];if(!listeners)return 0;if(listeners.fn)return 1;return listeners.length};EventEmitter.prototype.emit=function emit(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return false;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){if(listeners.once)this.removeListener(event,listeners.fn,undefined,true);switch(len){case 1:return listeners.fn.call(listeners.context),true;case 2:return listeners.fn.call(listeners.context,a1),true;case 3:return listeners.fn.call(listeners.context,a1,a2),true;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),true;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),true;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),true}for(i=1,args=new Array(len-1);i<len;i++){args[i-1]=arguments[i]}listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++){if(listeners[i].once)this.removeListener(event,listeners[i].fn,undefined,true);switch(len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++){args[j-1]=arguments[j]}listeners[i].fn.apply(listeners[i].context,args)}}}return true};EventEmitter.prototype.on=function on(event,fn,context){return addListener(this,event,fn,context,false)};EventEmitter.prototype.once=function once(event,fn,context){return addListener(this,event,fn,context,true)};EventEmitter.prototype.removeListener=function removeListener(event,fn,context,once){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn){clearEvent(this,evt);return this}var listeners=this._events[evt];if(listeners.fn){if(listeners.fn===fn&&(!once||listeners.once)&&(!context||listeners.context===context)){clearEvent(this,evt)}}else{for(var i=0,events=[],length=listeners.length;i<length;i++){if(listeners[i].fn!==fn||once&&!listeners[i].once||context&&listeners[i].context!==context){events.push(listeners[i])}}if(events.length)this._events[evt]=events.length===1?events[0]:events;else clearEvent(this,evt)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(event){var evt;if(event){evt=prefix?prefix+event:event;if(this._events[evt])clearEvent(this,evt)}else{this._events=new Events;this._eventsCount=0}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=prefix;EventEmitter.EventEmitter=EventEmitter;{module.exports=EventEmitter}});function encodeArray(arrayValue){return arrayValue.map(encodeURIComponent).join(",")}function encodeValue(value){if(Array.isArray(value)){return encodeArray(value)}return encodeURIComponent(String(value))}function appendQueryParam(url,key,value){if(value===false||value===null){return url}var punctuation=/\?/.test(url)?"&":"?";var query=encodeURIComponent(key);if(value!==undefined&&value!==""&&value!==true){query+="="+encodeValue(value)}return""+url+punctuation+query}function appendQueryObject(url,queryObject){if(!queryObject){return url}var result=url;Object.keys(queryObject).forEach(function(key){var value=queryObject[key];if(value===undefined){return}if(Array.isArray(value)){value=value.filter(function(v){return!!v}).join(",")}result=appendQueryParam(result,key,value)});return result}function prependOrigin(url,origin){if(!origin){return url}if(url.slice(0,4)==="http"){return url}var delimiter=url[0]==="/"?"":"/";return""+origin.replace(/\/$/,"")+delimiter+url}function interpolateRouteParams(route,params){if(!params){return route}return route.replace(/\/:([a-zA-Z0-9]+)/g,function(_,paramId){var value=params[paramId];if(value===undefined){throw new Error("Unspecified route parameter "+paramId)}var preppedValue=encodeValue(value);return"/"+preppedValue})}var urlUtils={appendQueryObject:appendQueryObject,appendQueryParam:appendQueryParam,prependOrigin:prependOrigin,interpolateRouteParams:interpolateRouteParams};var requestId=1;function MapiRequest(client,options){if(!client){throw new Error("MapiRequest requires a client")}if(!options||!options.path||!options.method){throw new Error("MapiRequest requires an options object with path and method properties")}var defaultHeaders={};if(options.body){defaultHeaders["content-type"]="application/json"}var headersWithDefaults=immutable(defaultHeaders,options.headers);var headers=Object.keys(headersWithDefaults).reduce(function(memo,name){memo[name.toLowerCase()]=headersWithDefaults[name];return memo},{});this.id=requestId++;this._options=options;this.emitter=new eventemitter3;this.client=client;this.response=null;this.error=null;this.sent=false;this.aborted=false;this.path=options.path;this.method=options.method;this.origin=options.origin||client.origin;this.query=options.query||{};this.params=options.params||{};this.body=options.body||null;this.file=options.file||null;this.headers=headers}MapiRequest.prototype.url=function url(accessToken){var url=urlUtils.prependOrigin(this.path,this.origin);url=urlUtils.appendQueryObject(url,this.query);var routeParams=this.params;var actualAccessToken=accessToken==null?this.client.accessToken:accessToken;if(actualAccessToken){url=urlUtils.appendQueryParam(url,"access_token",actualAccessToken);var accessTokenOwnerId=parseMapboxToken(actualAccessToken).user;routeParams=immutable({ownerId:accessTokenOwnerId},routeParams)}url=urlUtils.interpolateRouteParams(url,routeParams);return url};MapiRequest.prototype.send=function send(){var self=this;if(self.sent){throw new Error("This request has already been sent. Check the response and error properties. Create a new request with clone().")}self.sent=true;return self.client.sendRequest(self).then(function(response){self.response=response;self.emitter.emit(constants.EVENT_RESPONSE,response);return response},function(error){self.error=error;self.emitter.emit(constants.EVENT_ERROR,error);throw error})};MapiRequest.prototype.abort=function abort(){if(this._nextPageRequest){this._nextPageRequest.abort();delete this._nextPageRequest}if(this.response||this.error||this.aborted)return;this.aborted=true;this.client.abortRequest(this)};MapiRequest.prototype.eachPage=function eachPage(callback){var self=this;function handleResponse(response){function getNextPage(){delete self._nextPageRequest;var nextPageRequest=response.nextPage();if(nextPageRequest){self._nextPageRequest=nextPageRequest;getPage(nextPageRequest)}}callback(null,response,getNextPage)}function handleError(error){callback(error,null,function(){})}function getPage(request){request.send().then(handleResponse,handleError)}getPage(this)};MapiRequest.prototype.clone=function clone(){return this._extend()};MapiRequest.prototype._extend=function _extend(options){var extendedOptions=immutable(this._options,options);return new MapiRequest(this.client,extendedOptions)};var mapiRequest=MapiRequest;function MapiClient(options){if(!options||!options.accessToken){throw new Error("Cannot create a client without an access token")}parseMapboxToken(options.accessToken);this.accessToken=options.accessToken;this.origin=options.origin||constants.API_ORIGIN}MapiClient.prototype.createRequest=function createRequest(requestOptions){return new mapiRequest(this,requestOptions)};var mapiClient=MapiClient;function BrowserClient(options){mapiClient.call(this,options)}BrowserClient.prototype=Object.create(mapiClient.prototype);BrowserClient.prototype.constructor=BrowserClient;BrowserClient.prototype.sendRequest=browserLayer.browserSend;BrowserClient.prototype.abortRequest=browserLayer.browserAbort;function createBrowserClient(options){return new BrowserClient(options)}var browserClient=createBrowserClient;var toString=Object.prototype.toString;var isPlainObj=function(x){var prototype;return toString.call(x)==="[object Object]"&&(prototype=Object.getPrototypeOf(x),prototype===null||prototype===Object.getPrototypeOf({}))};var DEFAULT_ERROR_PATH="value";var NEWLINE_INDENT="\n ";var v={};v.assert=function(rootValidator,options){options=options||{};return function(value){var message=validate(rootValidator,value);if(!message){return}var errorMessage=processMessage(message,options);if(options.apiName){errorMessage=options.apiName+": "+errorMessage}throw new Error(errorMessage)}};v.shape=function shape(validatorObj){var validators=objectEntries(validatorObj);return function shapeValidator(value){var validationResult=validate(v.plainObject,value);if(validationResult){return validationResult}var key,validator;var errorMessages=[];for(var i=0;i<validators.length;i++){key=validators[i].key;validator=validators[i].value;validationResult=validate(validator,value[key]);if(validationResult){errorMessages.push([key].concat(validationResult))}}if(errorMessages.length<2){return errorMessages[0]}return function(options){errorMessages=errorMessages.map(function(message){var key=message[0];var renderedMessage=processMessage(message,options).split("\n").join(NEWLINE_INDENT);return"- "+key+": "+renderedMessage});var objectId=options.path.join(".");var ofPhrase=objectId===DEFAULT_ERROR_PATH?"":" of "+objectId;return"The following properties"+ofPhrase+" have invalid values:"+NEWLINE_INDENT+errorMessages.join(NEWLINE_INDENT)}}};v.strictShape=function strictShape(validatorObj){var shapeValidator=v.shape(validatorObj);return function strictShapeValidator(value){var shapeResult=shapeValidator(value);if(shapeResult){return shapeResult}var invalidKeys=Object.keys(value).reduce(function(memo,valueKey){if(validatorObj[valueKey]===undefined){memo.push(valueKey)}return memo},[]);if(invalidKeys.length!==0){return function(){return"The following keys are invalid: "+invalidKeys.join(", ")}}}};v.arrayOf=function arrayOf(validator){return createArrayValidator(validator)};v.tuple=function tuple(){var validators=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);return createArrayValidator(validators)};function createArrayValidator(validators){var validatingTuple=Array.isArray(validators);var getValidator=function(index){if(validatingTuple){return validators[index]}return validators};return function arrayValidator(value){var validationResult=validate(v.plainArray,value);if(validationResult){return validationResult}if(validatingTuple&&value.length!==validators.length){return"an array with "+validators.length+" items"}for(var i=0;i<value.length;i++){validationResult=validate(getValidator(i),value[i]);if(validationResult){return[i].concat(validationResult)}}}}v.required=function required(validator){function requiredValidator(value){if(value==null){return function(options){return formatErrorMessage(options,isArrayCulprit(options.path)?"cannot be undefined/null.":"is required.")}}return validator.apply(this,arguments)}requiredValidator.__required=true;return requiredValidator};v.oneOfType=function oneOfType(){var validators=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);return function oneOfTypeValidator(value){var messages=validators.map(function(validator){return validate(validator,value)}).filter(Boolean);if(messages.length!==validators.length){return}if(messages.every(function(message){return message.length===1&&typeof message[0]==="string"})){return orList(messages.map(function(m){return m[0]}))}return messages.reduce(function(max,arr){return arr.length>max.length?arr:max})}};v.equal=function equal(compareWith){return function equalValidator(value){if(value!==compareWith){return JSON.stringify(compareWith)}}};v.oneOf=function oneOf(){var options=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);var validators=options.map(function(value){return v.equal(value)});return v.oneOfType.apply(this,validators)};v.range=function range(compareWith){var min=compareWith[0];var max=compareWith[1];return function rangeValidator(value){var validationResult=validate(v.number,value);if(validationResult||value<min||value>max){return"number between "+min+" & "+max+" (inclusive)"}}};v.any=function any(){return};v.boolean=function boolean(value){if(typeof value!=="boolean"){return"boolean"}};v.number=function number(value){if(typeof value!=="number"){return"number"}};v.plainArray=function plainArray(value){if(!Array.isArray(value)){return"array"}};v.plainObject=function plainObject(value){if(!isPlainObj(value)){return"object"}};v.string=function string(value){if(typeof value!=="string"){return"string"}};v.func=function func(value){if(typeof value!=="function"){return"function"}};function validate(validator,value){if(value==null&&!validator.hasOwnProperty("__required")){return}var result=validator(value);if(result){return Array.isArray(result)?result:[result]}}function processMessage(message,options){var len=message.length;var result=message[len-1];var path=message.slice(0,len-1);if(path.length===0){path=[DEFAULT_ERROR_PATH]}options=immutable(options,{path:path});return typeof result==="function"?result(options):formatErrorMessage(options,prettifyResult(result))}function orList(list){if(list.length<2){return list[0]}if(list.length===2){return list.join(" or ")}return list.slice(0,-1).join(", ")+", or "+list.slice(-1)}function prettifyResult(result){return"must be "+addArticle(result)+"."}function addArticle(nounPhrase){if(/^an? /.test(nounPhrase)){return nounPhrase}if(/^[aeiou]/i.test(nounPhrase)){return"an "+nounPhrase}if(/^[a-z]/i.test(nounPhrase)){return"a "+nounPhrase}return nounPhrase}function formatErrorMessage(options,prettyResult){var arrayCulprit=isArrayCulprit(options.path);var output=options.path.join(".")+" "+prettyResult;var prepend=arrayCulprit?"Item at position ":"";return prepend+output}function isArrayCulprit(path){return typeof path[path.length-1]=="number"||typeof path[0]=="number"}function objectEntries(obj){return Object.keys(obj||{}).map(function(key){return{key:key,value:obj[key]}})}v.validate=validate;v.processMessage=processMessage;var lib=v;function file(value){if(typeof window!=="undefined"){if(value instanceof commonjsGlobal.Blob||value instanceof commonjsGlobal.ArrayBuffer){return}return"Blob or ArrayBuffer"}if(typeof value==="string"||value.pipe!==undefined){return}return"Filename or Readable stream"}function assertShape(validatorObj,apiName){return lib.assert(lib.strictShape(validatorObj),apiName)}function date(value){var msg="date";if(typeof value==="boolean"){return msg}try{var date=new Date(value);if(date.getTime&&isNaN(date.getTime())){return msg}}catch(e){return msg}}function coordinates(value){return lib.tuple(lib.number,lib.number)(value)}var validator=immutable(lib,{file:file,date:date,coordinates:coordinates,assertShape:assertShape});function pick(source,keys){var filter=function(key,val){return keys.indexOf(key)!==-1&&val!==undefined};if(typeof keys==="function"){filter=keys}return Object.keys(source).filter(function(key){return filter(key,source[key])}).reduce(function(result,key){result[key]=source[key];return result},{})}var pick_1=pick;function createServiceFactory(ServicePrototype){return function(clientOrConfig){var client;if(mapiClient.prototype.isPrototypeOf(clientOrConfig)){client=clientOrConfig}else{client=browserClient(clientOrConfig)}var service=Object.create(ServicePrototype);service.client=client;return service}}var createServiceFactory_1=createServiceFactory;var Datasets={};Datasets.listDatasets=function(){return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId"})};Datasets.createDataset=function(config){validator.assertShape({name:validator.string,description:validator.string})(config);return this.client.createRequest({method:"POST",path:"/datasets/v1/:ownerId",body:config})};Datasets.getMetadata=function(config){validator.assertShape({datasetId:validator.required(validator.string),description:validator.string})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId",params:config})};Datasets.updateMetadata=function(config){validator.assertShape({datasetId:validator.required(validator.string),name:validator.string,description:validator.string})(config);return this.client.createRequest({method:"PATCH",path:"/datasets/v1/:ownerId/:datasetId",params:pick_1(config,["datasetId"]),body:pick_1(config,["name","description"])})};Datasets.deleteDataset=function(config){validator.assertShape({datasetId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/datasets/v1/:ownerId/:datasetId",params:config})};Datasets.listFeatures=function(config){validator.assertShape({datasetId:validator.required(validator.string),limit:validator.number,start:validator.string})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId/features",params:pick_1(config,["datasetId"]),query:pick_1(config,["limit","start"])})};Datasets.putFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string),feature:validator.required(validator.plainObject)})(config);if(config.feature.id!==undefined&&config.feature.id!==config.featureId){throw new Error("featureId must match the id property of the feature")}return this.client.createRequest({method:"PUT",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:pick_1(config,["datasetId","featureId"]),body:config.feature})};Datasets.getFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:config})};Datasets.deleteFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:config})};var datasets=createServiceFactory_1(Datasets);function objectClean(obj){return pick_1(obj,function(_,val){return val!=null})}var objectClean_1=objectClean;function objectMap(obj,cb){return Object.keys(obj).reduce(function(result,key){result[key]=cb(key,obj[key]);return result},{})}var objectMap_1=objectMap;function stringifyBoolean(obj){return objectMap_1(obj,function(_,value){return typeof value==="boolean"?JSON.stringify(value):value})}var stringifyBooleans=stringifyBoolean;var Directions={};Directions.getDirections=function(config){validator.assertShape({profile:validator.oneOf("driving-traffic","driving","walking","cycling"),waypoints:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),bearing:validator.arrayOf(validator.range([0,360])),radius:validator.oneOfType(validator.number,validator.equal("unlimited")),waypointName:validator.string}))),alternatives:validator.boolean,annotations:validator.arrayOf(validator.oneOf("duration","distance","speed","congestion")),bannerInstructions:validator.boolean,continueStraight:validator.boolean,exclude:validator.string,geometries:validator.string,language:validator.string,overview:validator.string,roundaboutExits:validator.boolean,steps:validator.boolean,voiceInstructions:validator.boolean,voiceUnits:validator.string})(config);config.profile=config.profile||"driving";var path={coordinates:[],approach:[],bearing:[],radius:[],waypointName:[]};var waypointCount=config.waypoints.length;if(waypointCount<2||waypointCount>25){throw new Error("waypoints must include between 2 and 25 DirectionsWaypoints")}config.waypoints.forEach(function(waypoint){path.coordinates.push(waypoint.coordinates[0]+","+waypoint.coordinates[1]);["bearing"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){waypoint[prop]=waypoint[prop].join(",")}});["approach","bearing","radius","waypointName"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){path[prop].push(waypoint[prop])}else{path[prop].push("")}})});["approach","bearing","radius","waypointName"].forEach(function(prop){if(path[prop].every(function(char){return char===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});var query=stringifyBooleans({alternatives:config.alternatives,annotations:config.annotations,banner_instructions:config.bannerInstructions,continue_straight:config.continueStraight,exclude:config.exclude,geometries:config.geometries,language:config.language,overview:config.overview,roundabout_exits:config.roundaboutExits,steps:config.steps,voice_instructions:config.voiceInstructions,voice_units:config.voiceUnits,approaches:path.approach,bearings:path.bearing,radiuses:path.radius,waypoint_names:path.waypointName});return this.client.createRequest({method:"GET",path:"/directions/v5/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var directions=createServiceFactory_1(Directions);var Geocoding={};var featureTypes=["country","region","postcode","district","place","locality","neighborhood","address","poi","poi.landmark"];Geocoding.forwardGeocode=function(config){validator.assertShape({query:validator.required(validator.string),mode:validator.oneOf("mapbox.places","mapbox.places-permanent"),countries:validator.arrayOf(validator.string),proximity:validator.coordinates,types:validator.arrayOf(validator.oneOf(featureTypes)),autocomplete:validator.boolean,bbox:validator.arrayOf(validator.number),limit:validator.number,language:validator.arrayOf(validator.string)})(config);config.mode=config.mode||"mapbox.places";var query=stringifyBooleans(immutable({country:config.countries},pick_1(config,["proximity","types","autocomplete","bbox","limit","language"])));return this.client.createRequest({method:"GET",path:"/geocoding/v5/:mode/:query.json",params:pick_1(config,["mode","query"]),query:query})};Geocoding.reverseGeocode=function(config){validator.assertShape({query:validator.required(validator.coordinates),mode:validator.oneOf("mapbox.places","mapbox.places-permanent"),countries:validator.arrayOf(validator.string),types:validator.arrayOf(validator.oneOf(featureTypes)),bbox:validator.arrayOf(validator.number),limit:validator.number,language:validator.arrayOf(validator.string),reverseMode:validator.oneOf("distance","score")})(config);config.mode=config.mode||"mapbox.places";var query=stringifyBooleans(immutable({country:config.countries},pick_1(config,["country","types","bbox","limit","language","reverseMode"])));return this.client.createRequest({method:"GET",path:"/geocoding/v5/:mode/:query.json",params:pick_1(config,["mode","query"]),query:query})};var geocoding=createServiceFactory_1(Geocoding);var MapMatching={};MapMatching.getMatch=function(config){validator.assertShape({points:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),radius:validator.range([0,50]),isWaypoint:validator.boolean,waypointName:validator.string,timestamp:validator.date}))),profile:validator.oneOf("driving-traffic","driving","walking","cycling"),annotations:validator.arrayOf(validator.oneOf("duration","distance","speed")),geometries:validator.oneOf("geojson","polyline","polyline6"),language:validator.string,overview:validator.oneOf("full","simplified","false"),steps:validator.boolean,tidy:validator.boolean})(config);var pointCount=config.points.length;if(pointCount<2||pointCount>100){throw new Error("points must include between 2 and 100 MapMatchingPoints")}config.profile=config.profile||"driving";var path={coordinates:[],approach:[],radius:[],isWaypoint:[],waypointName:[],timestamp:[]};config.points.forEach(function(obj){path.coordinates.push(obj.coordinates[0]+","+obj.coordinates[1]);if(obj.hasOwnProperty("isWaypoint")&&obj.isWaypoint!=null){path.isWaypoint.push(obj.isWaypoint)}else{path.isWaypoint.push(true)}if(obj.hasOwnProperty("timestamp")&&obj.timestamp!=null){path.timestamp.push(Number(new Date(obj.timestamp)))}else{path.timestamp.push("")}["approach","radius","waypointName"].forEach(function(prop){if(obj.hasOwnProperty(prop)&&obj[prop]!=null){path[prop].push(obj[prop])}else{path[prop].push("")}})});["coordinates","approach","radius","waypointName","timestamp"].forEach(function(prop){if(path[prop].every(function(value){return value===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});path.isWaypoint[0]=true;path.isWaypoint[path.isWaypoint.length-1]=true;if(path.isWaypoint.every(function(value){return value===true})){delete path.isWaypoint}else{path.isWaypoint=path.isWaypoint.map(function(val,i){return val===true?i:""}).filter(function(x){return x===0||Boolean(x)}).join(";")}var body=stringifyBooleans(objectClean_1({annotations:config.annotations,geometries:config.geometries,language:config.language,overview:config.overview,steps:config.steps,tidy:config.tidy,approaches:path.approach,radiuses:path.radius,waypoints:path.isWaypoint,timestamps:path.timestamp,waypoint_names:path.waypointName,coordinates:path.coordinates}));return this.client.createRequest({method:"POST",path:"/matching/v5/mapbox/:profile",params:{profile:config.profile},body:urlUtils.appendQueryObject("",body).substring(1),headers:{"content-type":"application/x-www-form-urlencoded"}})};var mapMatching=createServiceFactory_1(MapMatching);var Matrix={};Matrix.getMatrix=function(config){validator.assertShape({points:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb")}))),profile:validator.oneOf("driving-traffic","driving","walking","cycling"),annotations:validator.arrayOf(validator.oneOf("duration","distance")),sources:validator.oneOfType(validator.equal("all"),validator.arrayOf(validator.number)),destinations:validator.oneOfType(validator.equal("all"),validator.arrayOf(validator.number))})(config);var pointCount=config.points.length;if(pointCount<2||pointCount>100){throw new Error("points must include between 2 and 100 MatrixPoints")}config.profile=config.profile||"driving";var path={coordinates:[],approach:[]};config.points.forEach(function(obj){path.coordinates.push(obj.coordinates[0]+","+obj.coordinates[1]);if(obj.hasOwnProperty("approach")&&obj.approach!=null){path.approach.push(obj.approach)}else{path.approach.push("")}});if(path.approach.every(function(value){return value===""})){delete path.approach}else{path.approach=path.approach.join(";")}var query={sources:Array.isArray(config.sources)?config.sources.join(";"):config.sources,destinations:Array.isArray(config.destinations)?config.destinations.join(";"):config.destinations,approaches:path.approach,annotations:config.annotations&&config.annotations.join(",")};return this.client.createRequest({method:"GET",path:"/directions-matrix/v1/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var matrix=createServiceFactory_1(Matrix);var Optimization={};Optimization.getOptimization=function(config){validator.assertShape({profile:validator.oneOf("driving","walking","cycling"),waypoints:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),bearing:validator.arrayOf(validator.range([0,360])),radius:validator.oneOfType(validator.number,validator.equal("unlimited"))}))),annotations:validator.arrayOf(validator.oneOf("duration","distance","speed")),geometries:validator.oneOf("geojson","polyline","polyline6"),language:validator.string,overview:validator.oneOf("simplified","full","false"),roundtrip:validator.boolean,steps:validator.boolean,source:validator.oneOf("any","first"),destination:validator.oneOf("any","last"),distributions:validator.arrayOf(validator.shape({pickup:validator.number,dropoff:validator.number}))})(config);var path={coordinates:[],approach:[],bearing:[],radius:[],distributions:[]};var waypointCount=config.waypoints.length;if(waypointCount<2||waypointCount>12){throw new Error("waypoints must include between 2 and 12 OptimizationWaypoints")}config.waypoints.forEach(function(waypoint){path.coordinates.push(waypoint.coordinates[0]+","+waypoint.coordinates[1]);["bearing"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){waypoint[prop]=waypoint[prop].join(",")}});["approach","bearing","radius"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){path[prop].push(waypoint[prop])}else{path[prop].push("")}})});if(config.distributions){config.distributions.forEach(function(dist){path.distributions.push(dist.pickup+","+dist.dropoff)})}["approach","bearing","radius","distributions"].forEach(function(prop){if(path[prop].every(function(char){return char===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});var query=stringifyBooleans({geometries:config.geometries,language:config.language,overview:config.overview,roundtrip:config.roundtrip,steps:config.steps,source:config.source,destination:config.destination,distributions:path.distributions,approaches:path.approach,bearings:path.bearing,radiuses:path.radius});return this.client.createRequest({method:"GET",path:"/optimized-trips/v1/mapbox/:profile/:coordinates",params:{profile:config.profile||"driving",coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var optimization=createServiceFactory_1(Optimization);var polyline_1=createCommonjsModule(function(module){var polyline={};function py2_round(value){return Math.floor(Math.abs(value)+.5)*(value>=0?1:-1)}function encode(current,previous,factor){current=py2_round(current*factor);previous=py2_round(previous*factor);var coordinate=current-previous;coordinate<<=1;if(current-previous<0){coordinate=~coordinate}var output="";while(coordinate>=32){output+=String.fromCharCode((32|coordinate&31)+63);coordinate>>=5}output+=String.fromCharCode(coordinate+63);return output}polyline.decode=function(str,precision){var index=0,lat=0,lng=0,coordinates=[],shift=0,result=0,byte=null,latitude_change,longitude_change,factor=Math.pow(10,precision||5);while(index<str.length){byte=null;shift=0;result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);latitude_change=result&1?~(result>>1):result>>1;shift=result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);longitude_change=result&1?~(result>>1):result>>1;lat+=latitude_change;lng+=longitude_change;coordinates.push([lat/factor,lng/factor])}return coordinates};polyline.encode=function(coordinates,precision){if(!coordinates.length){return""}var factor=Math.pow(10,precision||5),output=encode(coordinates[0][0],0,factor)+encode(coordinates[0][1],0,factor);for(var i=1;i<coordinates.length;i++){var a=coordinates[i],b=coordinates[i-1];output+=encode(a[0],b[0],factor);output+=encode(a[1],b[1],factor)}return output};function flipped(coords){var flipped=[];for(var i=0;i<coords.length;i++){flipped.push(coords[i].slice().reverse())}return flipped}polyline.fromGeoJSON=function(geojson,precision){if(geojson&&geojson.type==="Feature"){geojson=geojson.geometry}if(!geojson||geojson.type!=="LineString"){throw new Error("Input must be a GeoJSON LineString")}return polyline.encode(flipped(geojson.coordinates),precision)};polyline.toGeoJSON=function(str,precision){var coords=polyline.decode(str,precision);return{type:"LineString",coordinates:flipped(coords)}};if(module.exports){module.exports=polyline}});var Static={};Static.getStaticImage=function(config){validator.assertShape({ownerId:validator.required(validator.string),styleId:validator.required(validator.string),width:validator.required(validator.range([1,1280])),height:validator.required(validator.range([1,1280])),position:validator.required(validator.oneOfType(validator.oneOf("auto"),validator.strictShape({coordinates:validator.required(validator.coordinates),zoom:validator.required(validator.range([0,20])),bearing:validator.range([0,360]),pitch:validator.range([0,60])}))),overlays:validator.arrayOf(validator.plainObject),highRes:validator.boolean,insertOverlayBeforeLayer:validator.string,attribution:validator.boolean,logo:validator.boolean})(config);var encodedOverlay=(config.overlays||[]).map(function(overlayItem){if(overlayItem.marker){return encodeMarkerOverlay(overlayItem.marker)}if(overlayItem.path){return encodePathOverlay(overlayItem.path)}return encodeGeoJsonOverlay(overlayItem.geoJson)}).join(",");var encodedPosition=encodePosition(config.position);var encodedDimensions=config.width+"x"+config.height;if(config.highRes){encodedDimensions+="@2x"}var preEncodedUrlParts=[encodedOverlay,encodedPosition,encodedDimensions].filter(Boolean).join("/");var query={};if(config.attribution!==undefined){query.attribution=String(config.attribution)}if(config.logo!==undefined){query.logo=String(config.logo)}if(config.insertOverlayBeforeLayer!==undefined){query.before_layer=config.insertOverlayBeforeLayer}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId/static/"+preEncodedUrlParts,params:pick_1(config,["ownerId","styleId"]),query:query})};function encodePosition(position){if(position==="auto")return"auto";return position.coordinates.concat([position.zoom,position.bearing,position.pitch]).filter(Boolean).join(",")}function encodeMarkerOverlay(o){if(o.url){return encodeCustomMarkerOverlay(o)}return encodeSimpleMarkerOverlay(o)}function encodeSimpleMarkerOverlay(o){validator.assertShape({coordinates:validator.required(validator.coordinates),size:validator.oneOf("large","small"),label:validator.string,color:validator.string})(o);var result=o.size==="large"?"pin-l":"pin-s";if(o.label){result+="-"+String(o.label).toLowerCase()}if(o.color){result+="+"+sanitizeHexColor(o.color)}result+="("+o.coordinates.join(",")+")";return result}function encodeCustomMarkerOverlay(o){validator.assertShape({coordinates:validator.required(validator.coordinates),url:validator.required(validator.string)})(o);var result="url-"+encodeURIComponent(o.url);result+="("+o.coordinates.join(",")+")";return result}function encodePathOverlay(o){validator.assertShape({coordinates:validator.required(validator.arrayOf(validator.coordinates)),strokeWidth:validator.number,strokeColor:validator.string,strokeOpacity:validator.number,fillColor:validator.string,fillOpacity:validator.number})(o);if(o.strokeOpacity!==undefined&&o.strokeColor===undefined){throw new Error("strokeOpacity requires strokeColor")}if(o.fillColor!==undefined&&o.strokeColor===undefined){throw new Error("fillColor requires strokeColor")}if(o.fillOpacity!==undefined&&o.fillColor===undefined){throw new Error("fillOpacity requires fillColor")}var result="path";if(o.strokeWidth){result+="-"+o.strokeWidth}if(o.strokeColor){result+="+"+sanitizeHexColor(o.strokeColor)}if(o.strokeOpacity){result+="-"+o.strokeOpacity}if(o.fillColor){result+="+"+sanitizeHexColor(o.fillColor)}if(o.fillOpacity){result+="-"+o.fillOpacity}var reversedCoordinates=o.coordinates.map(function(c){return c.reverse()});var encodedPolyline=polyline_1.encode(reversedCoordinates);result+="("+encodeURIComponent(encodedPolyline)+")";return result}function encodeGeoJsonOverlay(o){validator.assert(validator.required(validator.plainObject))(o);return"geojson("+encodeURIComponent(JSON.stringify(o))+")"}function sanitizeHexColor(color){return color.replace(/^#/,"")}var _static=createServiceFactory_1(Static);var Styles={};Styles.getStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId",params:config})};Styles.createStyle=function(config){validator.assertShape({style:validator.plainObject,ownerId:validator.string})(config);return this.client.createRequest({method:"POST",path:"/styles/v1/:ownerId",params:pick_1(config,["ownerId"]),body:config.style})};Styles.updateStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),style:validator.required(validator.plainObject),lastKnownModification:validator.date,ownerId:validator.string})(config);var headers={};if(config.lastKnownModification){headers["If-Unmodified-Since"]=new Date(config.lastKnownModification).toUTCString()}return this.client.createRequest({method:"PATCH",path:"/styles/v1/:ownerId/:styleId",params:pick_1(config,["styleId","ownerId"]),headers:headers,body:config.style})};Styles.deleteStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"DELETE",path:"/styles/v1/:ownerId/:styleId",params:config})};Styles.listStyles=function(config){config=config||{};validator.assertShape({start:validator.string,ownerId:validator.string})(config);var query={};if(config.start){query.start=config.start}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId",params:pick_1(config,["ownerId"]),query:query})};Styles.putStyleIcon=function(config){validator.assertShape({styleId:validator.required(validator.string),iconId:validator.required(validator.string),file:validator.file,ownerId:validator.string})(config);return this.client.createRequest({method:"PUT",path:"/styles/v1/:ownerId/:styleId/sprite/:iconId",params:pick_1(config,["ownerId","styleId","iconId"]),file:config.file})};Styles.deleteStyleIcon=function(config){validator.assertShape({styleId:validator.required(validator.string),iconId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"DELETE",path:"/styles/v1/:ownerId/:styleId/sprite/:iconId",params:config})};Styles.getStyleSprite=function(config){validator.assertShape({styleId:validator.required(validator.string),format:validator.oneOf("json","png"),highRes:validator.boolean,ownerId:validator.string})(config);var format=config.format||"json";var fileName="sprite"+(config.highRes?"@2x":"")+"."+format;return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId/:fileName",params:immutable(pick_1(config,["ownerId","styleId"]),{fileName:fileName})})};Styles.getFontGlyphRange=function(config){validator.assertShape({fonts:validator.required(validator.oneOfType(validator.string,validator.arrayOf(validator.string))),start:validator.required(validator.number),end:validator.required(validator.number),ownerId:validator.string})(config);var fileName=config.start+"-"+config.end+".pbf";return this.client.createRequest({method:"GET",path:"/fonts/v1/:ownerId/:fontList/:fileName",params:immutable(pick_1(config,["ownerId"]),{fontList:[].concat(config.fonts),fileName:fileName})})};Styles.getEmbeddableHtml=function(config){validator.assertShape({styleId:validator.required(validator.string),scrollZoom:validator.boolean,title:validator.boolean,ownerId:validator.string})(config);var fileName=config.styleId+".html";var query={};if(config.scrollZoom!==undefined){query.zoomwheel=String(config.scrollZoom)}if(config.title!==undefined){query.title=String(config.title)}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:fileName",params:immutable(pick_1(config,["ownerId"]),{fileName:fileName}),query:query})};var styles=createServiceFactory_1(Styles);var Tilequery={};Tilequery.listFeatures=function(config){validator.assertShape({mapIds:validator.required(validator.arrayOf(validator.string)),coordinates:validator.required(validator.coordinates),radius:validator.number,limit:validator.range([1,50]),dedupe:validator.boolean,layers:validator.arrayOf(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/v4/:mapIds/tilequery/:coordinates.json",params:{mapIds:config.mapIds,coordinates:config.coordinates},query:pick_1(config,["radius","limit","dedupe","layers"])})};var tilequery=createServiceFactory_1(Tilequery);var Tilesets={};Tilesets.listTilesets=function(config){validator.assertShape({ownerId:validator.string})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/:ownerId",params:config})};var tilesets=createServiceFactory_1(Tilesets);var Tokens={};Tokens.listTokens=function(){return this.client.createRequest({method:"GET",path:"/tokens/v2/:ownerId"})};Tokens.createToken=function(config){config=config||{};validator.assertShape({note:validator.string,scopes:validator.arrayOf(validator.string),resources:validator.arrayOf(validator.string),allowedUrls:validator.arrayOf(validator.string)})(config);var body={};body.scopes=config.scopes||[];if(config.note!==undefined){body.note=config.note}if(config.resources){body.resources=config.resources}if(config.allowedUrls){body.allowedUrls=config.allowedUrls}return this.client.createRequest({method:"POST",path:"/tokens/v2/:ownerId",params:pick_1(config,["ownerId"]),body:body})};Tokens.createTemporaryToken=function(config){validator.assertShape({expires:validator.required(validator.date),scopes:validator.required(validator.arrayOf(validator.string))})(config);return this.client.createRequest({method:"POST",path:"/tokens/v2/:ownerId",params:pick_1(config,["ownerId"]),body:{expires:new Date(config.expires).toISOString(),scopes:config.scopes}})};Tokens.updateToken=function(config){validator.assertShape({tokenId:validator.required(validator.string),note:validator.string,scopes:validator.arrayOf(validator.string),resources:validator.arrayOf(validator.string),allowedUrls:validator.arrayOf(validator.string)})(config);var body={};if(config.scopes){body.scopes=config.scopes}if(config.note!==undefined){body.note=config.note}if(config.resources||config.resources===null){body.resources=config.resources}if(config.allowedUrls||config.allowedUrls===null){body.allowedUrls=config.allowedUrls}return this.client.createRequest({method:"PATCH",path:"/tokens/v2/:ownerId/:tokenId",params:pick_1(config,["ownerId","tokenId"]),body:body})};Tokens.getToken=function(){return this.client.createRequest({method:"GET",path:"/tokens/v2"})};Tokens.deleteToken=function(config){validator.assertShape({tokenId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/tokens/v2/:ownerId/:tokenId",params:pick_1(config,["ownerId","tokenId"])})};Tokens.listScopes=function(){return this.client.createRequest({method:"GET",path:"/scopes/v1/:ownerId"})};var tokens=createServiceFactory_1(Tokens);var Uploads={};Uploads.listUploads=function(config){validator.assertShape({reverse:validator.boolean})(config);return this.client.createRequest({method:"GET",path:"/uploads/v1/:ownerId",query:config})};Uploads.createUploadCredentials=function(){return this.client.createRequest({method:"POST",path:"/uploads/v1/:ownerId/credentials"})};Uploads.createUpload=function(config){validator.assertShape({mapId:validator.required(validator.string),url:validator.required(validator.string),tilesetName:validator.string})(config);return this.client.createRequest({method:"POST",path:"/uploads/v1/:ownerId",body:{tileset:config.mapId,url:config.url,name:config.tilesetName}})};Uploads.getUpload=function(config){validator.assertShape({uploadId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/uploads/v1/:ownerId/:uploadId",params:config})};Uploads.deleteUpload=function(config){validator.assertShape({uploadId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/uploads/v1/:ownerId/:uploadId",params:config})};var uploads=createServiceFactory_1(Uploads);function mapboxSdk(options){var client=browserClient(options);client.datasets=datasets(client);client.directions=directions(client);client.geocoding=geocoding(client);client.mapMatching=mapMatching(client);client.matrix=matrix(client);client.optimization=optimization(client);client.static=_static(client);client.styles=styles(client);client.tilequery=tilequery(client);client.tilesets=tilesets(client);client.tokens=tokens(client);client.uploads=uploads(client);return client}var bundle=mapboxSdk;return bundle}); | ||
(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):global.mapboxSdk=factory()})(this,function(){"use strict";function parseParam(param){var parts=param.match(/\s*(.+)\s*=\s*"?([^"]+)"?/);if(!parts)return null;return{key:parts[1],value:parts[2]}}function parseLink(link){var parts=link.match(/<?([^>]*)>(.*)/);if(!parts)return null;var linkUrl=parts[1];var linkParams=parts[2].split(";");var rel=null;var parsedLinkParams=linkParams.reduce(function(result,param){var parsed=parseParam(param);if(!parsed)return result;if(parsed.key==="rel"){if(!rel){rel=parsed.value}return result}result[parsed.key]=parsed.value;return result},{});if(!rel)return null;return{url:linkUrl,rel:rel,params:parsedLinkParams}}function parseLinkHeader(linkHeader){if(!linkHeader)return{};return linkHeader.split(/,\s*</).reduce(function(result,link){var parsed=parseLink(link);if(!parsed)return result;var splitRel=parsed.rel.split(/\s+/);splitRel.forEach(function(rel){if(!result[rel]){result[rel]={url:parsed.url,params:parsed.params}}});return result},{})}var parseLinkHeader_1=parseLinkHeader;function MapiResponse(request,responseData){this.request=request;this.headers=responseData.headers;this.rawBody=responseData.body;this.statusCode=responseData.statusCode;try{this.body=JSON.parse(responseData.body||"{}")}catch(parseError){this.body=responseData.body}this.links=parseLinkHeader_1(this.headers.link)}MapiResponse.prototype.hasNextPage=function hasNextPage(){return!!this.links.next};MapiResponse.prototype.nextPage=function nextPage(){if(!this.hasNextPage())return null;return this.request._extend({path:this.links.next.url})};var mapiResponse=MapiResponse;var constants={API_ORIGIN:"https://api.mapbox.com",EVENT_PROGRESS_DOWNLOAD:"downloadProgress",EVENT_PROGRESS_UPLOAD:"uploadProgress",EVENT_ERROR:"error",EVENT_RESPONSE:"response",ERROR_HTTP:"HttpError",ERROR_REQUEST_ABORTED:"RequestAbortedError"};function MapiError(options){var errorType=options.type||constants.ERROR_HTTP;var body;if(options.body){try{body=JSON.parse(options.body)}catch(e){body=options.body}}else{body=null}var message=options.message||null;if(!message){if(typeof body==="string"){message=body}else if(body&&typeof body.message==="string"){message=body.message}else if(errorType===constants.ERROR_REQUEST_ABORTED){message="Request aborted"}}this.message=message;this.type=errorType;this.statusCode=options.statusCode||null;this.request=options.request;this.body=body}var mapiError=MapiError;function parseSingleHeader(raw){var boundary=raw.indexOf(":");var name=raw.substring(0,boundary).trim().toLowerCase();var value=raw.substring(boundary+1).trim();return{name:name,value:value}}function parseHeaders(raw){var headers={};if(!raw){return headers}raw.trim().split(/[\r|\n]+/).forEach(function(rawHeader){var parsed=parseSingleHeader(rawHeader);headers[parsed.name]=parsed.value});return headers}var parseHeaders_1=parseHeaders;var requestsUnderway={};function browserAbort(request){var xhr=requestsUnderway[request.id];if(!xhr)return;xhr.abort();delete requestsUnderway[request.id]}function createResponse(request,xhr){return new mapiResponse(request,{body:xhr.response,headers:parseHeaders_1(xhr.getAllResponseHeaders()),statusCode:xhr.status})}function normalizeBrowserProgressEvent(event){var total=event.total;var transferred=event.loaded;var percent=100*transferred/total;return{total:total,transferred:transferred,percent:percent}}function sendRequestXhr(request,xhr){return new Promise(function(resolve,reject){xhr.onprogress=function(event){request.emitter.emit(constants.EVENT_PROGRESS_DOWNLOAD,normalizeBrowserProgressEvent(event))};var file=request.file;if(file){xhr.upload.onprogress=function(event){request.emitter.emit(constants.EVENT_PROGRESS_UPLOAD,normalizeBrowserProgressEvent(event))}}xhr.onerror=function(error){reject(error)};xhr.onabort=function(){var mapiError$$1=new mapiError({request:request,type:constants.ERROR_REQUEST_ABORTED});reject(mapiError$$1)};xhr.onload=function(){delete requestsUnderway[request.id];if(xhr.status<200||xhr.status>=400){var mapiError$$1=new mapiError({request:request,body:xhr.response,statusCode:xhr.status});reject(mapiError$$1);return}resolve(xhr)};var body=request.body;if(typeof body==="string"){xhr.send(body)}else if(body){xhr.send(JSON.stringify(body))}else if(file){xhr.send(file)}else{xhr.send()}requestsUnderway[request.id]=xhr}).then(function(xhr){return createResponse(request,xhr)})}function createRequestXhr(request,accessToken){var url=request.url(accessToken);var xhr=new window.XMLHttpRequest;xhr.open(request.method,url);Object.keys(request.headers).forEach(function(key){xhr.setRequestHeader(key,request.headers[key])});return xhr}function browserSend(request){return Promise.resolve().then(function(){var xhr=createRequestXhr(request,request.client.accessToken);return sendRequestXhr(request,xhr)})}var browserLayer={browserAbort:browserAbort,sendRequestXhr:sendRequestXhr,browserSend:browserSend,createRequestXhr:createRequestXhr};var commonjsGlobal=typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports}var base64=createCommonjsModule(function(module,exports){(function(root){var freeExports=exports;var freeModule=module&&module.exports==freeExports&&module;var freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var InvalidCharacterError=function(message){this.message=message};InvalidCharacterError.prototype=new Error;InvalidCharacterError.prototype.name="InvalidCharacterError";var error=function(message){throw new InvalidCharacterError(message)};var TABLE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var REGEX_SPACE_CHARACTERS=/[\t\n\f\r ]/g;var decode=function(input){input=String(input).replace(REGEX_SPACE_CHARACTERS,"");var length=input.length;if(length%4==0){input=input.replace(/==?$/,"");length=input.length}if(length%4==1||/[^+a-zA-Z0-9/]/.test(input)){error("Invalid character: the string to be decoded is not correctly encoded.")}var bitCounter=0;var bitStorage;var buffer;var output="";var position=-1;while(++position<length){buffer=TABLE.indexOf(input.charAt(position));bitStorage=bitCounter%4?bitStorage*64+buffer:buffer;if(bitCounter++%4){output+=String.fromCharCode(255&bitStorage>>(-2*bitCounter&6))}}return output};var encode=function(input){input=String(input);if(/[^\0-\xFF]/.test(input)){error("The string to be encoded contains characters outside of the "+"Latin1 range.")}var padding=input.length%3;var output="";var position=-1;var a;var b;var c;var buffer;var length=input.length-padding;while(++position<length){a=input.charCodeAt(position)<<16;b=input.charCodeAt(++position)<<8;c=input.charCodeAt(++position);buffer=a+b+c;output+=TABLE.charAt(buffer>>18&63)+TABLE.charAt(buffer>>12&63)+TABLE.charAt(buffer>>6&63)+TABLE.charAt(buffer&63)}if(padding==2){a=input.charCodeAt(position)<<8;b=input.charCodeAt(++position);buffer=a+b;output+=TABLE.charAt(buffer>>10)+TABLE.charAt(buffer>>4&63)+TABLE.charAt(buffer<<2&63)+"="}else if(padding==1){buffer=input.charCodeAt(position);output+=TABLE.charAt(buffer>>2)+TABLE.charAt(buffer<<4&63)+"=="}return output};var base64={encode:encode,decode:decode,version:"0.1.0"};if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=base64}else{for(var key in base64){base64.hasOwnProperty(key)&&(freeExports[key]=base64[key])}}}else{root.base64=base64}})(commonjsGlobal)});var tokenCache={};function parseToken(token){if(tokenCache[token]){return tokenCache[token]}var parts=token.split(".");var usage=parts[0];var rawPayload=parts[1];if(!rawPayload){throw new Error("Invalid token")}var parsedPayload=parsePaylod(rawPayload);var result={usage:usage,user:parsedPayload.u};if(has(parsedPayload,"a"))result.authorization=parsedPayload.a;if(has(parsedPayload,"exp"))result.expires=parsedPayload.exp*1e3;if(has(parsedPayload,"iat"))result.created=parsedPayload.iat*1e3;if(has(parsedPayload,"scopes"))result.scopes=parsedPayload.scopes;if(has(parsedPayload,"client"))result.client=parsedPayload.client;if(has(parsedPayload,"ll"))result.lastLogin=parsedPayload.ll;if(has(parsedPayload,"iu"))result.impersonator=parsedPayload.iu;tokenCache[token]=result;return result}function parsePaylod(rawPayload){try{return JSON.parse(base64.decode(rawPayload))}catch(parseError){throw new Error("Invalid token")}}function has(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}var parseMapboxToken=parseToken;var immutable=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target}var eventemitter3=createCommonjsModule(function(module){var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)prefix=false}function EE(fn,context,once){this.fn=fn;this.context=context;this.once=once||false}function addListener(emitter,event,fn,context,once){if(typeof fn!=="function"){throw new TypeError("The listener must be a function")}var listener=new EE(fn,context||emitter,once),evt=prefix?prefix+event:event;if(!emitter._events[evt])emitter._events[evt]=listener,emitter._eventsCount++;else if(!emitter._events[evt].fn)emitter._events[evt].push(listener);else emitter._events[evt]=[emitter._events[evt],listener];return emitter}function clearEvent(emitter,evt){if(--emitter._eventsCount===0)emitter._events=new Events;else delete emitter._events[evt]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events){if(has.call(events,name))names.push(prefix?name.slice(1):name)}if(Object.getOwnPropertySymbols){return names.concat(Object.getOwnPropertySymbols(events))}return names};EventEmitter.prototype.listeners=function listeners(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++){ee[i]=handlers[i].fn}return ee};EventEmitter.prototype.listenerCount=function listenerCount(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];if(!listeners)return 0;if(listeners.fn)return 1;return listeners.length};EventEmitter.prototype.emit=function emit(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return false;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){if(listeners.once)this.removeListener(event,listeners.fn,undefined,true);switch(len){case 1:return listeners.fn.call(listeners.context),true;case 2:return listeners.fn.call(listeners.context,a1),true;case 3:return listeners.fn.call(listeners.context,a1,a2),true;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),true;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),true;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),true}for(i=1,args=new Array(len-1);i<len;i++){args[i-1]=arguments[i]}listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++){if(listeners[i].once)this.removeListener(event,listeners[i].fn,undefined,true);switch(len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++){args[j-1]=arguments[j]}listeners[i].fn.apply(listeners[i].context,args)}}}return true};EventEmitter.prototype.on=function on(event,fn,context){return addListener(this,event,fn,context,false)};EventEmitter.prototype.once=function once(event,fn,context){return addListener(this,event,fn,context,true)};EventEmitter.prototype.removeListener=function removeListener(event,fn,context,once){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn){clearEvent(this,evt);return this}var listeners=this._events[evt];if(listeners.fn){if(listeners.fn===fn&&(!once||listeners.once)&&(!context||listeners.context===context)){clearEvent(this,evt)}}else{for(var i=0,events=[],length=listeners.length;i<length;i++){if(listeners[i].fn!==fn||once&&!listeners[i].once||context&&listeners[i].context!==context){events.push(listeners[i])}}if(events.length)this._events[evt]=events.length===1?events[0]:events;else clearEvent(this,evt)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(event){var evt;if(event){evt=prefix?prefix+event:event;if(this._events[evt])clearEvent(this,evt)}else{this._events=new Events;this._eventsCount=0}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=prefix;EventEmitter.EventEmitter=EventEmitter;{module.exports=EventEmitter}});function encodeArray(arrayValue){return arrayValue.map(encodeURIComponent).join(",")}function encodeValue(value){if(Array.isArray(value)){return encodeArray(value)}return encodeURIComponent(String(value))}function appendQueryParam(url,key,value){if(value===false||value===null){return url}var punctuation=/\?/.test(url)?"&":"?";var query=encodeURIComponent(key);if(value!==undefined&&value!==""&&value!==true){query+="="+encodeValue(value)}return""+url+punctuation+query}function appendQueryObject(url,queryObject){if(!queryObject){return url}var result=url;Object.keys(queryObject).forEach(function(key){var value=queryObject[key];if(value===undefined){return}if(Array.isArray(value)){value=value.filter(function(v){return!!v}).join(",")}result=appendQueryParam(result,key,value)});return result}function prependOrigin(url,origin){if(!origin){return url}if(url.slice(0,4)==="http"){return url}var delimiter=url[0]==="/"?"":"/";return""+origin.replace(/\/$/,"")+delimiter+url}function interpolateRouteParams(route,params){if(!params){return route}return route.replace(/\/:([a-zA-Z0-9]+)/g,function(_,paramId){var value=params[paramId];if(value===undefined){throw new Error("Unspecified route parameter "+paramId)}var preppedValue=encodeValue(value);return"/"+preppedValue})}var urlUtils={appendQueryObject:appendQueryObject,appendQueryParam:appendQueryParam,prependOrigin:prependOrigin,interpolateRouteParams:interpolateRouteParams};var requestId=1;function MapiRequest(client,options){if(!client){throw new Error("MapiRequest requires a client")}if(!options||!options.path||!options.method){throw new Error("MapiRequest requires an options object with path and method properties")}var defaultHeaders={};if(options.body){defaultHeaders["content-type"]="application/json"}var headersWithDefaults=immutable(defaultHeaders,options.headers);var headers=Object.keys(headersWithDefaults).reduce(function(memo,name){memo[name.toLowerCase()]=headersWithDefaults[name];return memo},{});this.id=requestId++;this._options=options;this.emitter=new eventemitter3;this.client=client;this.response=null;this.error=null;this.sent=false;this.aborted=false;this.path=options.path;this.method=options.method;this.origin=options.origin||client.origin;this.query=options.query||{};this.params=options.params||{};this.body=options.body||null;this.file=options.file||null;this.headers=headers}MapiRequest.prototype.url=function url(accessToken){var url=urlUtils.prependOrigin(this.path,this.origin);url=urlUtils.appendQueryObject(url,this.query);var routeParams=this.params;var actualAccessToken=accessToken==null?this.client.accessToken:accessToken;if(actualAccessToken){url=urlUtils.appendQueryParam(url,"access_token",actualAccessToken);var accessTokenOwnerId=parseMapboxToken(actualAccessToken).user;routeParams=immutable({ownerId:accessTokenOwnerId},routeParams)}url=urlUtils.interpolateRouteParams(url,routeParams);return url};MapiRequest.prototype.send=function send(){var self=this;if(self.sent){throw new Error("This request has already been sent. Check the response and error properties. Create a new request with clone().")}self.sent=true;return self.client.sendRequest(self).then(function(response){self.response=response;self.emitter.emit(constants.EVENT_RESPONSE,response);return response},function(error){self.error=error;self.emitter.emit(constants.EVENT_ERROR,error);throw error})};MapiRequest.prototype.abort=function abort(){if(this._nextPageRequest){this._nextPageRequest.abort();delete this._nextPageRequest}if(this.response||this.error||this.aborted)return;this.aborted=true;this.client.abortRequest(this)};MapiRequest.prototype.eachPage=function eachPage(callback){var self=this;function handleResponse(response){function getNextPage(){delete self._nextPageRequest;var nextPageRequest=response.nextPage();if(nextPageRequest){self._nextPageRequest=nextPageRequest;getPage(nextPageRequest)}}callback(null,response,getNextPage)}function handleError(error){callback(error,null,function(){})}function getPage(request){request.send().then(handleResponse,handleError)}getPage(this)};MapiRequest.prototype.clone=function clone(){return this._extend()};MapiRequest.prototype._extend=function _extend(options){var extendedOptions=immutable(this._options,options);return new MapiRequest(this.client,extendedOptions)};var mapiRequest=MapiRequest;function MapiClient(options){if(!options||!options.accessToken){throw new Error("Cannot create a client without an access token")}parseMapboxToken(options.accessToken);this.accessToken=options.accessToken;this.origin=options.origin||constants.API_ORIGIN}MapiClient.prototype.createRequest=function createRequest(requestOptions){return new mapiRequest(this,requestOptions)};var mapiClient=MapiClient;function BrowserClient(options){mapiClient.call(this,options)}BrowserClient.prototype=Object.create(mapiClient.prototype);BrowserClient.prototype.constructor=BrowserClient;BrowserClient.prototype.sendRequest=browserLayer.browserSend;BrowserClient.prototype.abortRequest=browserLayer.browserAbort;function createBrowserClient(options){return new BrowserClient(options)}var browserClient=createBrowserClient;var toString=Object.prototype.toString;var isPlainObj=function(x){var prototype;return toString.call(x)==="[object Object]"&&(prototype=Object.getPrototypeOf(x),prototype===null||prototype===Object.getPrototypeOf({}))};var DEFAULT_ERROR_PATH="value";var NEWLINE_INDENT="\n ";var v={};v.assert=function(rootValidator,options){options=options||{};return function(value){var message=validate(rootValidator,value);if(!message){return}var errorMessage=processMessage(message,options);if(options.apiName){errorMessage=options.apiName+": "+errorMessage}throw new Error(errorMessage)}};v.shape=function shape(validatorObj){var validators=objectEntries(validatorObj);return function shapeValidator(value){var validationResult=validate(v.plainObject,value);if(validationResult){return validationResult}var key,validator;var errorMessages=[];for(var i=0;i<validators.length;i++){key=validators[i].key;validator=validators[i].value;validationResult=validate(validator,value[key]);if(validationResult){errorMessages.push([key].concat(validationResult))}}if(errorMessages.length<2){return errorMessages[0]}return function(options){errorMessages=errorMessages.map(function(message){var key=message[0];var renderedMessage=processMessage(message,options).split("\n").join(NEWLINE_INDENT);return"- "+key+": "+renderedMessage});var objectId=options.path.join(".");var ofPhrase=objectId===DEFAULT_ERROR_PATH?"":" of "+objectId;return"The following properties"+ofPhrase+" have invalid values:"+NEWLINE_INDENT+errorMessages.join(NEWLINE_INDENT)}}};v.strictShape=function strictShape(validatorObj){var shapeValidator=v.shape(validatorObj);return function strictShapeValidator(value){var shapeResult=shapeValidator(value);if(shapeResult){return shapeResult}var invalidKeys=Object.keys(value).reduce(function(memo,valueKey){if(validatorObj[valueKey]===undefined){memo.push(valueKey)}return memo},[]);if(invalidKeys.length!==0){return function(){return"The following keys are invalid: "+invalidKeys.join(", ")}}}};v.arrayOf=function arrayOf(validator){return createArrayValidator(validator)};v.tuple=function tuple(){var validators=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);return createArrayValidator(validators)};function createArrayValidator(validators){var validatingTuple=Array.isArray(validators);var getValidator=function(index){if(validatingTuple){return validators[index]}return validators};return function arrayValidator(value){var validationResult=validate(v.plainArray,value);if(validationResult){return validationResult}if(validatingTuple&&value.length!==validators.length){return"an array with "+validators.length+" items"}for(var i=0;i<value.length;i++){validationResult=validate(getValidator(i),value[i]);if(validationResult){return[i].concat(validationResult)}}}}v.required=function required(validator){function requiredValidator(value){if(value==null){return function(options){return formatErrorMessage(options,isArrayCulprit(options.path)?"cannot be undefined/null.":"is required.")}}return validator.apply(this,arguments)}requiredValidator.__required=true;return requiredValidator};v.oneOfType=function oneOfType(){var validators=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);return function oneOfTypeValidator(value){var messages=validators.map(function(validator){return validate(validator,value)}).filter(Boolean);if(messages.length!==validators.length){return}if(messages.every(function(message){return message.length===1&&typeof message[0]==="string"})){return orList(messages.map(function(m){return m[0]}))}return messages.reduce(function(max,arr){return arr.length>max.length?arr:max})}};v.equal=function equal(compareWith){return function equalValidator(value){if(value!==compareWith){return JSON.stringify(compareWith)}}};v.oneOf=function oneOf(){var options=Array.isArray(arguments[0])?arguments[0]:Array.prototype.slice.call(arguments);var validators=options.map(function(value){return v.equal(value)});return v.oneOfType.apply(this,validators)};v.range=function range(compareWith){var min=compareWith[0];var max=compareWith[1];return function rangeValidator(value){var validationResult=validate(v.number,value);if(validationResult||value<min||value>max){return"number between "+min+" & "+max+" (inclusive)"}}};v.any=function any(){return};v.boolean=function boolean(value){if(typeof value!=="boolean"){return"boolean"}};v.number=function number(value){if(typeof value!=="number"){return"number"}};v.plainArray=function plainArray(value){if(!Array.isArray(value)){return"array"}};v.plainObject=function plainObject(value){if(!isPlainObj(value)){return"object"}};v.string=function string(value){if(typeof value!=="string"){return"string"}};v.func=function func(value){if(typeof value!=="function"){return"function"}};function validate(validator,value){if(value==null&&!validator.hasOwnProperty("__required")){return}var result=validator(value);if(result){return Array.isArray(result)?result:[result]}}function processMessage(message,options){var len=message.length;var result=message[len-1];var path=message.slice(0,len-1);if(path.length===0){path=[DEFAULT_ERROR_PATH]}options=immutable(options,{path:path});return typeof result==="function"?result(options):formatErrorMessage(options,prettifyResult(result))}function orList(list){if(list.length<2){return list[0]}if(list.length===2){return list.join(" or ")}return list.slice(0,-1).join(", ")+", or "+list.slice(-1)}function prettifyResult(result){return"must be "+addArticle(result)+"."}function addArticle(nounPhrase){if(/^an? /.test(nounPhrase)){return nounPhrase}if(/^[aeiou]/i.test(nounPhrase)){return"an "+nounPhrase}if(/^[a-z]/i.test(nounPhrase)){return"a "+nounPhrase}return nounPhrase}function formatErrorMessage(options,prettyResult){var arrayCulprit=isArrayCulprit(options.path);var output=options.path.join(".")+" "+prettyResult;var prepend=arrayCulprit?"Item at position ":"";return prepend+output}function isArrayCulprit(path){return typeof path[path.length-1]=="number"||typeof path[0]=="number"}function objectEntries(obj){return Object.keys(obj||{}).map(function(key){return{key:key,value:obj[key]}})}v.validate=validate;v.processMessage=processMessage;var lib=v;function file(value){if(typeof window!=="undefined"){if(value instanceof commonjsGlobal.Blob||value instanceof commonjsGlobal.ArrayBuffer){return}return"Blob or ArrayBuffer"}if(typeof value==="string"||value.pipe!==undefined){return}return"Filename or Readable stream"}function assertShape(validatorObj,apiName){return lib.assert(lib.strictShape(validatorObj),apiName)}function date(value){var msg="date";if(typeof value==="boolean"){return msg}try{var date=new Date(value);if(date.getTime&&isNaN(date.getTime())){return msg}}catch(e){return msg}}function coordinates(value){return lib.tuple(lib.number,lib.number)(value)}var validator=immutable(lib,{file:file,date:date,coordinates:coordinates,assertShape:assertShape});function pick(source,keys){var filter=function(key,val){return keys.indexOf(key)!==-1&&val!==undefined};if(typeof keys==="function"){filter=keys}return Object.keys(source).filter(function(key){return filter(key,source[key])}).reduce(function(result,key){result[key]=source[key];return result},{})}var pick_1=pick;function createServiceFactory(ServicePrototype){return function(clientOrConfig){var client;if(mapiClient.prototype.isPrototypeOf(clientOrConfig)){client=clientOrConfig}else{client=browserClient(clientOrConfig)}var service=Object.create(ServicePrototype);service.client=client;return service}}var createServiceFactory_1=createServiceFactory;var Datasets={};Datasets.listDatasets=function(){return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId"})};Datasets.createDataset=function(config){validator.assertShape({name:validator.string,description:validator.string})(config);return this.client.createRequest({method:"POST",path:"/datasets/v1/:ownerId",body:config})};Datasets.getMetadata=function(config){validator.assertShape({datasetId:validator.required(validator.string),description:validator.string})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId",params:config})};Datasets.updateMetadata=function(config){validator.assertShape({datasetId:validator.required(validator.string),name:validator.string,description:validator.string})(config);return this.client.createRequest({method:"PATCH",path:"/datasets/v1/:ownerId/:datasetId",params:pick_1(config,["datasetId"]),body:pick_1(config,["name","description"])})};Datasets.deleteDataset=function(config){validator.assertShape({datasetId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/datasets/v1/:ownerId/:datasetId",params:config})};Datasets.listFeatures=function(config){validator.assertShape({datasetId:validator.required(validator.string),limit:validator.number,start:validator.string})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId/features",params:pick_1(config,["datasetId"]),query:pick_1(config,["limit","start"])})};Datasets.putFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string),feature:validator.required(validator.plainObject)})(config);if(config.feature.id!==undefined&&config.feature.id!==config.featureId){throw new Error("featureId must match the id property of the feature")}return this.client.createRequest({method:"PUT",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:pick_1(config,["datasetId","featureId"]),body:config.feature})};Datasets.getFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:config})};Datasets.deleteFeature=function(config){validator.assertShape({datasetId:validator.required(validator.string),featureId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/datasets/v1/:ownerId/:datasetId/features/:featureId",params:config})};var datasets=createServiceFactory_1(Datasets);function objectClean(obj){return pick_1(obj,function(_,val){return val!=null})}var objectClean_1=objectClean;function objectMap(obj,cb){return Object.keys(obj).reduce(function(result,key){result[key]=cb(key,obj[key]);return result},{})}var objectMap_1=objectMap;function stringifyBoolean(obj){return objectMap_1(obj,function(_,value){return typeof value==="boolean"?JSON.stringify(value):value})}var stringifyBooleans=stringifyBoolean;var Directions={};Directions.getDirections=function(config){validator.assertShape({profile:validator.oneOf("driving-traffic","driving","walking","cycling"),waypoints:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),bearing:validator.arrayOf(validator.range([0,360])),radius:validator.oneOfType(validator.number,validator.equal("unlimited")),waypointName:validator.string}))),alternatives:validator.boolean,annotations:validator.arrayOf(validator.oneOf("duration","distance","speed","congestion")),bannerInstructions:validator.boolean,continueStraight:validator.boolean,exclude:validator.string,geometries:validator.string,language:validator.string,overview:validator.string,roundaboutExits:validator.boolean,steps:validator.boolean,voiceInstructions:validator.boolean,voiceUnits:validator.string})(config);config.profile=config.profile||"driving";var path={coordinates:[],approach:[],bearing:[],radius:[],waypointName:[]};var waypointCount=config.waypoints.length;if(waypointCount<2||waypointCount>25){throw new Error("waypoints must include between 2 and 25 DirectionsWaypoints")}config.waypoints.forEach(function(waypoint){path.coordinates.push(waypoint.coordinates[0]+","+waypoint.coordinates[1]);["bearing"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){waypoint[prop]=waypoint[prop].join(",")}});["approach","bearing","radius","waypointName"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){path[prop].push(waypoint[prop])}else{path[prop].push("")}})});["approach","bearing","radius","waypointName"].forEach(function(prop){if(path[prop].every(function(char){return char===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});var query=stringifyBooleans({alternatives:config.alternatives,annotations:config.annotations,banner_instructions:config.bannerInstructions,continue_straight:config.continueStraight,exclude:config.exclude,geometries:config.geometries,language:config.language,overview:config.overview,roundabout_exits:config.roundaboutExits,steps:config.steps,voice_instructions:config.voiceInstructions,voice_units:config.voiceUnits,approaches:path.approach,bearings:path.bearing,radiuses:path.radius,waypoint_names:path.waypointName});return this.client.createRequest({method:"GET",path:"/directions/v5/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var directions=createServiceFactory_1(Directions);var Geocoding={};var featureTypes=["country","region","postcode","district","place","locality","neighborhood","address","poi","poi.landmark"];Geocoding.forwardGeocode=function(config){validator.assertShape({query:validator.required(validator.string),mode:validator.oneOf("mapbox.places","mapbox.places-permanent"),countries:validator.arrayOf(validator.string),proximity:validator.coordinates,types:validator.arrayOf(validator.oneOf(featureTypes)),autocomplete:validator.boolean,bbox:validator.arrayOf(validator.number),limit:validator.number,language:validator.arrayOf(validator.string)})(config);config.mode=config.mode||"mapbox.places";var query=stringifyBooleans(immutable({country:config.countries},pick_1(config,["proximity","types","autocomplete","bbox","limit","language"])));return this.client.createRequest({method:"GET",path:"/geocoding/v5/:mode/:query.json",params:pick_1(config,["mode","query"]),query:query})};Geocoding.reverseGeocode=function(config){validator.assertShape({query:validator.required(validator.coordinates),mode:validator.oneOf("mapbox.places","mapbox.places-permanent"),countries:validator.arrayOf(validator.string),types:validator.arrayOf(validator.oneOf(featureTypes)),bbox:validator.arrayOf(validator.number),limit:validator.number,language:validator.arrayOf(validator.string),reverseMode:validator.oneOf("distance","score")})(config);config.mode=config.mode||"mapbox.places";var query=stringifyBooleans(immutable({country:config.countries},pick_1(config,["country","types","bbox","limit","language","reverseMode"])));return this.client.createRequest({method:"GET",path:"/geocoding/v5/:mode/:query.json",params:pick_1(config,["mode","query"]),query:query})};var geocoding=createServiceFactory_1(Geocoding);var MapMatching={};MapMatching.getMatch=function(config){validator.assertShape({points:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),radius:validator.range([0,50]),isWaypoint:validator.boolean,waypointName:validator.string,timestamp:validator.date}))),profile:validator.oneOf("driving-traffic","driving","walking","cycling"),annotations:validator.arrayOf(validator.oneOf("duration","distance","speed")),geometries:validator.oneOf("geojson","polyline","polyline6"),language:validator.string,overview:validator.oneOf("full","simplified","false"),steps:validator.boolean,tidy:validator.boolean})(config);var pointCount=config.points.length;if(pointCount<2||pointCount>100){throw new Error("points must include between 2 and 100 MapMatchingPoints")}config.profile=config.profile||"driving";var path={coordinates:[],approach:[],radius:[],isWaypoint:[],waypointName:[],timestamp:[]};config.points.forEach(function(obj){path.coordinates.push(obj.coordinates[0]+","+obj.coordinates[1]);if(obj.hasOwnProperty("isWaypoint")&&obj.isWaypoint!=null){path.isWaypoint.push(obj.isWaypoint)}else{path.isWaypoint.push(true)}if(obj.hasOwnProperty("timestamp")&&obj.timestamp!=null){path.timestamp.push(Number(new Date(obj.timestamp)))}else{path.timestamp.push("")}["approach","radius","waypointName"].forEach(function(prop){if(obj.hasOwnProperty(prop)&&obj[prop]!=null){path[prop].push(obj[prop])}else{path[prop].push("")}})});["coordinates","approach","radius","waypointName","timestamp"].forEach(function(prop){if(path[prop].every(function(value){return value===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});path.isWaypoint[0]=true;path.isWaypoint[path.isWaypoint.length-1]=true;if(path.isWaypoint.every(function(value){return value===true})){delete path.isWaypoint}else{path.isWaypoint=path.isWaypoint.map(function(val,i){return val===true?i:""}).filter(function(x){return x===0||Boolean(x)}).join(";")}var body=stringifyBooleans(objectClean_1({annotations:config.annotations,geometries:config.geometries,language:config.language,overview:config.overview,steps:config.steps,tidy:config.tidy,approaches:path.approach,radiuses:path.radius,waypoints:path.isWaypoint,timestamps:path.timestamp,waypoint_names:path.waypointName,coordinates:path.coordinates}));return this.client.createRequest({method:"POST",path:"/matching/v5/mapbox/:profile",params:{profile:config.profile},body:urlUtils.appendQueryObject("",body).substring(1),headers:{"content-type":"application/x-www-form-urlencoded"}})};var mapMatching=createServiceFactory_1(MapMatching);var Matrix={};Matrix.getMatrix=function(config){validator.assertShape({points:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb")}))),profile:validator.oneOf("driving-traffic","driving","walking","cycling"),annotations:validator.arrayOf(validator.oneOf("duration","distance")),sources:validator.oneOfType(validator.equal("all"),validator.arrayOf(validator.number)),destinations:validator.oneOfType(validator.equal("all"),validator.arrayOf(validator.number))})(config);var pointCount=config.points.length;if(pointCount<2||pointCount>100){throw new Error("points must include between 2 and 100 MatrixPoints")}config.profile=config.profile||"driving";var path={coordinates:[],approach:[]};config.points.forEach(function(obj){path.coordinates.push(obj.coordinates[0]+","+obj.coordinates[1]);if(obj.hasOwnProperty("approach")&&obj.approach!=null){path.approach.push(obj.approach)}else{path.approach.push("")}});if(path.approach.every(function(value){return value===""})){delete path.approach}else{path.approach=path.approach.join(";")}var query={sources:Array.isArray(config.sources)?config.sources.join(";"):config.sources,destinations:Array.isArray(config.destinations)?config.destinations.join(";"):config.destinations,approaches:path.approach,annotations:config.annotations&&config.annotations.join(",")};return this.client.createRequest({method:"GET",path:"/directions-matrix/v1/mapbox/:profile/:coordinates",params:{profile:config.profile,coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var matrix=createServiceFactory_1(Matrix);var Optimization={};Optimization.getOptimization=function(config){validator.assertShape({profile:validator.oneOf("driving","walking","cycling"),waypoints:validator.required(validator.arrayOf(validator.shape({coordinates:validator.required(validator.coordinates),approach:validator.oneOf("unrestricted","curb"),bearing:validator.arrayOf(validator.range([0,360])),radius:validator.oneOfType(validator.number,validator.equal("unlimited"))}))),annotations:validator.arrayOf(validator.oneOf("duration","distance","speed")),geometries:validator.oneOf("geojson","polyline","polyline6"),language:validator.string,overview:validator.oneOf("simplified","full","false"),roundtrip:validator.boolean,steps:validator.boolean,source:validator.oneOf("any","first"),destination:validator.oneOf("any","last"),distributions:validator.arrayOf(validator.shape({pickup:validator.number,dropoff:validator.number}))})(config);var path={coordinates:[],approach:[],bearing:[],radius:[],distributions:[]};var waypointCount=config.waypoints.length;if(waypointCount<2||waypointCount>12){throw new Error("waypoints must include between 2 and 12 OptimizationWaypoints")}config.waypoints.forEach(function(waypoint){path.coordinates.push(waypoint.coordinates[0]+","+waypoint.coordinates[1]);["bearing"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){waypoint[prop]=waypoint[prop].join(",")}});["approach","bearing","radius"].forEach(function(prop){if(waypoint.hasOwnProperty(prop)&&waypoint[prop]!=null){path[prop].push(waypoint[prop])}else{path[prop].push("")}})});if(config.distributions){config.distributions.forEach(function(dist){path.distributions.push(dist.pickup+","+dist.dropoff)})}["approach","bearing","radius","distributions"].forEach(function(prop){if(path[prop].every(function(char){return char===""})){delete path[prop]}else{path[prop]=path[prop].join(";")}});var query=stringifyBooleans({geometries:config.geometries,language:config.language,overview:config.overview,roundtrip:config.roundtrip,steps:config.steps,source:config.source,destination:config.destination,distributions:path.distributions,approaches:path.approach,bearings:path.bearing,radiuses:path.radius});return this.client.createRequest({method:"GET",path:"/optimized-trips/v1/mapbox/:profile/:coordinates",params:{profile:config.profile||"driving",coordinates:path.coordinates.join(";")},query:objectClean_1(query)})};var optimization=createServiceFactory_1(Optimization);var polyline_1=createCommonjsModule(function(module){var polyline={};function py2_round(value){return Math.floor(Math.abs(value)+.5)*(value>=0?1:-1)}function encode(current,previous,factor){current=py2_round(current*factor);previous=py2_round(previous*factor);var coordinate=current-previous;coordinate<<=1;if(current-previous<0){coordinate=~coordinate}var output="";while(coordinate>=32){output+=String.fromCharCode((32|coordinate&31)+63);coordinate>>=5}output+=String.fromCharCode(coordinate+63);return output}polyline.decode=function(str,precision){var index=0,lat=0,lng=0,coordinates=[],shift=0,result=0,byte=null,latitude_change,longitude_change,factor=Math.pow(10,precision||5);while(index<str.length){byte=null;shift=0;result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);latitude_change=result&1?~(result>>1):result>>1;shift=result=0;do{byte=str.charCodeAt(index++)-63;result|=(byte&31)<<shift;shift+=5}while(byte>=32);longitude_change=result&1?~(result>>1):result>>1;lat+=latitude_change;lng+=longitude_change;coordinates.push([lat/factor,lng/factor])}return coordinates};polyline.encode=function(coordinates,precision){if(!coordinates.length){return""}var factor=Math.pow(10,precision||5),output=encode(coordinates[0][0],0,factor)+encode(coordinates[0][1],0,factor);for(var i=1;i<coordinates.length;i++){var a=coordinates[i],b=coordinates[i-1];output+=encode(a[0],b[0],factor);output+=encode(a[1],b[1],factor)}return output};function flipped(coords){var flipped=[];for(var i=0;i<coords.length;i++){flipped.push(coords[i].slice().reverse())}return flipped}polyline.fromGeoJSON=function(geojson,precision){if(geojson&&geojson.type==="Feature"){geojson=geojson.geometry}if(!geojson||geojson.type!=="LineString"){throw new Error("Input must be a GeoJSON LineString")}return polyline.encode(flipped(geojson.coordinates),precision)};polyline.toGeoJSON=function(str,precision){var coords=polyline.decode(str,precision);return{type:"LineString",coordinates:flipped(coords)}};if(module.exports){module.exports=polyline}});var Static={};Static.getStaticImage=function(config){validator.assertShape({ownerId:validator.required(validator.string),styleId:validator.required(validator.string),width:validator.required(validator.range([1,1280])),height:validator.required(validator.range([1,1280])),position:validator.required(validator.oneOfType(validator.oneOf("auto"),validator.strictShape({coordinates:validator.required(validator.coordinates),zoom:validator.required(validator.range([0,20])),bearing:validator.range([0,360]),pitch:validator.range([0,60])}))),overlays:validator.arrayOf(validator.plainObject),highRes:validator.boolean,insertOverlayBeforeLayer:validator.string,attribution:validator.boolean,logo:validator.boolean})(config);var encodedOverlay=(config.overlays||[]).map(function(overlayItem){if(overlayItem.marker){return encodeMarkerOverlay(overlayItem.marker)}if(overlayItem.path){return encodePathOverlay(overlayItem.path)}return encodeGeoJsonOverlay(overlayItem.geoJson)}).join(",");var encodedPosition=encodePosition(config.position);var encodedDimensions=config.width+"x"+config.height;if(config.highRes){encodedDimensions+="@2x"}var preEncodedUrlParts=[encodedOverlay,encodedPosition,encodedDimensions].filter(Boolean).join("/");var query={};if(config.attribution!==undefined){query.attribution=String(config.attribution)}if(config.logo!==undefined){query.logo=String(config.logo)}if(config.insertOverlayBeforeLayer!==undefined){query.before_layer=config.insertOverlayBeforeLayer}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId/static/"+preEncodedUrlParts,params:pick_1(config,["ownerId","styleId"]),query:query})};function encodePosition(position){if(position==="auto")return"auto";return position.coordinates.concat([position.zoom,position.bearing,position.pitch]).filter(Boolean).join(",")}function encodeMarkerOverlay(o){if(o.url){return encodeCustomMarkerOverlay(o)}return encodeSimpleMarkerOverlay(o)}function encodeSimpleMarkerOverlay(o){validator.assertShape({coordinates:validator.required(validator.coordinates),size:validator.oneOf("large","small"),label:validator.string,color:validator.string})(o);var result=o.size==="large"?"pin-l":"pin-s";if(o.label){result+="-"+String(o.label).toLowerCase()}if(o.color){result+="+"+sanitizeHexColor(o.color)}result+="("+o.coordinates.join(",")+")";return result}function encodeCustomMarkerOverlay(o){validator.assertShape({coordinates:validator.required(validator.coordinates),url:validator.required(validator.string)})(o);var result="url-"+encodeURIComponent(o.url);result+="("+o.coordinates.join(",")+")";return result}function encodePathOverlay(o){validator.assertShape({coordinates:validator.required(validator.arrayOf(validator.coordinates)),strokeWidth:validator.number,strokeColor:validator.string,strokeOpacity:validator.number,fillColor:validator.string,fillOpacity:validator.number})(o);if(o.strokeOpacity!==undefined&&o.strokeColor===undefined){throw new Error("strokeOpacity requires strokeColor")}if(o.fillColor!==undefined&&o.strokeColor===undefined){throw new Error("fillColor requires strokeColor")}if(o.fillOpacity!==undefined&&o.fillColor===undefined){throw new Error("fillOpacity requires fillColor")}var result="path";if(o.strokeWidth){result+="-"+o.strokeWidth}if(o.strokeColor){result+="+"+sanitizeHexColor(o.strokeColor)}if(o.strokeOpacity){result+="-"+o.strokeOpacity}if(o.fillColor){result+="+"+sanitizeHexColor(o.fillColor)}if(o.fillOpacity){result+="-"+o.fillOpacity}var reversedCoordinates=o.coordinates.map(function(c){return c.reverse()});var encodedPolyline=polyline_1.encode(reversedCoordinates);result+="("+encodeURIComponent(encodedPolyline)+")";return result}function encodeGeoJsonOverlay(o){validator.assert(validator.required(validator.plainObject))(o);return"geojson("+encodeURIComponent(JSON.stringify(o))+")"}function sanitizeHexColor(color){return color.replace(/^#/,"")}var _static=createServiceFactory_1(Static);var Styles={};Styles.getStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId",params:config})};Styles.createStyle=function(config){validator.assertShape({style:validator.plainObject,ownerId:validator.string})(config);return this.client.createRequest({method:"POST",path:"/styles/v1/:ownerId",params:pick_1(config,["ownerId"]),body:config.style})};Styles.updateStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),style:validator.required(validator.plainObject),lastKnownModification:validator.date,ownerId:validator.string})(config);var headers={};if(config.lastKnownModification){headers["If-Unmodified-Since"]=new Date(config.lastKnownModification).toUTCString()}return this.client.createRequest({method:"PATCH",path:"/styles/v1/:ownerId/:styleId",params:pick_1(config,["styleId","ownerId"]),headers:headers,body:config.style})};Styles.deleteStyle=function(config){validator.assertShape({styleId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"DELETE",path:"/styles/v1/:ownerId/:styleId",params:config})};Styles.listStyles=function(config){config=config||{};validator.assertShape({start:validator.string,ownerId:validator.string})(config);var query={};if(config.start){query.start=config.start}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId",params:pick_1(config,["ownerId"]),query:query})};Styles.putStyleIcon=function(config){validator.assertShape({styleId:validator.required(validator.string),iconId:validator.required(validator.string),file:validator.file,ownerId:validator.string})(config);return this.client.createRequest({method:"PUT",path:"/styles/v1/:ownerId/:styleId/sprite/:iconId",params:pick_1(config,["ownerId","styleId","iconId"]),file:config.file})};Styles.deleteStyleIcon=function(config){validator.assertShape({styleId:validator.required(validator.string),iconId:validator.required(validator.string),ownerId:validator.string})(config);return this.client.createRequest({method:"DELETE",path:"/styles/v1/:ownerId/:styleId/sprite/:iconId",params:config})};Styles.getStyleSprite=function(config){validator.assertShape({styleId:validator.required(validator.string),format:validator.oneOf("json","png"),highRes:validator.boolean,ownerId:validator.string})(config);var format=config.format||"json";var fileName="sprite"+(config.highRes?"@2x":"")+"."+format;return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:styleId/:fileName",params:immutable(pick_1(config,["ownerId","styleId"]),{fileName:fileName})})};Styles.getFontGlyphRange=function(config){validator.assertShape({fonts:validator.required(validator.oneOfType(validator.string,validator.arrayOf(validator.string))),start:validator.required(validator.number),end:validator.required(validator.number),ownerId:validator.string})(config);var fileName=config.start+"-"+config.end+".pbf";return this.client.createRequest({method:"GET",path:"/fonts/v1/:ownerId/:fontList/:fileName",params:immutable(pick_1(config,["ownerId"]),{fontList:[].concat(config.fonts),fileName:fileName})})};Styles.getEmbeddableHtml=function(config){validator.assertShape({styleId:validator.required(validator.string),scrollZoom:validator.boolean,title:validator.boolean,ownerId:validator.string})(config);var fileName=config.styleId+".html";var query={};if(config.scrollZoom!==undefined){query.zoomwheel=String(config.scrollZoom)}if(config.title!==undefined){query.title=String(config.title)}return this.client.createRequest({method:"GET",path:"/styles/v1/:ownerId/:fileName",params:immutable(pick_1(config,["ownerId"]),{fileName:fileName}),query:query})};var styles=createServiceFactory_1(Styles);var Tilequery={};Tilequery.listFeatures=function(config){validator.assertShape({mapIds:validator.required(validator.arrayOf(validator.string)),coordinates:validator.required(validator.coordinates),radius:validator.number,limit:validator.range([1,50]),dedupe:validator.boolean,geometry:validator.oneOf("polygon","linestring","point"),layers:validator.arrayOf(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/v4/:mapIds/tilequery/:coordinates.json",params:{mapIds:config.mapIds,coordinates:config.coordinates},query:pick_1(config,["radius","limit","dedupe","layers","geometry"])})};var tilequery=createServiceFactory_1(Tilequery);var Tilesets={};Tilesets.listTilesets=function(config){validator.assertShape({ownerId:validator.string})(config);return this.client.createRequest({method:"GET",path:"/tilesets/v1/:ownerId",params:config})};var tilesets=createServiceFactory_1(Tilesets);var Tokens={};Tokens.listTokens=function(){return this.client.createRequest({method:"GET",path:"/tokens/v2/:ownerId"})};Tokens.createToken=function(config){config=config||{};validator.assertShape({note:validator.string,scopes:validator.arrayOf(validator.string),resources:validator.arrayOf(validator.string),allowedUrls:validator.arrayOf(validator.string)})(config);var body={};body.scopes=config.scopes||[];if(config.note!==undefined){body.note=config.note}if(config.resources){body.resources=config.resources}if(config.allowedUrls){body.allowedUrls=config.allowedUrls}return this.client.createRequest({method:"POST",path:"/tokens/v2/:ownerId",params:pick_1(config,["ownerId"]),body:body})};Tokens.createTemporaryToken=function(config){validator.assertShape({expires:validator.required(validator.date),scopes:validator.required(validator.arrayOf(validator.string))})(config);return this.client.createRequest({method:"POST",path:"/tokens/v2/:ownerId",params:pick_1(config,["ownerId"]),body:{expires:new Date(config.expires).toISOString(),scopes:config.scopes}})};Tokens.updateToken=function(config){validator.assertShape({tokenId:validator.required(validator.string),note:validator.string,scopes:validator.arrayOf(validator.string),resources:validator.arrayOf(validator.string),allowedUrls:validator.arrayOf(validator.string)})(config);var body={};if(config.scopes){body.scopes=config.scopes}if(config.note!==undefined){body.note=config.note}if(config.resources||config.resources===null){body.resources=config.resources}if(config.allowedUrls||config.allowedUrls===null){body.allowedUrls=config.allowedUrls}return this.client.createRequest({method:"PATCH",path:"/tokens/v2/:ownerId/:tokenId",params:pick_1(config,["ownerId","tokenId"]),body:body})};Tokens.getToken=function(){return this.client.createRequest({method:"GET",path:"/tokens/v2"})};Tokens.deleteToken=function(config){validator.assertShape({tokenId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/tokens/v2/:ownerId/:tokenId",params:pick_1(config,["ownerId","tokenId"])})};Tokens.listScopes=function(){return this.client.createRequest({method:"GET",path:"/scopes/v1/:ownerId"})};var tokens=createServiceFactory_1(Tokens);var Uploads={};Uploads.listUploads=function(config){validator.assertShape({reverse:validator.boolean})(config);return this.client.createRequest({method:"GET",path:"/uploads/v1/:ownerId",query:config})};Uploads.createUploadCredentials=function(){return this.client.createRequest({method:"POST",path:"/uploads/v1/:ownerId/credentials"})};Uploads.createUpload=function(config){validator.assertShape({mapId:validator.required(validator.string),url:validator.required(validator.string),tilesetName:validator.string})(config);return this.client.createRequest({method:"POST",path:"/uploads/v1/:ownerId",body:{tileset:config.mapId,url:config.url,name:config.tilesetName}})};Uploads.getUpload=function(config){validator.assertShape({uploadId:validator.required(validator.string)})(config);return this.client.createRequest({method:"GET",path:"/uploads/v1/:ownerId/:uploadId",params:config})};Uploads.deleteUpload=function(config){validator.assertShape({uploadId:validator.required(validator.string)})(config);return this.client.createRequest({method:"DELETE",path:"/uploads/v1/:ownerId/:uploadId",params:config})};var uploads=createServiceFactory_1(Uploads);function mapboxSdk(options){var client=browserClient(options);client.datasets=datasets(client);client.directions=directions(client);client.geocoding=geocoding(client);client.mapMatching=mapMatching(client);client.matrix=matrix(client);client.optimization=optimization(client);client.static=_static(client);client.styles=styles(client);client.tilequery=tilequery(client);client.tilesets=tilesets(client);client.tokens=tokens(client);client.uploads=uploads(client);return client}var bundle=mapboxSdk;return bundle}); |
Sorry, the diff of this file is too big to display
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
430853
11911