@basemaps/lambda-tiler 6.32.0 → 6.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,14 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [6.32.1](https://github.com/linz/basemaps/compare/v6.32.0...v6.32.1) (2022-07-28)
7
+
8
+ **Note:** Version bump only for package @basemaps/lambda-tiler
9
+
10
+
11
+
12
+
13
+
6
14
  # [6.32.0](https://github.com/linz/basemaps/compare/v6.31.0...v6.32.0) (2022-07-28)
7
15
 
8
16
 
package/dist/index.js CHANGED
@@ -180,11 +180,11 @@ PARAMETER["false_easting",1600000],
180
180
  PARAMETER["false_northing",10000000],
181
181
  UNIT["metre",1,
182
182
  AUTHORITY["EPSG","9001"]],
183
- AUTHORITY["EPSG","2193"]]`;Zo.default.defs(Re.Nztm2000.toEpsgString(),n6);Zo.default.defs(Re.Citm2000.toEpsgString(),i6);var Y0=new Map;function Ox(t){return t==null?null:typeof t=="number"?t:"code"in t?t.code:"projection"in t?t.projection.code:null}var jr=class{constructor(e){this.epsg=e;try{this.projection=(0,Zo.default)(e.toEpsgString(),Re.Wgs84.toEpsgString())}catch(r){throw new it(`Failed to create projection: ${e.toEpsgString()}, ${Re.Wgs84.toEpsgString()}`,500,r)}}static define(e,r){if(Y0.get(e.code)!=null)throw new Error("Duplicate projection definition: "+e.toEpsgString());Zo.default.defs(e.toEpsgString(),r)}static get(e){let r=this.tryGet(e);if(r==null)throw new Error(`Invalid projection: ${e}`);return r}static tryGet(e){let r=Ox(e);if(r==null)return null;let i=Y0.get(r);if(i!=null)return i;let n=Re.tryGet(r);return n==null||Zo.default.defs(n.toEpsgString())==null?null:(i=new jr(n),Y0.set(r,i),i)}projectMultipolygon(e,r){if(r.epsg.code===this.epsg.code)return e;let{toWgs84:i}=this,{fromWgs84:n}=r;return e.map(o=>o.map(a=>a.map(h=>n(i(h)))))}get toWgs84(){return this.projection.forward}get fromWgs84(){return this.projection.inverse}boundsToWgs84BoundingBox(e){let r=this.toWgs84([e.x,e.y]),i=this.toWgs84([e.x+e.width,e.y+e.height]);return[r[0],r[1],i[0],i[1]]}boundsToGeoJsonFeature(e,r={}){let i=[e.x,e.y],n=[e.x+e.width,e.y],o=[e.x,e.y+e.height],a=[e.x+e.width,e.y+e.height],h=Yu([[[i,o,a,n,i]]],this.toWgs84),d=h.length===1?e6(h[0],r):t6(h,r);return d.bbox=this.boundsToWgs84BoundingBox(e),d}toGeoJson(e){return{type:"FeatureCollection",features:e.map(r=>this.boundsToGeoJsonFeature(r,{name:r.name}))}}static getTiffResZoom(e,r,i=1){let n=0;for(;n<e.zooms.length;++n)if(e.pixelScale(n)<=r*i)return n;if(n===e.zooms.length)return n-1;throw new Error("ResZoom not found")}static tileToWgs84Bbox(e,r){let i=e.tileToSource(r),n=e.tileToSource({x:r.x+1,y:r.y+1,z:r.z}),o=this.get(e),[a,h]=o.toWgs84([i.x,n.y]),[d,m]=o.toWgs84([n.x,i.y]);return[a,h,d,m]}static tileCenterToLatLon(e,r){let i=e.tileToSource({x:r.x+.5,y:r.y+.5,z:r.z}),[n,o]=this.get(e).toWgs84([i.x,i.y]);return jr.wrapLatLon(o,n)}static wrapLatLon(e,r){let i={lat:e,lon:r},n=Math.floor(Math.abs(e)/90)%4,o=e>0?90:-90,a=e%90;switch(n){case 0:i.lat=a;break;case 1:i.lat=o-a,i.lon+=180;break;case 2:i.lat=-a,i.lon+=180;break;case 3:i.lat=-o+a;break}return(i.lon>180||i.lon<-180)&&(i.lon-=Math.floor((i.lon+180)/360)*360),i}static findAlignmentLevels(e,r,i){return Math.max(0,this.getTiffResZoom(e,i,2)-r.z)}static getImagePixelWidth(e,r,i){let n=e.tileToSource(r),o=e.tileToSource({x:r.x+1,y:r.y+1,z:r.z});return Math.round((o.x-n.x)/e.pixelScale(i))*2}};function s6(t){return t==null||typeof t=="string"?!1:"roleArn"in t&&typeof t.roleArn=="string"}var o6=de(require("aws-sdk/lib/core.js"),1),a6=de(require("aws-sdk/clients/s3.js"),1);function Yo(t){return"promise"in t?t.promise():t}function Xo(t,e){return Ei(t)?typeof t.statusCode!="number"?new it(e,500,t):new it(e,t.statusCode,t):new it(e,500,t)}var Jt=class extends Rt{constructor(e,r,i){super(),this.type=Jt.type,this.protocol="s3",this.chunkSize=Jt.DefaultChunkSize,this.maxChunkCount=Jt.DefaultMaxChunkCount,this.bucket=e,this.key=r,this.remote=i}get uri(){return this.name}get name(){return`s3://${this.bucket}/${this.key}`}static isSource(e){return e.type===Jt.type}get size(){return this._size?this._size:(this._size=Promise.resolve().then(async()=>(await Yo(this.remote.headObject({Bucket:this.bucket,Key:this.key}))).ContentLength||-1),this._size)}static fromUri(e,r){let i=Qr(e);return i==null||i.key==null||i.protocol!=="s3"?null:new Jt(i.bucket,i.key,r)}async fetchBytes(e,r){let i=this.toRange(e,r);try{let n=await this.remote.getObject({Bucket:this.bucket,Key:this.key,Range:i}).promise();if(!Buffer.isBuffer(n.Body))throw new Error("Failed to fetch object, Body is not a buffer");n.ContentRange!=null&&this._size==null&&(this._size=Promise.resolve(this.parseContentRange(n.ContentRange)));let o=n.Body;return o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)}catch(n){throw Xo(n,`Failed to fetch ${this.name} ${i}`)}}};Jt.type="aws:s3";Jt.DefaultChunkSize=64*1024;Jt.DefaultMaxChunkCount=32;var Zt=class{constructor(e){this.protocol=Zt.protocol,this.s3=e}source(e){let r=Jt.fromUri(e,this.s3);if(r==null)throw new Error(`Failed to create aws s3 source from uri: ${e}`);return r}static is(e){return e.protocol===Zt.protocol}static isPath(e){return e==null?!1:e.startsWith("s3://")}async*list(e,r){for await(let i of this.details(e,r))yield i.path}async*details(e,r){let i=Qr(e);if(i==null)return;let n,o=r?.recursive===!1?"/":void 0,a=i.bucket,h=i.key,d=0;try{for(;;){d++;let m=await Yo(this.s3.listObjectsV2({Bucket:a,Prefix:h,ContinuationToken:n,Delimiter:o}));if(m.CommonPrefixes!=null)for(let p of m.CommonPrefixes)p.Prefix!=null&&(yield{path:`s3://${a}/${p.Prefix}`,isDirectory:!0});if(m.Contents!=null)for(let p of m.Contents)p.Key!=null&&(yield{path:`s3://${a}/${p.Key}`,size:p.Size});if(!m.IsTruncated)break;if(d>=Zt.MaxListCount)throw new Error(`Failed to finish listing within ${Zt.MaxListCount} list attempts`);n=m.NextContinuationToken}}catch(m){throw Xo(m,`Failed to list: "${e}"`)}}async read(e){let r=Qr(e);if(r==null||r.key==null)throw new Error(`Failed to read: "${e}"`);try{return(await this.s3.getObject({Bucket:r.bucket,Key:r.key}).promise()).Body}catch(i){throw Xo(i,`Failed to read: "${e}"`)}}async write(e,r,i){let n=Qr(e);if(n==null||n.key==null)throw new Error(`Failed to write: "${e}"`);try{await Yo(this.s3.upload({Bucket:n.bucket,Key:n.key,Body:r,ContentEncoding:i?.contentEncoding,ContentType:i?.contentType}))}catch(o){throw Xo(o,`Failed to write: "${e}"`)}}exists(e){return this.head(e).then(r=>r!=null)}stream(e){let r=Qr(e);if(r==null||r.key==null)throw new Error(`S3: Unable to read "${e}"`);return this.s3.getObject({Bucket:r.bucket,Key:r.key}).createReadStream()}async head(e){let r=Qr(e);if(r==null||r.key==null)throw new Error(`Failed to exists: "${e}"`);try{return{size:(await Yo(this.s3.headObject({Bucket:r.bucket,Key:r.key}))).ContentLength,path:e}}catch(i){if(Ei(i)&&i.code==="NotFound")return null;throw Xo(i,`Failed to exists: "${e}"`)}}};Zt.protocol="s3";Zt.MaxListCount=100;var Yt=class{static fsFromRole(e,r,i){if(typeof e=="object")return Yt.fsFromRole(e.roleArn,e.externalId,e.durationSeconds);let n=Yt.role(e,r,i);return new Zt(new a6.default({credentials:n}))}static role(e,r,i){i=i??Yt.DefaultRoleDurationSeconds;let n=`role::${e}::${r}::${i}`,o=Yt.cache.get(n);return o==null&&(o=new o6.default.ChainableTemporaryCredentials({params:{RoleArn:e,ExternalId:r,RoleSessionName:"fsa-"+Math.random().toString(32)+"-"+Date.now(),DurationSeconds:i}}),Yt.cache.set(n,o)),o}};Yt.DefaultRoleDurationSeconds=3600;Yt.cache=new Map;var l6=de(require("aws-sdk/clients/s3.js"),1),u6=require("util"),Xu=require("zlib");var kx=(0,u6.promisify)(Xu.gunzip),Er=nt;Er.readJson=async function(e){let r=await this.read(e);return e.endsWith(".gz")?JSON.parse((await kx(r)).toString()):JSON.parse(r.toString())};Er.writeJson=async function(e,r){let i=Buffer.from(JSON.stringify(r,void 0,2));if(e.endsWith(".gz")){let n=(0,Xu.createGzip)();return n.end(i),this.write(e,n)}else return this.write(e,i)};Er.configure=function(e){if(e.type!=="s3"||!s6(e))return;let r=Qr(e.path);if(r==null)throw new Error("Failed to parse URI: "+e.path);let i=`s3://${r.bucket}/`;this.register(i,Yt.fsFromRole(e.roleArn,e.externalId))};Er.register("s3://",new Zt(new l6.default));function X0(t){return t[0].toUpperCase()+t.slice(1).replace(/_(\d+)-(\d+)m/g," $1.$2m").replace(/_/g," ")}function h6(t){let e=/(?:^|\D)(\d{4})(?:-(\d{2}))?(?:$|\D)/g,r=[];for(let i=e.exec(t);i!=null;i=e.exec(t))r.push(parseInt(i[1])),i[2]!=null&&r.push(parseInt(i[1].slice(0,2)+i[2]));return r.length===0?[-1,-1]:(r.sort(),[r[0],r[r.length-1]+1])}process.env.AWS_NODEJS_CONNECTION_REUSE_ENABLED="1";_e.setConfigProvider(new Va(u1.TileMetadata.TableName));var s4=de(t0(),1);var Mn="application/json",re;(function(t){t.CacheControl="Cache-Control",t.ContentEncoding="Content-Encoding",t.ContentType="Content-Type",t.Cors="Access-Control-Allow-Origin",t.ETag="ETag",t.IfNoneMatch="If-None-Match",t.Server="Server",t.ServerTiming="Server-Timing"})(re||(re={}));var Qo;(function(t){t.CloudfrontId="X-Amz-Cf-Id",t.TraceId="X-Amzn-Trace-Id"})(Qo||(Qo={}));var $r;(function(t){t.CorrelationId="X-LINZ-Correlation-Id",t.RequestId="X-LINZ-Request-Id"})($r||($r={}));var _s=class{constructor(){if(this.timers=new Map,typeof process<"u"&&typeof process.hrtime.bigint=="function"){let e=BigInt(1e6);this.getTime=()=>Number(process.hrtime.bigint()/e)}else typeof typeof performance<"u"?this.getTime=()=>performance.now():this.getTime=()=>Date.now()}start(e){let r=this.timers.get(e);if(r!=null&&r.duration==null)throw new Error(`Duplicate startTime for "${e}"`);this.timers.set(e,{start:this.getTime()})}end(e){let r=this.timers.get(e);if(r==null)throw new Error(`Missing startTime information for "${e}"`);let i=this.getTime()-r.start;return r.duration=i,i}get metrics(){if(this.timers.size===0)return;let e={};for(let[r,i]of this.timers.entries())i.duration!=null&&(e[r]=i.duration);return e}get unfinished(){let e=[];for(let[r,i]of this.timers.entries())i.duration==null&&e.push(r);if(e.length!==0)return e}};var c6=de(Xn(),1);function Bt(t){return!(typeof t!="object"||t==null)}var xs=class{constructor(e,r,i){this.logContext={},this.timer=new _s,this.headers=new Map,this.context=r,this.event=e,this.id=(0,c6.ulid)(),this.log=i,this.timer=new _s,this.log=i.child({id:this.id,aws:{lambdaId:r.awsRequestId}})}set(e,r){r==null&&(r=void 0),this.logContext[e]=r}toResponse(e){return e?.body}};var d6=require("url");var f6=de(Xn(),1);var or=class extends xs{constructor(e,r,i){var n;super(e,r,i),this.headers=new Map,this.correlationId=(n=this.header($r.CorrelationId))!==null&&n!==void 0?n:f6.ulid(),this.set("correlationId",this.correlationId)}header(e){return this._isHeadersLoaded!==!0&&(this.loadHeaders(),this._isHeadersLoaded=!0),this.headers.get(e.toLowerCase())}json(){var e;if(this.header(re.ContentType)!==Mn)throw new Error(`Invalid Content-Type: "${this.header("content-type")}"`);if(this.body==null)throw new Error("Cannot parse empty body as JSON");try{return this.isBase64Encoded?JSON.parse(Buffer.from((e=this.body)!==null&&e!==void 0?e:"","base64").toString()):JSON.parse(this.body)}catch{throw new Error("Body is not a JSON object")}}get query(){return this._query==null&&(this._query=this.loadQueryString()),this._query}get url(){return this.path}};var ea=class extends or{static is(e){return Bt(e)&&Bt(e.requestContext)&&Bt(e.requestContext.elb)}toResponse(e){return{statusCode:e.status,statusDescription:e.statusDescription,body:e.body,headers:this.toHeaders(e.headers),isBase64Encoded:e.isBase64Encoded}}toHeaders(e){if(e.size===0)return;let r={};for(let i of e)r[i[0]]=i[1];return r}loadHeaders(){if(this.event.headers!=null)for(let[e,r]of Object.entries(this.event.headers))r!=null&&this.headers.set(e.toLowerCase(),r)}loadQueryString(){let e=new d6.URLSearchParams;if(this.event.queryStringParameters==null)return e;for(let[r,i]of Object.entries(this.event.queryStringParameters))e.append(r.toLowerCase(),i??"true");return e}get method(){return this.event.httpMethod.toUpperCase()}get path(){return this.event.path}get body(){return this.event.body}get isBase64Encoded(){return this.event.isBase64Encoded}};var m6=require("url");var hi=class extends or{static is(e){return!(!Bt(e)||!Bt(e.requestContext)||typeof e.requestContext.apiId!="string"||typeof e.requestContext.resourceId!="string"||typeof e.requestContext.httpMethod!="string")}toResponse(e){return{statusCode:e.status,body:e.body,headers:hi.toHeaders(e),isBase64Encoded:e.isBase64Encoded}}static toHeaders(e){if(e.headers.size===0)return;let r={};for(let i of e.headers)r[i[0]]=i[1];return r}loadHeaders(){if(this.event.headers!=null)for(let[e,r]of Object.entries(this.event.headers))r!=null&&this.headers.set(e.toLowerCase(),r)}loadQueryString(){let e=new m6.URLSearchParams;if(this.event.multiValueQueryStringParameters==null)return e;for(let[r,i]of Object.entries(this.event.multiValueQueryStringParameters))if(i!=null)for(let n of i)e.append(r.toLowerCase(),n);return e}get path(){return this.event.path}get method(){return this.event.httpMethod.toUpperCase()}get body(){return this.event.body}get isBase64Encoded(){return this.event.isBase64Encoded}};var Q0=require("url");var ta=class extends or{static is(e){if(!Bt(e)||!Array.isArray(e.Records))return!1;let r=e.Records[0];return Bt(r)?Bt(r.cf):!1}toResponse(e){if(e.status===100&&this.event!=null){let r=this.event.Records[0].cf.request;for(let[i,n]of e.headers)r.headers[i.toLowerCase()]=[{key:i,value:String(n)}];return this.event.Records[0].cf.request}return{status:String(e.status),statusDescription:e.statusDescription,body:e.body,headers:this.toHeaders(e),bodyEncoding:"text"}}toHeaders(e){if(e.headers.size===0)return{};let r={};for(let i of e.headers)r[i[0]]=[{key:i[0],value:String(i[1])}];return r}loadHeaders(){var e;for(let[r,i]of Object.entries(this.event.Records[0].cf.request.headers))this.headers.set(r.toLowerCase(),(e=i[0])===null||e===void 0?void 0:e.value)}loadQueryString(){let e=this.event.Records[0].cf.request.querystring;return e==null?new Q0.URLSearchParams:new Q0.URLSearchParams(e.toLowerCase())}get path(){return this.event.Records[0].cf.request.uri}get method(){return this.event.Records[0].cf.request.method.toUpperCase()}get body(){let e=this.event.Records[0].cf.request.body;return e==null?null:e.data}get isBase64Encoded(){var e;return((e=this.event.Records[0].cf.request.body)===null||e===void 0?void 0:e.encoding)==="base64"}};var ee=class{constructor(e,r,i){if(this._body=null,this.headers=new Map,this.status=e,this.statusDescription=r,i!=null)for(let n of Object.keys(i))this.header(n,i[n])}static is(e){return e instanceof ee}static ok(e=200,r="Ok"){return new ee(e,r)}header(e,r){let i=e.toLowerCase();if(r==null)return this.headers.get(i);this.headers.set(i,r)}get isBase64Encoded(){return Buffer.isBuffer(this._body)}json(e){return this.buffer(JSON.stringify(e),Mn),this}buffer(e,r=Mn){return this.header(re.ContentType,r),this._body=e,this}get body(){return this._body==null?(this.header(re.ContentType,Mn),JSON.stringify({id:this.header($r.RequestId),status:this.status,message:this.statusDescription,correlationId:this.header($r.CorrelationId)})):Buffer.isBuffer(this._body)?this._body.toString("base64"):this._body}};var t4=de(e4(),1);var lh=class{constructor(){this.hooks={request:[],response:[]},this.router=(0,t4.default)({defaultRoute:()=>new ee(404,"Not found")})}register(e,r,i){this.router.on(e,r,async(n,o,a)=>n instanceof or?(n.params=a,uh(n,i)):new ee(500,"Internal server error"))}hook(e,r){this.hooks[e].push(r)}get(e,r){return this.register("GET",e,r)}post(e,r){return this.register("POST",e,r)}delete(e,r){return this.register("DELETE",e,r)}options(e,r){return this.register("OPTIONS",e,r)}patch(e,r){return this.register("PATCH",e,r)}head(e,r){return this.register("HEAD",e,r)}put(e,r){return this.register("PUT",e,r)}async after(e,r){try{for(let i of this.hooks.response)await i(e,r)}catch(i){return ee.is(i)?i:(e.set("err",i),new ee(500,"Internal Server Error"))}return r}async handle(e){for(let i of this.hooks.request){let n=await uh(e,i);if(n)return this.after(e,n)}let r=await this.router.lookup(e,null);return r?this.after(e,r):this.after(e,new ee(404,"Not found"))}};var r4=require("url");var Rn=class extends or{toResponse(e){return{statusCode:e.status,body:e.body,headers:hi.toHeaders(e),isBase64Encoded:e.isBase64Encoded}}loadHeaders(){for(let[e,r]of Object.entries(this.event.headers))this.headers.set(e.toLowerCase(),r)}loadQueryString(){return new r4.URLSearchParams(this.event.rawQueryString)}get method(){return this.event.requestContext.http.method.toUpperCase()}get path(){return this.event.rawPath}get isBase64Encoded(){return this.event.isBase64Encoded}get body(){return this.event.body==null?null:this.event.body}static is(e){return!(!Bt(e)||!Bt(e.requestContext)||!Bt(e.requestContext.http))}};var o4="v6.32.0",aS="cf9e8d4e61f7634acf51b9a837bbab6889761f1b",i4={version:o4,hash:aS};async function uh(t,e){t.timer.timers.has("lambda")||t.timer.start("lambda");try{return await e(t)}catch(r){return ee.is(r)?r:(t.set("err",r),new ee(500,"Internal Server Error"))}}function n4(t,e){let r=200;ee.is(e)&&(r=e.status,t.set("description",e.statusDescription)),t.set("status",r),t.timer.timers.size>0&&t.set("metrics",t.timer.metrics),i4.hash&&t.set("package",i4);let i=t.timer.timers.has("lambda")?t.timer.end("lambda"):0;return t.set("unfinished",t.timer.unfinished),t.set("duration",i),t.set("@type","report"),r>499?t.log.error(t.logContext,"Lambda:Done"):r>399?t.log.warn(t.logContext,"Lambda:Done"):t.log.info(t.logContext,"Lambda:Done"),e}function lS(t){let e={rejectOnError:!0,tracePercent:0,...t};if(isNaN(e.tracePercent)||e.tracePercent>1)throw new Error("tracePercent is not between 0-1 :"+e.tracePercent);return e}var ar=class{static request(e,r,i){if(ea.is(e))return new ea(e,r,i);if(Rn.is(e))return new Rn(e,r,i);if(hi.is(e))return new hi(e,r,i);if(ta.is(e))return new ta(e,r,i);throw new Error("Request is not a a ALB, ApiGateway or Cloudfront event")}static handler(e,r,i){let n=lS(r);function o(a,h,d){let m=new xs(a,h,i??ar.Logger);n.tracePercent>0&&Math.random()<n.tracePercent&&(m.log.level="trace"),process.env.TRACE_LAMBDA&&(m.log.level="trace"),m.log.trace({event:a},"Lambda:Start");let p=h.awsRequestId;m.set("aws",{lambdaId:p}),uh(m,e).then(M=>{if(n4(m,M),ee.is(M)&&n.rejectOnError){if(m.logContext.err)return d(m.logContext.err);if(M.status>399)return d(m.toResponse(M))}return d(null,m.toResponse(M))})}return o}static http(e){let r=new lh;function i(n,o,a){let h=ar.request(n,o,e??ar.Logger),d=h.header(Qo.CloudfrontId),m=h.header(Qo.TraceId),p=o.awsRequestId;(d||m||p)&&h.set("aws",{cloudFrontId:d,traceId:m,lambdaId:p}),h.set("method",h.method),h.set("path",h.path),r.handle(h).then(M=>{var R;M.status===500&&M.header(re.CacheControl,"no-store"),M.header($r.RequestId,h.id),M.header($r.CorrelationId,h.correlationId);let x=(R=h.timer.metrics)===null||R===void 0?void 0:R.lambda;x!=null&&M.header(re.ServerTiming,`total;dur=${x}`),!M.isBase64Encoded&&M.header(re.ContentType)==null&&M.header(re.ContentType,Mn),ar.ServerName&&M.header(re.Server,`${ar.ServerName}-${o4}`),n4(h,M),a(null,h.toResponse(M))})}return i.router=r,i}};ar.Logger=(0,s4.default)();ar.ServerName="linz";var qe={key(t){return Buffer.isBuffer(t)||typeof t=="string"?Qn(t):Qn(JSON.stringify(t))},isNotModified(t,e){let r=t.header(re.IfNoneMatch);return r!=null&&r.indexOf(e)>-1?(t.set("cache",{hit:!0,match:r}),!0):!1}};var be=()=>new ee(404,"Not Found"),ct=()=>new ee(304,"Not modified");var uS=.2,aa=class{constructor(e){this.tms=e}async tile(e,r,i,n){let o=[];for(let a of e){let h=this.getTiles(a,r,i,n);h!=null&&(o=o.concat(h))}return o}getRasterTiffIntersection(e,r,i,n){let o=this.tms.tileToPixels(r,i),a=new xe(o.x,o.y,this.tms.tileSize,this.tms.tileSize),h=e.images[0].bbox,d=this.tms.sourceToPixels(h[0],h[3],n),m=this.tms.sourceToPixels(h[2],h[1],n),p=xe.fromUpperLeftLowerRight(d,m),M=p.intersection(a);return M==null?null:{tiff:p,intersection:M,tile:a}}createComposition(e,r,i,n,o){let a=xe.fromJson(e.getTileBounds(r,i)),h=a.scale(n,n).add(o.tiff).round(uS),d=h.intersection(o.tile);if(d==null)return null;let m=d.subtract(h);if(m.height<.5||m.width<.5)return null;let p=h.subtract(o.tile),M={tiff:e.tif,source:{x:r,y:i,imageId:e.id,width:a.width,height:a.height},y:Math.max(0,Math.round(p.y)),x:Math.max(0,Math.round(p.x))};if((a.width<e.tileSize.width||a.height<e.tileSize.height)&&(M.extract={width:a.width,height:a.height}),a.width!==h.width||a.height!==h.height){let R=a.width!==h.width?h.width/a.width:h.height/a.height;M.resize={width:h.width,height:h.height,scale:R}}return(m.y!==0||m.x!==0||m.height!==h.height||m.width!==h.width)&&(M.crop=m),M}getTiles(e,r,i,n){let o=this.getRasterTiffIntersection(e,r,i,n);if(o==null)return null;let a=this.tms.pixelScale(n),h=e.getImageByResolution(a),d=a/h.resolution[0],m=o.intersection.subtract(o.tiff),{tileSize:p,tileCount:M}=h,R=[],x=1/d;for(let w of aa.getRequiredTiles(m,d,p,M)){let E=this.createComposition(h,w.x,w.y,x,o);E!=null&&R.push(E)}return R.length===0?null:R}static*getRequiredTiles(e,r,i,n){let o=Math.max(Math.floor(e.x/i.width*r),0),a=Math.min(Math.ceil(e.right/i.width*r),n.x),h=Math.max(Math.floor(e.y/i.height*r),0),d=Math.min(Math.ceil(e.bottom/i.height*r),n.y);for(let m=o;m<a;m++)for(let p=h;p<d;p++)yield{x:m,y:p}}};var a4=[He.Jpeg,He.Webp,He.Png];function md(t){if(t==null)return null;let e=t.toLowerCase();return e===He.Png?He.Png:e===He.Webp?He.Webp:e===He.Jpeg||e==="jpg"?He.Jpeg:e===He.Avif?He.Avif:null}var l4=de(Xn(),1),hS=60*60*1e3,cS=24*hS,fS=91*cS;function dS(t){if(t==null)return{valid:!1,message:"missing"};if(!t.startsWith("c")&&!t.startsWith("d"))return{valid:!1,message:"malformed"};let e=t.slice(1).toUpperCase();try{let r=l4.decodeTime(e);if(t.startsWith("d"))return{valid:!0,message:"ok"};if(Date.now()-r>fS)return{valid:!1,message:"expired"}}catch{return{valid:!1,message:"malformed"}}return{valid:!0,message:"ok"}}var wt={apiKey(t){let e=t.query.get(u1.ApiKey.QueryString)??t.header("X-LINZ-Api-Key"),r=dS(e);if(!r.valid)throw new ee(400,"API Key Invalid: "+r.message);return t.set("api",e),e},getTileMatrixSet(t){return Yn.find(t)},getRequestedFormats(t){let e=[...t.query.getAll("format"),...t.query.getAll("tileFormat")];if(e.length===0)return null;let r=new Set;for(let i of e){let n=md(i);n!=null&&r.add(n)}return r.size===0?null:[...r.values()]},getTileFormat(t){let e=md(t);return e||(t===rr.MapboxVectorTiles?rr.MapboxVectorTiles:null)},xyz(t){wt.apiKey(t),t.set("tileSet",t.params.tileSet);let e=parseInt(t.params.x,10),r=parseInt(t.params.y,10),i=parseInt(t.params.z,10),n=wt.getTileMatrixSet(t.params.tileMatrix);if(n==null)throw new ee(404,"Tile Matrix not found");t.set("tileMatrix",n.identifier),t.set("projection",n.projection.code);let o=wt.getTileFormat(t.params.tileType);if(o==null)throw new ee(404,"Tile extension not found");if(t.set("extension",o),isNaN(i)||i>n.maxZoom||i<0)throw new ee(404,`Zoom not found: ${i}`);let a=n.zooms[i];if(isNaN(e)||e<0||e>a.matrixWidth)throw new ee(404,`X not found: ${e}`);if(isNaN(r)||r<0||r>a.matrixHeight)throw new ee(404,`Y not found: ${r}`);let h={tile:{x:e,y:r,z:i},tileSet:t.params.tileSet,tileMatrix:n,tileType:o};t.set("xyz",h.tile);let d=jr.tileCenterToLatLon(n,h.tile);return t.set("location",d),h}};var mS=1+1e-10,u4=10**8;function pd(t){return Math.round(t*u4)/u4}function pS(t){return[pd(t[0]),pd(t[1])]}function gS(t,e,r){if(Sn.delta(t[0],t[2])<=0)return Sn.bboxToMultiPolygon(t);let i=[];for(let o of e){let a=[xe.fromJson(o).pad(mS).toPolygon()];i=Qp(i,a)}return Yu(i,o=>pS(r.toWgs84(o)))}async function yS(t,e,r){let i=jr.get(r),n=[],o=[],a=await _e.getAllImagery(e.layers,[r.projection]),h=await _e.Provider.get(_e.Provider.id("linz"));if(h==null)return null;for(let d of e.layers){let m=d[i.epsg.code];if(m==null)continue;let p=a.get(m);if(p==null)continue;let M=i.boundsToWgs84BoundingBox(p.bounds).map(pd),R=h6(p.name);if(R[0]===-1)throw new Error("Missing date in imagery name: "+p.name);let x=[R.map(C=>`${C}-01-01T00:00:00Z`)],w={spatial:{bbox:[M]},temporal:{interval:x}};o.push({type:"Feature",stac_version:Ka.Version,id:m+"_item",collection:m,assets:{},links:[],bbox:M,geometry:{type:"MultiPolygon",coordinates:gS(M,p.files,i)},properties:{title:p.title??X0(p.name),category:p.category,datetime:null,start_datetime:x[0][0],end_datetime:x[0][1]}});let E=Mt.convertZoomLevel(d.minZoom?d.minZoom:0,lt,r,!0),T=Mt.convertZoomLevel(d.maxZoom?d.maxZoom:32,lt,r,!0);n.push({stac_version:Ka.Version,license:Ka.License,id:p.id,providers:[{name:h.serviceProvider.name,url:h.serviceProvider.site,roles:["host"]}],title:p.title??X0(p.name),description:"No description",extent:w,links:[],summaries:{"linz:category":p.category,"linz:zoom":{min:E,max:T},"linz:priority":[1e3+e.layers.indexOf(d)]}})}return{id:e.id,type:"FeatureCollection",stac_version:Ka.Version,stac_extensions:["single-file-stac"],title:e.title??"No title",description:e.description??"No Description",features:o,collections:n,links:[]}}async function gd(t){let e=wt.getTileMatrixSet(t.params.tileMatrix);if(e==null)throw new ee(404,"Tile Matrix not found");t.timer.start("tileset:load");let r=await _e.TileSet.get(_e.TileSet.id(t.params.tileSet));if(t.timer.end("tileset:load"),r==null||r.type===vt.Vector)return be();let i=qe.key(r);if(qe.isNotModified(t,i))return ct();t.timer.start("stac:load");let n=await yS(t,r,e);if(t.timer.end("stac:load"),n==null)return be();let o=new ee(200,"ok");return o.header(re.ETag,i),o.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),o.json(n),o}var Ph=de(require("path"),1);var Cr;(function(t){t.NONE="application/octet-stream",t.JPEG="image/jpeg",t.JP2="image/jp2",t.WEBP="image/webp",t.LZW="application/lzw",t.DEFLATE="application/deflate"})(Cr||(Cr={}));var yd={1:Cr.NONE,5:Cr.LZW,6:Cr.JPEG,7:Cr.JPEG,8:Cr.DEFLATE,34712:Cr.JP2,50001:Cr.WEBP};var ae;(function(t){t[t.Artist=315]="Artist",t[t.BitsPerSample=258]="BitsPerSample",t[t.CellLength=265]="CellLength",t[t.CellWidth=264]="CellWidth",t[t.ColorMap=320]="ColorMap",t[t.Compression=259]="Compression",t[t.Copyright=33432]="Copyright",t[t.DateTime=306]="DateTime",t[t.ExtraSamples=338]="ExtraSamples",t[t.FillOrder=266]="FillOrder",t[t.FreeByteCounts=289]="FreeByteCounts",t[t.FreeOffsets=288]="FreeOffsets",t[t.GrayResponseCurve=291]="GrayResponseCurve",t[t.GrayResponseUnit=290]="GrayResponseUnit",t[t.HostComputer=316]="HostComputer",t[t.ImageDescription=270]="ImageDescription",t[t.ImageHeight=257]="ImageHeight",t[t.ImageWidth=256]="ImageWidth",t[t.Make=271]="Make",t[t.MaxSampleValue=281]="MaxSampleValue",t[t.MinSampleValue=280]="MinSampleValue",t[t.Model=272]="Model",t[t.NewSubFileType=254]="NewSubFileType",t[t.Orientation=274]="Orientation",t[t.PhotometricInterpretation=262]="PhotometricInterpretation",t[t.PlanarConfiguration=284]="PlanarConfiguration",t[t.ResolutionUnit=296]="ResolutionUnit",t[t.RowsPerStrip=278]="RowsPerStrip",t[t.SamplesPerPixel=277]="SamplesPerPixel",t[t.Software=305]="Software",t[t.StripByteCounts=279]="StripByteCounts",t[t.StripOffsets=273]="StripOffsets",t[t.SubFileType=255]="SubFileType",t[t.Threshholding=263]="Threshholding",t[t.XResolution=282]="XResolution",t[t.YResolution=283]="YResolution",t[t.BadFaxLines=326]="BadFaxLines",t[t.CleanFaxData=327]="CleanFaxData",t[t.ClipPath=343]="ClipPath",t[t.ConsecutiveBadFaxLines=328]="ConsecutiveBadFaxLines",t[t.Decode=433]="Decode",t[t.DefaultImageColor=434]="DefaultImageColor",t[t.DocumentName=269]="DocumentName",t[t.DotRange=336]="DotRange",t[t.HalftoneHints=321]="HalftoneHints",t[t.Indexed=346]="Indexed",t[t.JPEGTables=347]="JPEGTables",t[t.PageName=285]="PageName",t[t.PageNumber=297]="PageNumber",t[t.Predictor=317]="Predictor",t[t.PrimaryChromaticities=319]="PrimaryChromaticities",t[t.ReferenceBlackWhite=532]="ReferenceBlackWhite",t[t.SampleFormat=339]="SampleFormat",t[t.SMinSampleValue=340]="SMinSampleValue",t[t.SMaxSampleValue=341]="SMaxSampleValue",t[t.StripRowCounts=559]="StripRowCounts",t[t.SubIFDs=330]="SubIFDs",t[t.T4Options=292]="T4Options",t[t.T6Options=293]="T6Options",t[t.TileByteCounts=325]="TileByteCounts",t[t.TileHeight=323]="TileHeight",t[t.TileOffsets=324]="TileOffsets",t[t.TileWidth=322]="TileWidth",t[t.TransferFunction=301]="TransferFunction",t[t.WhitePoint=318]="WhitePoint",t[t.XClipPathUnits=344]="XClipPathUnits",t[t.XPosition=286]="XPosition",t[t.YCbCrCoefficients=529]="YCbCrCoefficients",t[t.YCbCrPositioning=531]="YCbCrPositioning",t[t.YCbCrSubSampling=530]="YCbCrSubSampling",t[t.YClipPathUnits=345]="YClipPathUnits",t[t.YPosition=287]="YPosition",t[t.ApertureValue=37378]="ApertureValue",t[t.ColorSpace=40961]="ColorSpace",t[t.DateTimeDigitized=36868]="DateTimeDigitized",t[t.DateTimeOriginal=36867]="DateTimeOriginal",t[t.ExifIFD=34665]="ExifIFD",t[t.ExifVersion=36864]="ExifVersion",t[t.ExposureTime=33434]="ExposureTime",t[t.FileSource=41728]="FileSource",t[t.Flash=37385]="Flash",t[t.FlashpixVersion=40960]="FlashpixVersion",t[t.FNumber=33437]="FNumber",t[t.ImageUniqueID=42016]="ImageUniqueID",t[t.LightSource=37384]="LightSource",t[t.MakerNote=37500]="MakerNote",t[t.ShutterSpeedValue=37377]="ShutterSpeedValue",t[t.UserComment=37510]="UserComment",t[t.IPTC=33723]="IPTC",t[t.ICCProfile=34675]="ICCProfile",t[t.XMP=700]="XMP",t[t.GDAL_METADATA=42112]="GDAL_METADATA",t[t.GDAL_NODATA=42113]="GDAL_NODATA",t[t.Photoshop=34377]="Photoshop",t[t.ModelPixelScale=33550]="ModelPixelScale",t[t.ModelTiePoint=33922]="ModelTiePoint",t[t.ModelTransformation=34264]="ModelTransformation",t[t.GeoKeyDirectory=34735]="GeoKeyDirectory",t[t.GeoDoubleParams=34736]="GeoDoubleParams",t[t.GeoAsciiParams=34737]="GeoAsciiParams"})(ae||(ae={}));var P1;(function(t){t[t.GTModelTypeGeoKey=1024]="GTModelTypeGeoKey",t[t.GTRasterTypeGeoKey=1025]="GTRasterTypeGeoKey",t[t.GTCitationGeoKey=1026]="GTCitationGeoKey",t[t.GeographicTypeGeoKey=2048]="GeographicTypeGeoKey",t[t.GeogCitationGeoKey=2049]="GeogCitationGeoKey",t[t.GeogGeodeticDatumGeoKey=2050]="GeogGeodeticDatumGeoKey",t[t.GeogPrimeMeridianGeoKey=2051]="GeogPrimeMeridianGeoKey",t[t.GeogLinearUnitsGeoKey=2052]="GeogLinearUnitsGeoKey",t[t.GeogLinearUnitSizeGeoKey=2053]="GeogLinearUnitSizeGeoKey",t[t.GeogAngularUnitsGeoKey=2054]="GeogAngularUnitsGeoKey",t[t.GeogAngularUnitSizeGeoKey=2055]="GeogAngularUnitSizeGeoKey",t[t.GeogEllipsoidGeoKey=2056]="GeogEllipsoidGeoKey",t[t.GeogSemiMajorAxisGeoKey=2057]="GeogSemiMajorAxisGeoKey",t[t.GeogSemiMinorAxisGeoKey=2058]="GeogSemiMinorAxisGeoKey",t[t.GeogInvFlatteningGeoKey=2059]="GeogInvFlatteningGeoKey",t[t.GeogAzimuthUnitsGeoKey=2060]="GeogAzimuthUnitsGeoKey",t[t.GeogPrimeMeridianLongGeoKey=2061]="GeogPrimeMeridianLongGeoKey",t[t.GeogTOWGS84GeoKey=2062]="GeogTOWGS84GeoKey",t[t.ProjectedCSTypeGeoKey=3072]="ProjectedCSTypeGeoKey",t[t.PCSCitationGeoKey=3073]="PCSCitationGeoKey",t[t.ProjectionGeoKey=3074]="ProjectionGeoKey",t[t.ProjCoordTransGeoKey=3075]="ProjCoordTransGeoKey",t[t.ProjLinearUnitsGeoKey=3076]="ProjLinearUnitsGeoKey",t[t.ProjLinearUnitSizeGeoKey=3077]="ProjLinearUnitSizeGeoKey",t[t.ProjStdParallel1GeoKey=3078]="ProjStdParallel1GeoKey",t[t.ProjStdParallel2GeoKey=3079]="ProjStdParallel2GeoKey",t[t.ProjNatOriginLongGeoKey=3080]="ProjNatOriginLongGeoKey",t[t.ProjNatOriginLatGeoKey=3081]="ProjNatOriginLatGeoKey",t[t.ProjFalseEastingGeoKey=3082]="ProjFalseEastingGeoKey",t[t.ProjFalseNorthingGeoKey=3083]="ProjFalseNorthingGeoKey",t[t.ProjFalseOriginLongGeoKey=3084]="ProjFalseOriginLongGeoKey",t[t.ProjFalseOriginLatGeoKey=3085]="ProjFalseOriginLatGeoKey",t[t.ProjFalseOriginEastingGeoKey=3086]="ProjFalseOriginEastingGeoKey",t[t.ProjFalseOriginNorthingGeoKey=3087]="ProjFalseOriginNorthingGeoKey",t[t.ProjCenterLongGeoKey=3088]="ProjCenterLongGeoKey",t[t.ProjCenterLatGeoKey=3089]="ProjCenterLatGeoKey",t[t.ProjCenterEastingGeoKey=3090]="ProjCenterEastingGeoKey",t[t.ProjCenterNorthingGeoKey=3091]="ProjCenterNorthingGeoKey",t[t.ProjScaleAtNatOriginGeoKey=3092]="ProjScaleAtNatOriginGeoKey",t[t.ProjScaleAtCenterGeoKey=3093]="ProjScaleAtCenterGeoKey",t[t.ProjAzimuthAngleGeoKey=3094]="ProjAzimuthAngleGeoKey",t[t.ProjStraightVertPoleLongGeoKey=3095]="ProjStraightVertPoleLongGeoKey",t[t.ProjRectifiedGridAngleGeoKey=3096]="ProjRectifiedGridAngleGeoKey",t[t.VerticalCSTypeGeoKey=4096]="VerticalCSTypeGeoKey",t[t.VerticalCitationGeoKey=4097]="VerticalCitationGeoKey",t[t.VerticalDatumGeoKey=4098]="VerticalDatumGeoKey",t[t.VerticalUnitsGeoKey=4099]="VerticalUnitsGeoKey"})(P1||(P1={}));var Ae;(function(t){t[t.BYTE=1]="BYTE",t[t.ASCII=2]="ASCII",t[t.SHORT=3]="SHORT",t[t.LONG=4]="LONG",t[t.RATIONAL=5]="RATIONAL",t[t.SBYTE=6]="SBYTE",t[t.UNDEFINED=7]="UNDEFINED",t[t.SSHORT=8]="SSHORT",t[t.SLONG=9]="SLONG",t[t.SRATIONAL=10]="SRATIONAL",t[t.FLOAT=11]="FLOAT",t[t.DOUBLE=12]="DOUBLE",t[t.LONG8=16]="LONG8",t[t.SLONG8=17]="SLONG8",t[t.IFD8=18]="IFD8"})(Ae||(Ae={}));var ve;(function(t){t[t.UInt8=1]="UInt8",t[t.UInt16=2]="UInt16",t[t.UInt32=4]="UInt32",t[t.UInt64=8]="UInt64",t[t.Double=8]="Double",t[t.Float=4]="Float"})(ve||(ve={}));var h4=2**32,bS=typeof setImmediate>"u"?setTimeout:setImmediate,Dt=()=>{throw new Error("Method not implemented.")},ci=class{constructor(){this.isLittleEndian=!0,this.delayMs=ci.DefaultDelayMs,this.maxChunkCount=10,this.chunks=ci.DefaultChunkCache(),this.blankFillCount=16,this.maxConcurrentRequests=50,this.toFetch=new Set,this.toFetchPromise=null,this.byteOffset=0,this.getFloat32=Dt,this.getFloat64=Dt,this.getInt8=Dt,this.getInt16=Dt,this.getInt32=Dt,this.setFloat32=Dt,this.setFloat64=Dt,this.setInt8=Dt,this.setInt16=Dt,this.setInt32=Dt,this.setUint8=Dt,this.setUint16=Dt,this.setUint32=Dt,this.setBigInt64=Dt,this.setBigUint64=Dt}static getByteRanges(e,r=32,i=16){if(e.size===0)return{chunks:[],blankFill:[]};let n=[...e.values()].sort((d,m)=>d-m),o=[],a=[];o.push(a);let h=[];for(let d=0;d<n.length;++d){let m=n[d],p=n[d-1];if(a.length>=r)a=[m],o.push(a);else if(d===0||m===p+1)a.push(m);else if(m<p+i){for(let M=p;M<m;M++)a.push(M+1),h.push(M+1);h.pop()}else a=[m],o.push(a)}return{chunks:o,blankFill:h}}async fetchData(){if(this.toFetch.size===0)return;let e=this.toFetch;this.toFetch=new Set,this.toFetchPromise=null;let r=ci.getByteRanges(e,this.maxChunkCount,this.blankFillCount),i=[];for(let n of r.chunks){let o=n[0],a=n[n.length-1],h=o*this.chunkSize,d=a*this.chunkSize+this.chunkSize-h,m=await this.fetchBytes(h,d);if(n.length===1){i[o]=m,this.chunks.set(o,new DataView(m));continue}let p=o*this.chunkSize;for(let M of n){let R=M*this.chunkSize-p,x=m.slice(R,R+this.chunkSize);i[M]=x,this.chunks.set(M,new DataView(x))}}}async loadBytes(e,r){if(e<0)throw new Error("Offset must be positive");let i=Math.floor(e/this.chunkSize),n=Math.ceil((e+r)/this.chunkSize)-1;for(let o=i;o<=n;o++)this.chunks.has(o)||this.toFetch.add(o);if(this.toFetch.size!==0){if(this.toFetchPromise==null&&(this.toFetchPromise=new Promise(o=>bS(o,this.delayMs)).then(()=>this.fetchData())),this.toFetch.size>this.maxConcurrentRequests)throw new Error("Too many outstanding requests");await this.toFetchPromise}}getChunkId(e){return Math.floor(e/this.chunkSize)}getUint(e,r){switch(r){case ve.UInt8:return this.getUint8(e);case ve.UInt16:return this.getUint16(e);case ve.UInt32:return this.getUint32(e);case ve.UInt64:return this.getUint64(e)}}bytes(e,r){let i=this.isOneChunk(e,r);if(i){let m=this.getView(i),p=e-i*this.chunkSize;return new Uint8Array(m.buffer.slice(p,p+r))}let n=new Uint8Array(r),o=e+r,a=Math.floor(e/this.chunkSize),h=Math.ceil((e+r)/this.chunkSize)-1,d=0;for(let m=a;m<=h;m++){let p=e+d,M=m*this.chunkSize,R=this.getView(m),x=Math.min(o,M+this.chunkSize),w=R.buffer.slice(p-M,x-M);n.set(new Uint8Array(w),d),d+=w.byteLength}return n}getView(e){let r=this.chunks.get(e);if(r==null)throw new Error(`Chunk:${e} is not ready`);return r}isOneChunk(e,r){let i=e+r-1,n=Math.floor(e/this.chunkSize);return Math.floor(i/this.chunkSize)-n<1?n:null}hasBytes(e,r=1){let i=Math.floor(e/this.chunkSize),n=Math.ceil((e+r)/this.chunkSize)-1;for(let o=i;o<=n;o++)if(!this.chunks.has(o))return!1;return!0}toRange(e,r){if(r==null)return`bytes=${e}`;if(e<0)throw new Error("Cannot read from remote source with negative offset and length");return`bytes=${e}-${e+r}`}parseContentRange(e){let[r,i]=e.split(" ");if(r!=="bytes")throw new Error("Failed to parse content-range: "+e);if(i==null)throw new Error("Failed to parse content-range: "+e);let[,n]=i.split("/"),o=Number(n);if(isNaN(o))throw new Error("Failed to parse content-range: "+e);return o}get buffer(){throw new Error("Method not implemented.")}get byteLength(){if(this._byteLength)return this._byteLength;throw Error(".size() has not been fetched.")}getUint8(e){let r=Math.floor(e/this.chunkSize),i=this.chunks.get(r);if(i==null)throw new Error(`Chunk:${r} is not ready`);return i.getUint8(e-r*this.chunkSize)}getUint16(e){let r=this.isOneChunk(e,ve.UInt16);if(r!=null)return this.getView(r).getUint16(e-r*this.chunkSize,this.isLittleEndian);let i=this.getUint8(e),n=this.getUint8(e+ve.UInt8);return this.isLittleEndian?i+(n<<8):(i<<8)+n}getUint32(e){let r=this.isOneChunk(e,ve.UInt32);if(r!=null)return this.getView(r).getUint32(e-r*this.chunkSize,this.isLittleEndian);let i=this.getUint16(e),n=this.getUint16(e+ve.UInt16);return this.isLittleEndian?i+n*65536:i*65536+n}getUint64(e){let r=this.isOneChunk(e,ve.UInt64);if(r!=null){let o=this.getView(r);return Number(o.getBigUint64(e-r*this.chunkSize,this.isLittleEndian))}let i=this.getUint32(e),n=this.getUint32(e+ve.UInt32);return this.isLittleEndian?i+n*h4:i*h4+n}getBigUint64(e){let r=this.isOneChunk(e,ve.UInt64);if(r!=null)return this.getView(r).getBigUint64(e-r*this.chunkSize,this.isLittleEndian);let i=BigInt(this.getUint32(e)),n=BigInt(this.getUint32(e+ve.UInt32));return this.isLittleEndian?i+(n<<BigInt(32)):(i<<BigInt(32))+n}getBigInt64(){throw new Error("Not implemented.")}};ci.DefaultChunkCache=()=>new Map;ci.DefaultDelayMs=1;var c4=de(vd(),1);function f4(t){switch(t){case Ae.BYTE:case Ae.ASCII:case Ae.SBYTE:case Ae.UNDEFINED:return 1;case Ae.SHORT:case Ae.SSHORT:return 2;case Ae.LONG:case Ae.SLONG:case Ae.FLOAT:return 4;case Ae.RATIONAL:case Ae.SRATIONAL:case Ae.DOUBLE:case Ae.LONG8:case Ae.SLONG8:case Ae.IFD8:return 8;default:throw new Error(`Invalid fieldType ${t}`)}}var Es={char:(t,e)=>String.fromCharCode(t.getUint8(e)),uint8:(t,e)=>t.getUint8(e),uint16:(t,e)=>t.getUint16(e),uint32:(t,e)=>t.getUint32(e),uint64:(t,e)=>t.getUint64(e),double:(t,e)=>c4.read(t.bytes(e,ve.Double),0,t.isLittleEndian,52,8),rational:(t,e)=>[t.getUint32(e),t.getUint32(e+4)]};function hh(t){switch(t){case Ae.ASCII:return Es.char;case Ae.BYTE:case Ae.UNDEFINED:case Ae.SBYTE:return Es.uint8;case Ae.SHORT:case Ae.SSHORT:return Es.uint16;case Ae.LONG:case Ae.SLONG:return Es.uint32;case Ae.RATIONAL:case Ae.SRATIONAL:return Es.rational;case Ae.DOUBLE:return Es.double;case Ae.LONG8:return Es.uint64;default:throw new Error(`Unknown read type "${t}" "${Ae[t]}"`)}}var Cn=class{constructor(e,r,i){this.tiff=r,this.byteOffset=i,this.id=e,this.name=ae[this.id],this.dataType=this.tiff.source.getUint16(i+2),this.dataCount=this.tiff.source.getUint(i+4,this.tiff.ifdConfig.pointer),this.dataTypeSize=f4(this.dataType),this.dataLength=this.dataTypeSize*this.dataCount}get hasBytes(){return this.tiff.source.hasBytes(this.valuePointer,this.dataLength)}get isReady(){return!0}get dataTypeName(){return Ae[this.dataType]}get valuePointer(){let e=this.size-this.tiff.ifdConfig.pointer;return this.isValueInline?this.byteOffset+e:this.tiff.source.getUint(this.byteOffset+e,this.tiff.ifdConfig.pointer)}get size(){return this.tiff.ifdConfig.ifd}get isValueInline(){return this.dataLength<=this.tiff.ifdConfig.pointer}readValue(){let e=this.valuePointer,r=this.dataTypeSize,i=hh(this.dataType),n=this.dataCount,o=n*r;if(n===1)return i(this.tiff.source,e);let a=[];for(let h=0;h<o;h+=r)a.push(i(this.tiff.source,e+h));return this.dataType===Ae.ASCII?a.join("").trim():a}toJSON(){return{id:this.id,name:this.name,offset:this.byteOffset,isReady:this.isReady,type:this.dataTypeName,value:this.value}}};var Rs=class extends Cn{constructor(){super(...arguments),this.value=null}get isReady(){return this.value!=null}async fetch(){return this.tiff.source.hasBytes(this.valuePointer,this.dataLength)===!1&&await this.tiff.source.loadBytes(this.valuePointer,this.dataLength),this.value=this.readValue(),this.value}};var O1=class extends Cn{constructor(e,r,i){super(e,r,i),this.loadedValues=null}get value(){return this.loadedValues!=null?this.loadedValues:this.hasBytes?(this.readValue(),this.loadedValues):null}async load(){await this.tiff.source.loadBytes(this.valuePointer,this.dataLength),this.readValue()}readValue(){let e=super.readValue();return typeof e=="number"?this.loadedValues=[e]:this.loadedValues=e,this.loadedValues}async getValueAt(e){if(this.loadedValues)return this.loadedValues[e];let r=this.dataTypeSize,i=this.valuePointer+r*e,n=hh(this.dataType);return this.tiff.source.hasBytes(i,r)||await this.tiff.source.loadBytes(i,r),n(this.tiff.source,i)}};var k1=class extends Cn{constructor(){super(...arguments),this._isRead=!1,this._value=null}get value(){return this._isRead===!1&&(this._value=this.readValue(),this._isRead=!0),this._value}};var ch={create(t,e){let r=t.source.getUint16(e);if(r===ae.TileOffsets||r===ae.TileByteCounts||r===ae.StripByteCounts||r===ae.StripOffsets)return new O1(r,t,e);let i=new k1(r,t,e);return i.hasBytes?i:new Rs(r,t,e)},isStatic(t){return t instanceof k1},isLazy(t){return t instanceof Rs},isOffsetArray(t){return t instanceof O1}};var vS=32767,fh=class{constructor(e,r,i){this.tagsGeoLoaded=!1,this.tagsGeo=new Map,this.tif=e,this.id=r,this.tags=i}async init(e=!1){let r=[this.fetch(ae.Compression),this.fetch(ae.ImageHeight),this.fetch(ae.ImageWidth),this.fetch(ae.ModelPixelScale),this.fetch(ae.ModelTiePoint),this.fetch(ae.ModelTransformation),this.fetch(ae.TileHeight),this.fetch(ae.TileWidth)];e&&(r.push(this.fetch(ae.GeoKeyDirectory)),r.push(this.fetch(ae.GeoAsciiParams)),r.push(this.fetch(ae.GeoDoubleParams))),await Promise.all(r),e&&await this.loadGeoTiffTags()}value(e){let r=this.tags.get(e);return r==null?null:r.value}async loadGeoTiffTags(){if(this.tagsGeoLoaded)return;let e=this.tags.get(ae.GeoKeyDirectory);if(e==null){this.tagsGeoLoaded=!0;return}if(!e.isReady&&e instanceof Rs&&await Promise.all([this.fetch(ae.GeoKeyDirectory),this.fetch(ae.GeoAsciiParams),this.fetch(ae.GeoDoubleParams)]),this.tagsGeoLoaded=!0,e.value==null)return;let r=e.value;if(!Array.isArray(r))throw new Error("Invalid geo tags found");for(let i=4;i<=r[3]*4;i+=4){let n=r[i],o=r[i+1],a=r[i+3];if(o===0){this.tagsGeo.set(n,a);continue}let h=this.tags.get(o);if(h==null||h.value==null)continue;let d=r[i+2];Array.isArray(h.value)?this.tagsGeo.set(n,h.value[a+d-1]):typeof h.value=="string"&&this.tagsGeo.set(n,h.value.substr(a,a+d-1).trim())}}valueGeo(e){if(this.tagsGeoLoaded===!1)throw new Error("loadGeoTiffTags() has not been called");return this.tagsGeo.get(e)}async fetch(e){let r=this.tags.get(e);return r==null?null:ch.isLazy(r)?r.fetch():r.value}get origin(){let e=this.value(ae.ModelTiePoint);if(e!=null&&e.length===6)return[e[3],e[4],e[5]];let r=this.value(ae.ModelTransformation);if(r!=null)return[r[3],r[7],r[11]];if(this.value(ae.NewSubFileType)===1&&this.id!==0)return this.tif.images[0].origin;throw new Error("Image does not have a geo transformation.")}get isGeoLocated(){return this.value(ae.ModelPixelScale)!=null||this.value(ae.ModelTransformation)!=null?!0:this.value(ae.NewSubFileType)===1&&this.id!==0?this.tif.images[0].isGeoLocated:!1}get resolution(){let e=this.value(ae.ModelPixelScale);if(e!=null)return[e[0],-e[1],e[2]];let r=this.value(ae.ModelTransformation);if(r!=null)return[r[0],r[5],r[10]];if(this.value(ae.NewSubFileType)===1&&this.id!==0){let i=this.tif.images[0],[n,o,a]=i.resolution,h=i.size,d=this.size;return[n*h.width/d.width,o*h.height/d.height,a]}throw new Error("Image does not have a geo transformation.")}get bbox(){let e=this.size,r=this.origin,i=this.resolution;if(r==null||e==null||i==null)throw new Error("Unable to calculate bounding box");let n=r[0],o=r[1],a=n+i[0]*e.width,h=o+i[1]*e.height;return[Math.min(n,a),Math.min(o,h),Math.max(n,a),Math.max(o,h)]}get compression(){let e=this.value(ae.Compression);return e==null||typeof e!="number"?null:yd[e]}get epsg(){let e=this.valueGeo(P1.ProjectedCSTypeGeoKey);return e===vS?null:e}get size(){return{width:this.value(ae.ImageWidth),height:this.value(ae.ImageHeight)}}get tagList(){return[...this.tags.keys()].map(e=>ae[e])}isTiled(){return this.value(ae.TileWidth)!==null}get tileSize(){return{width:this.value(ae.TileWidth),height:this.value(ae.TileHeight)}}get tileCount(){let e=this.size,r=this.tileSize,i=Math.ceil(e.width/r.width),n=Math.ceil(e.height/r.height);return{x:i,y:n}}get tileOffset(){let e=this.tags.get(ae.TileOffsets);if(e==null)throw new Error("No tile offsets found");return e}get stripCount(){let e=this.tags.get(ae.StripByteCounts);return e==null?0:e.dataCount}async getTileOffset(e){let r=this.tileOffset;if(e<0||e>r.dataCount)throw new Error(`Tile offset: ${e} out of range: 0 -> ${r.dataCount}`);return r.getValueAt(e)}getTileBounds(e,r){let{size:i,tileSize:n}=this,o=r*n.height,a=e*n.width,h=a+n.width>=i.width?i.width-a:n.width,d=o+n.height>=i.height?i.height-o:n.height;return{x:a,y:o,width:h,height:d}}async getStrip(e){if(this.isTiled())throw new Error("Cannot read stripes, tiff is tiled");let r=this.tags.get(ae.StripByteCounts),i=this.tags.get(ae.StripOffsets);if(e>=r.dataCount)throw new Error("Cannot read strip, index out of bounds");let[n,o]=await Promise.all([i.getValueAt(e),r.getValueAt(e)]);return this.getBytes(n,o)}getJpegHeader(e){let r=this.value(ae.JPEGTables);if(r==null)throw new Error("Unable to find Jpeg header");let i=r.slice(0,r.length-2),n=new Uint8Array(e.byteLength+i.length-2);return n.set(i,0),n.set(e.slice(2),i.length),n}async getBytes(e,r){let i=this.compression;if(i==null)throw new Error("Unsupported compression: "+this.value(ae.Compression));if(r===0)return null;await this.tif.source.loadBytes(e,r);let n=this.tif.source.bytes(e,r);return this.compression===Cr.JPEG?{mimeType:i,bytes:this.getJpegHeader(n)}:{mimeType:i,bytes:n}}async getTile(e,r){let i=this.compression,n=this.size,o=this.tileSize;if(o==null)throw new Error("Tiff is not tiled");if(i==null)throw new Error("Unsupported compression: "+this.value(ae.Compression));let a=Math.ceil(n.height/o.height),h=Math.ceil(n.width/o.width);if(e>=h||r>=a)throw new Error(`Tile index is outside of range x:${e} >= ${h} or y:${r} >= ${a}`);let d=r*h+e,m=h*a;if(d>=m)throw new Error(`Tile index is outside of tile range: ${d} >= ${m}`);let{offset:p,imageSize:M}=await this.getTileSize(d);return this.getBytes(p,M)}async getTileSize(e){if(this.tif.options.tileLeaderByteSize){let o=await this.getTileOffset(e);if(o===0)return{offset:0,imageSize:0};let a=this.tif.options.tileLeaderByteSize;return await this.tif.source.loadBytes(o-a,a),{offset:o,imageSize:this.tif.source.getUint(o-a,a)}}let r=this.tags.get(ae.TileByteCounts);if(r==null)throw new Error("No tile byte counts found");let[i,n]=await Promise.all([this.getTileOffset(e),r.getValueAt(e)]);return{offset:i,imageSize:n}}};var L1;(function(t){t[t.Big=19789]="Big",t[t.Little=18761]="Little"})(L1||(L1={}));var Ar;(function(t){t[t.BigTiff=43]="BigTiff",t[t.Tiff=42]="Tiff"})(Ar||(Ar={}));var wd="__reverse";function d4(t,e){if(t[wd]==null){let r={};for(let i of Object.keys(t)){let n=t[i];r[n]=i}Object.defineProperty(t,wd,{enumerable:!1,value:r,writable:!1})}return t[wd][e]}var An;(function(t){t.GDAL_STRUCTURAL_METADATA_SIZE="GDAL_STRUCTURAL_METADATA_SIZE",t.LAYOUT="LAYOUT",t.BLOCK_ORDER="BLOCK_ORDER",t.BLOCK_LEADER="BLOCK_LEADER",t.BLOCK_TRAILER="BLOCK_TRAILER",t.KNOWN_INCOMPATIBLE_EDITION="KNOWN_INCOMPATIBLE_EDITION",t.MASK_INTERLEAVED_WITH_IMAGERY="MASK_INTERLEAVED_WITH_IMAGERY"})(An||(An={}));var _d;(function(t){t.RowMajor="ROW_MAJOR"})(_d||(_d={}));var xd;(function(t){t.uint32="SIZE_AS_UINT4"})(xd||(xd={}));var wS={uint32:ve.UInt32},dh=class{constructor(){this.options=new Map}get isCogOptimized(){return this.isBroken?!1:this.options.get(An.LAYOUT)==="IFDS_BEFORE_DATA"}get isBroken(){return this.options.get(An.KNOWN_INCOMPATIBLE_EDITION)==="YES"}set(e,r){this.options.set(e,r)}process(e,r,i){let n=[];for(let a=r;a<r+i;a++){let h=e.getUint8(a);h!==0&&n.push(String.fromCharCode(h))}let o=n.join("").trim().split(`
183
+ AUTHORITY["EPSG","2193"]]`;Zo.default.defs(Re.Nztm2000.toEpsgString(),n6);Zo.default.defs(Re.Citm2000.toEpsgString(),i6);var Y0=new Map;function Ox(t){return t==null?null:typeof t=="number"?t:"code"in t?t.code:"projection"in t?t.projection.code:null}var jr=class{constructor(e){this.epsg=e;try{this.projection=(0,Zo.default)(e.toEpsgString(),Re.Wgs84.toEpsgString())}catch(r){throw new it(`Failed to create projection: ${e.toEpsgString()}, ${Re.Wgs84.toEpsgString()}`,500,r)}}static define(e,r){if(Y0.get(e.code)!=null)throw new Error("Duplicate projection definition: "+e.toEpsgString());Zo.default.defs(e.toEpsgString(),r)}static get(e){let r=this.tryGet(e);if(r==null)throw new Error(`Invalid projection: ${e}`);return r}static tryGet(e){let r=Ox(e);if(r==null)return null;let i=Y0.get(r);if(i!=null)return i;let n=Re.tryGet(r);return n==null||Zo.default.defs(n.toEpsgString())==null?null:(i=new jr(n),Y0.set(r,i),i)}projectMultipolygon(e,r){if(r.epsg.code===this.epsg.code)return e;let{toWgs84:i}=this,{fromWgs84:n}=r;return e.map(o=>o.map(a=>a.map(h=>n(i(h)))))}get toWgs84(){return this.projection.forward}get fromWgs84(){return this.projection.inverse}boundsToWgs84BoundingBox(e){let r=this.toWgs84([e.x,e.y]),i=this.toWgs84([e.x+e.width,e.y+e.height]);return[r[0],r[1],i[0],i[1]]}boundsToGeoJsonFeature(e,r={}){let i=[e.x,e.y],n=[e.x+e.width,e.y],o=[e.x,e.y+e.height],a=[e.x+e.width,e.y+e.height],h=Yu([[[i,o,a,n,i]]],this.toWgs84),d=h.length===1?e6(h[0],r):t6(h,r);return d.bbox=this.boundsToWgs84BoundingBox(e),d}toGeoJson(e){return{type:"FeatureCollection",features:e.map(r=>this.boundsToGeoJsonFeature(r,{name:r.name}))}}static getTiffResZoom(e,r,i=1){let n=0;for(;n<e.zooms.length;++n)if(e.pixelScale(n)<=r*i)return n;if(n===e.zooms.length)return n-1;throw new Error("ResZoom not found")}static tileToWgs84Bbox(e,r){let i=e.tileToSource(r),n=e.tileToSource({x:r.x+1,y:r.y+1,z:r.z}),o=this.get(e),[a,h]=o.toWgs84([i.x,n.y]),[d,m]=o.toWgs84([n.x,i.y]);return[a,h,d,m]}static tileCenterToLatLon(e,r){let i=e.tileToSource({x:r.x+.5,y:r.y+.5,z:r.z}),[n,o]=this.get(e).toWgs84([i.x,i.y]);return jr.wrapLatLon(o,n)}static wrapLatLon(e,r){let i={lat:e,lon:r},n=Math.floor(Math.abs(e)/90)%4,o=e>0?90:-90,a=e%90;switch(n){case 0:i.lat=a;break;case 1:i.lat=o-a,i.lon+=180;break;case 2:i.lat=-a,i.lon+=180;break;case 3:i.lat=-o+a;break}return(i.lon>180||i.lon<-180)&&(i.lon-=Math.floor((i.lon+180)/360)*360),i}static findAlignmentLevels(e,r,i){return Math.max(0,this.getTiffResZoom(e,i,2)-r.z)}static getImagePixelWidth(e,r,i){let n=e.tileToSource(r),o=e.tileToSource({x:r.x+1,y:r.y+1,z:r.z});return Math.round((o.x-n.x)/e.pixelScale(i))*2}};function s6(t){return t==null||typeof t=="string"?!1:"roleArn"in t&&typeof t.roleArn=="string"}var o6=de(require("aws-sdk/lib/core.js"),1),a6=de(require("aws-sdk/clients/s3.js"),1);function Yo(t){return"promise"in t?t.promise():t}function Xo(t,e){return Ei(t)?typeof t.statusCode!="number"?new it(e,500,t):new it(e,t.statusCode,t):new it(e,500,t)}var Jt=class extends Rt{constructor(e,r,i){super(),this.type=Jt.type,this.protocol="s3",this.chunkSize=Jt.DefaultChunkSize,this.maxChunkCount=Jt.DefaultMaxChunkCount,this.bucket=e,this.key=r,this.remote=i}get uri(){return this.name}get name(){return`s3://${this.bucket}/${this.key}`}static isSource(e){return e.type===Jt.type}get size(){return this._size?this._size:(this._size=Promise.resolve().then(async()=>(await Yo(this.remote.headObject({Bucket:this.bucket,Key:this.key}))).ContentLength||-1),this._size)}static fromUri(e,r){let i=Qr(e);return i==null||i.key==null||i.protocol!=="s3"?null:new Jt(i.bucket,i.key,r)}async fetchBytes(e,r){let i=this.toRange(e,r);try{let n=await this.remote.getObject({Bucket:this.bucket,Key:this.key,Range:i}).promise();if(!Buffer.isBuffer(n.Body))throw new Error("Failed to fetch object, Body is not a buffer");n.ContentRange!=null&&this._size==null&&(this._size=Promise.resolve(this.parseContentRange(n.ContentRange)));let o=n.Body;return o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)}catch(n){throw Xo(n,`Failed to fetch ${this.name} ${i}`)}}};Jt.type="aws:s3";Jt.DefaultChunkSize=64*1024;Jt.DefaultMaxChunkCount=32;var Zt=class{constructor(e){this.protocol=Zt.protocol,this.s3=e}source(e){let r=Jt.fromUri(e,this.s3);if(r==null)throw new Error(`Failed to create aws s3 source from uri: ${e}`);return r}static is(e){return e.protocol===Zt.protocol}static isPath(e){return e==null?!1:e.startsWith("s3://")}async*list(e,r){for await(let i of this.details(e,r))yield i.path}async*details(e,r){let i=Qr(e);if(i==null)return;let n,o=r?.recursive===!1?"/":void 0,a=i.bucket,h=i.key,d=0;try{for(;;){d++;let m=await Yo(this.s3.listObjectsV2({Bucket:a,Prefix:h,ContinuationToken:n,Delimiter:o}));if(m.CommonPrefixes!=null)for(let p of m.CommonPrefixes)p.Prefix!=null&&(yield{path:`s3://${a}/${p.Prefix}`,isDirectory:!0});if(m.Contents!=null)for(let p of m.Contents)p.Key!=null&&(yield{path:`s3://${a}/${p.Key}`,size:p.Size});if(!m.IsTruncated)break;if(d>=Zt.MaxListCount)throw new Error(`Failed to finish listing within ${Zt.MaxListCount} list attempts`);n=m.NextContinuationToken}}catch(m){throw Xo(m,`Failed to list: "${e}"`)}}async read(e){let r=Qr(e);if(r==null||r.key==null)throw new Error(`Failed to read: "${e}"`);try{return(await this.s3.getObject({Bucket:r.bucket,Key:r.key}).promise()).Body}catch(i){throw Xo(i,`Failed to read: "${e}"`)}}async write(e,r,i){let n=Qr(e);if(n==null||n.key==null)throw new Error(`Failed to write: "${e}"`);try{await Yo(this.s3.upload({Bucket:n.bucket,Key:n.key,Body:r,ContentEncoding:i?.contentEncoding,ContentType:i?.contentType}))}catch(o){throw Xo(o,`Failed to write: "${e}"`)}}exists(e){return this.head(e).then(r=>r!=null)}stream(e){let r=Qr(e);if(r==null||r.key==null)throw new Error(`S3: Unable to read "${e}"`);return this.s3.getObject({Bucket:r.bucket,Key:r.key}).createReadStream()}async head(e){let r=Qr(e);if(r==null||r.key==null)throw new Error(`Failed to exists: "${e}"`);try{return{size:(await Yo(this.s3.headObject({Bucket:r.bucket,Key:r.key}))).ContentLength,path:e}}catch(i){if(Ei(i)&&i.code==="NotFound")return null;throw Xo(i,`Failed to exists: "${e}"`)}}};Zt.protocol="s3";Zt.MaxListCount=100;var Yt=class{static fsFromRole(e,r,i){if(typeof e=="object")return Yt.fsFromRole(e.roleArn,e.externalId,e.durationSeconds);let n=Yt.role(e,r,i);return new Zt(new a6.default({credentials:n}))}static role(e,r,i){i=i??Yt.DefaultRoleDurationSeconds;let n=`role::${e}::${r}::${i}`,o=Yt.cache.get(n);return o==null&&(o=new o6.default.ChainableTemporaryCredentials({params:{RoleArn:e,ExternalId:r,RoleSessionName:"fsa-"+Math.random().toString(32)+"-"+Date.now(),DurationSeconds:i}}),Yt.cache.set(n,o)),o}};Yt.DefaultRoleDurationSeconds=3600;Yt.cache=new Map;var l6=de(require("aws-sdk/clients/s3.js"),1),u6=require("util"),Xu=require("zlib");var kx=(0,u6.promisify)(Xu.gunzip),Er=nt;Er.readJson=async function(e){let r=await this.read(e);return e.endsWith(".gz")?JSON.parse((await kx(r)).toString()):JSON.parse(r.toString())};Er.writeJson=async function(e,r){let i=Buffer.from(JSON.stringify(r,void 0,2));if(e.endsWith(".gz")){let n=(0,Xu.createGzip)();return n.end(i),this.write(e,n)}else return this.write(e,i)};Er.configure=function(e){if(e.type!=="s3"||!s6(e))return;let r=Qr(e.path);if(r==null)throw new Error("Failed to parse URI: "+e.path);let i=`s3://${r.bucket}/`;this.register(i,Yt.fsFromRole(e.roleArn,e.externalId))};Er.register("s3://",new Zt(new l6.default));function X0(t){return t[0].toUpperCase()+t.slice(1).replace(/_(\d+)-(\d+)m/g," $1.$2m").replace(/_/g," ")}function h6(t){let e=/(?:^|\D)(\d{4})(?:-(\d{2}))?(?:$|\D)/g,r=[];for(let i=e.exec(t);i!=null;i=e.exec(t))r.push(parseInt(i[1])),i[2]!=null&&r.push(parseInt(i[1].slice(0,2)+i[2]));return r.length===0?[-1,-1]:(r.sort(),[r[0],r[r.length-1]+1])}process.env.AWS_NODEJS_CONNECTION_REUSE_ENABLED="1";_e.setConfigProvider(new Va(u1.TileMetadata.TableName));var s4=de(t0(),1);var Mn="application/json",re;(function(t){t.CacheControl="Cache-Control",t.ContentEncoding="Content-Encoding",t.ContentType="Content-Type",t.Cors="Access-Control-Allow-Origin",t.ETag="ETag",t.IfNoneMatch="If-None-Match",t.Server="Server",t.ServerTiming="Server-Timing"})(re||(re={}));var Qo;(function(t){t.CloudfrontId="X-Amz-Cf-Id",t.TraceId="X-Amzn-Trace-Id"})(Qo||(Qo={}));var $r;(function(t){t.CorrelationId="X-LINZ-Correlation-Id",t.RequestId="X-LINZ-Request-Id"})($r||($r={}));var _s=class{constructor(){if(this.timers=new Map,typeof process<"u"&&typeof process.hrtime.bigint=="function"){let e=BigInt(1e6);this.getTime=()=>Number(process.hrtime.bigint()/e)}else typeof typeof performance<"u"?this.getTime=()=>performance.now():this.getTime=()=>Date.now()}start(e){let r=this.timers.get(e);if(r!=null&&r.duration==null)throw new Error(`Duplicate startTime for "${e}"`);this.timers.set(e,{start:this.getTime()})}end(e){let r=this.timers.get(e);if(r==null)throw new Error(`Missing startTime information for "${e}"`);let i=this.getTime()-r.start;return r.duration=i,i}get metrics(){if(this.timers.size===0)return;let e={};for(let[r,i]of this.timers.entries())i.duration!=null&&(e[r]=i.duration);return e}get unfinished(){let e=[];for(let[r,i]of this.timers.entries())i.duration==null&&e.push(r);if(e.length!==0)return e}};var c6=de(Xn(),1);function Bt(t){return!(typeof t!="object"||t==null)}var xs=class{constructor(e,r,i){this.logContext={},this.timer=new _s,this.headers=new Map,this.context=r,this.event=e,this.id=(0,c6.ulid)(),this.log=i,this.timer=new _s,this.log=i.child({id:this.id,aws:{lambdaId:r.awsRequestId}})}set(e,r){r==null&&(r=void 0),this.logContext[e]=r}toResponse(e){return e?.body}};var d6=require("url");var f6=de(Xn(),1);var or=class extends xs{constructor(e,r,i){var n;super(e,r,i),this.headers=new Map,this.correlationId=(n=this.header($r.CorrelationId))!==null&&n!==void 0?n:f6.ulid(),this.set("correlationId",this.correlationId)}header(e){return this._isHeadersLoaded!==!0&&(this.loadHeaders(),this._isHeadersLoaded=!0),this.headers.get(e.toLowerCase())}json(){var e;if(this.header(re.ContentType)!==Mn)throw new Error(`Invalid Content-Type: "${this.header("content-type")}"`);if(this.body==null)throw new Error("Cannot parse empty body as JSON");try{return this.isBase64Encoded?JSON.parse(Buffer.from((e=this.body)!==null&&e!==void 0?e:"","base64").toString()):JSON.parse(this.body)}catch{throw new Error("Body is not a JSON object")}}get query(){return this._query==null&&(this._query=this.loadQueryString()),this._query}get url(){return this.path}};var ea=class extends or{static is(e){return Bt(e)&&Bt(e.requestContext)&&Bt(e.requestContext.elb)}toResponse(e){return{statusCode:e.status,statusDescription:e.statusDescription,body:e.body,headers:this.toHeaders(e.headers),isBase64Encoded:e.isBase64Encoded}}toHeaders(e){if(e.size===0)return;let r={};for(let i of e)r[i[0]]=i[1];return r}loadHeaders(){if(this.event.headers!=null)for(let[e,r]of Object.entries(this.event.headers))r!=null&&this.headers.set(e.toLowerCase(),r)}loadQueryString(){let e=new d6.URLSearchParams;if(this.event.queryStringParameters==null)return e;for(let[r,i]of Object.entries(this.event.queryStringParameters))e.append(r.toLowerCase(),i??"true");return e}get method(){return this.event.httpMethod.toUpperCase()}get path(){return this.event.path}get body(){return this.event.body}get isBase64Encoded(){return this.event.isBase64Encoded}};var m6=require("url");var hi=class extends or{static is(e){return!(!Bt(e)||!Bt(e.requestContext)||typeof e.requestContext.apiId!="string"||typeof e.requestContext.resourceId!="string"||typeof e.requestContext.httpMethod!="string")}toResponse(e){return{statusCode:e.status,body:e.body,headers:hi.toHeaders(e),isBase64Encoded:e.isBase64Encoded}}static toHeaders(e){if(e.headers.size===0)return;let r={};for(let i of e.headers)r[i[0]]=i[1];return r}loadHeaders(){if(this.event.headers!=null)for(let[e,r]of Object.entries(this.event.headers))r!=null&&this.headers.set(e.toLowerCase(),r)}loadQueryString(){let e=new m6.URLSearchParams;if(this.event.multiValueQueryStringParameters==null)return e;for(let[r,i]of Object.entries(this.event.multiValueQueryStringParameters))if(i!=null)for(let n of i)e.append(r.toLowerCase(),n);return e}get path(){return this.event.path}get method(){return this.event.httpMethod.toUpperCase()}get body(){return this.event.body}get isBase64Encoded(){return this.event.isBase64Encoded}};var Q0=require("url");var ta=class extends or{static is(e){if(!Bt(e)||!Array.isArray(e.Records))return!1;let r=e.Records[0];return Bt(r)?Bt(r.cf):!1}toResponse(e){if(e.status===100&&this.event!=null){let r=this.event.Records[0].cf.request;for(let[i,n]of e.headers)r.headers[i.toLowerCase()]=[{key:i,value:String(n)}];return this.event.Records[0].cf.request}return{status:String(e.status),statusDescription:e.statusDescription,body:e.body,headers:this.toHeaders(e),bodyEncoding:"text"}}toHeaders(e){if(e.headers.size===0)return{};let r={};for(let i of e.headers)r[i[0]]=[{key:i[0],value:String(i[1])}];return r}loadHeaders(){var e;for(let[r,i]of Object.entries(this.event.Records[0].cf.request.headers))this.headers.set(r.toLowerCase(),(e=i[0])===null||e===void 0?void 0:e.value)}loadQueryString(){let e=this.event.Records[0].cf.request.querystring;return e==null?new Q0.URLSearchParams:new Q0.URLSearchParams(e.toLowerCase())}get path(){return this.event.Records[0].cf.request.uri}get method(){return this.event.Records[0].cf.request.method.toUpperCase()}get body(){let e=this.event.Records[0].cf.request.body;return e==null?null:e.data}get isBase64Encoded(){var e;return((e=this.event.Records[0].cf.request.body)===null||e===void 0?void 0:e.encoding)==="base64"}};var ee=class{constructor(e,r,i){if(this._body=null,this.headers=new Map,this.status=e,this.statusDescription=r,i!=null)for(let n of Object.keys(i))this.header(n,i[n])}static is(e){return e instanceof ee}static ok(e=200,r="Ok"){return new ee(e,r)}header(e,r){let i=e.toLowerCase();if(r==null)return this.headers.get(i);this.headers.set(i,r)}get isBase64Encoded(){return Buffer.isBuffer(this._body)}json(e){return this.buffer(JSON.stringify(e),Mn),this}buffer(e,r=Mn){return this.header(re.ContentType,r),this._body=e,this}get body(){return this._body==null?(this.header(re.ContentType,Mn),JSON.stringify({id:this.header($r.RequestId),status:this.status,message:this.statusDescription,correlationId:this.header($r.CorrelationId)})):Buffer.isBuffer(this._body)?this._body.toString("base64"):this._body}};var t4=de(e4(),1);var lh=class{constructor(){this.hooks={request:[],response:[]},this.router=(0,t4.default)({defaultRoute:()=>new ee(404,"Not found")})}register(e,r,i){this.router.on(e,r,async(n,o,a)=>n instanceof or?(n.params=a,uh(n,i)):new ee(500,"Internal server error"))}hook(e,r){this.hooks[e].push(r)}get(e,r){return this.register("GET",e,r)}post(e,r){return this.register("POST",e,r)}delete(e,r){return this.register("DELETE",e,r)}options(e,r){return this.register("OPTIONS",e,r)}patch(e,r){return this.register("PATCH",e,r)}head(e,r){return this.register("HEAD",e,r)}put(e,r){return this.register("PUT",e,r)}async after(e,r){try{for(let i of this.hooks.response)await i(e,r)}catch(i){return ee.is(i)?i:(e.set("err",i),new ee(500,"Internal Server Error"))}return r}async handle(e){for(let i of this.hooks.request){let n=await uh(e,i);if(n)return this.after(e,n)}let r=await this.router.lookup(e,null);return r?this.after(e,r):this.after(e,new ee(404,"Not found"))}};var r4=require("url");var Rn=class extends or{toResponse(e){return{statusCode:e.status,body:e.body,headers:hi.toHeaders(e),isBase64Encoded:e.isBase64Encoded}}loadHeaders(){for(let[e,r]of Object.entries(this.event.headers))this.headers.set(e.toLowerCase(),r)}loadQueryString(){return new r4.URLSearchParams(this.event.rawQueryString)}get method(){return this.event.requestContext.http.method.toUpperCase()}get path(){return this.event.rawPath}get isBase64Encoded(){return this.event.isBase64Encoded}get body(){return this.event.body==null?null:this.event.body}static is(e){return!(!Bt(e)||!Bt(e.requestContext)||!Bt(e.requestContext.http))}};var o4="v6.32.1",aS="4544a7d98667c5274142f1bb6bf61f02e4e5f618",i4={version:o4,hash:aS};async function uh(t,e){t.timer.timers.has("lambda")||t.timer.start("lambda");try{return await e(t)}catch(r){return ee.is(r)?r:(t.set("err",r),new ee(500,"Internal Server Error"))}}function n4(t,e){let r=200;ee.is(e)&&(r=e.status,t.set("description",e.statusDescription)),t.set("status",r),t.timer.timers.size>0&&t.set("metrics",t.timer.metrics),i4.hash&&t.set("package",i4);let i=t.timer.timers.has("lambda")?t.timer.end("lambda"):0;return t.set("unfinished",t.timer.unfinished),t.set("duration",i),t.set("@type","report"),r>499?t.log.error(t.logContext,"Lambda:Done"):r>399?t.log.warn(t.logContext,"Lambda:Done"):t.log.info(t.logContext,"Lambda:Done"),e}function lS(t){let e={rejectOnError:!0,tracePercent:0,...t};if(isNaN(e.tracePercent)||e.tracePercent>1)throw new Error("tracePercent is not between 0-1 :"+e.tracePercent);return e}var ar=class{static request(e,r,i){if(ea.is(e))return new ea(e,r,i);if(Rn.is(e))return new Rn(e,r,i);if(hi.is(e))return new hi(e,r,i);if(ta.is(e))return new ta(e,r,i);throw new Error("Request is not a a ALB, ApiGateway or Cloudfront event")}static handler(e,r,i){let n=lS(r);function o(a,h,d){let m=new xs(a,h,i??ar.Logger);n.tracePercent>0&&Math.random()<n.tracePercent&&(m.log.level="trace"),process.env.TRACE_LAMBDA&&(m.log.level="trace"),m.log.trace({event:a},"Lambda:Start");let p=h.awsRequestId;m.set("aws",{lambdaId:p}),uh(m,e).then(M=>{if(n4(m,M),ee.is(M)&&n.rejectOnError){if(m.logContext.err)return d(m.logContext.err);if(M.status>399)return d(m.toResponse(M))}return d(null,m.toResponse(M))})}return o}static http(e){let r=new lh;function i(n,o,a){let h=ar.request(n,o,e??ar.Logger),d=h.header(Qo.CloudfrontId),m=h.header(Qo.TraceId),p=o.awsRequestId;(d||m||p)&&h.set("aws",{cloudFrontId:d,traceId:m,lambdaId:p}),h.set("method",h.method),h.set("path",h.path),r.handle(h).then(M=>{var R;M.status===500&&M.header(re.CacheControl,"no-store"),M.header($r.RequestId,h.id),M.header($r.CorrelationId,h.correlationId);let x=(R=h.timer.metrics)===null||R===void 0?void 0:R.lambda;x!=null&&M.header(re.ServerTiming,`total;dur=${x}`),!M.isBase64Encoded&&M.header(re.ContentType)==null&&M.header(re.ContentType,Mn),ar.ServerName&&M.header(re.Server,`${ar.ServerName}-${o4}`),n4(h,M),a(null,h.toResponse(M))})}return i.router=r,i}};ar.Logger=(0,s4.default)();ar.ServerName="linz";var qe={key(t){return Buffer.isBuffer(t)||typeof t=="string"?Qn(t):Qn(JSON.stringify(t))},isNotModified(t,e){let r=t.header(re.IfNoneMatch);return r!=null&&r.indexOf(e)>-1?(t.set("cache",{hit:!0,match:r}),!0):!1}};var be=()=>new ee(404,"Not Found"),ct=()=>new ee(304,"Not modified");var uS=.2,aa=class{constructor(e){this.tms=e}async tile(e,r,i,n){let o=[];for(let a of e){let h=this.getTiles(a,r,i,n);h!=null&&(o=o.concat(h))}return o}getRasterTiffIntersection(e,r,i,n){let o=this.tms.tileToPixels(r,i),a=new xe(o.x,o.y,this.tms.tileSize,this.tms.tileSize),h=e.images[0].bbox,d=this.tms.sourceToPixels(h[0],h[3],n),m=this.tms.sourceToPixels(h[2],h[1],n),p=xe.fromUpperLeftLowerRight(d,m),M=p.intersection(a);return M==null?null:{tiff:p,intersection:M,tile:a}}createComposition(e,r,i,n,o){let a=xe.fromJson(e.getTileBounds(r,i)),h=a.scale(n,n).add(o.tiff).round(uS),d=h.intersection(o.tile);if(d==null)return null;let m=d.subtract(h);if(m.height<.5||m.width<.5)return null;let p=h.subtract(o.tile),M={tiff:e.tif,source:{x:r,y:i,imageId:e.id,width:a.width,height:a.height},y:Math.max(0,Math.round(p.y)),x:Math.max(0,Math.round(p.x))};if((a.width<e.tileSize.width||a.height<e.tileSize.height)&&(M.extract={width:a.width,height:a.height}),a.width!==h.width||a.height!==h.height){let R=a.width!==h.width?h.width/a.width:h.height/a.height;M.resize={width:h.width,height:h.height,scale:R}}return(m.y!==0||m.x!==0||m.height!==h.height||m.width!==h.width)&&(M.crop=m),M}getTiles(e,r,i,n){let o=this.getRasterTiffIntersection(e,r,i,n);if(o==null)return null;let a=this.tms.pixelScale(n),h=e.getImageByResolution(a),d=a/h.resolution[0],m=o.intersection.subtract(o.tiff),{tileSize:p,tileCount:M}=h,R=[],x=1/d;for(let w of aa.getRequiredTiles(m,d,p,M)){let E=this.createComposition(h,w.x,w.y,x,o);E!=null&&R.push(E)}return R.length===0?null:R}static*getRequiredTiles(e,r,i,n){let o=Math.max(Math.floor(e.x/i.width*r),0),a=Math.min(Math.ceil(e.right/i.width*r),n.x),h=Math.max(Math.floor(e.y/i.height*r),0),d=Math.min(Math.ceil(e.bottom/i.height*r),n.y);for(let m=o;m<a;m++)for(let p=h;p<d;p++)yield{x:m,y:p}}};var a4=[He.Jpeg,He.Webp,He.Png];function md(t){if(t==null)return null;let e=t.toLowerCase();return e===He.Png?He.Png:e===He.Webp?He.Webp:e===He.Jpeg||e==="jpg"?He.Jpeg:e===He.Avif?He.Avif:null}var l4=de(Xn(),1),hS=60*60*1e3,cS=24*hS,fS=91*cS;function dS(t){if(t==null)return{valid:!1,message:"missing"};if(!t.startsWith("c")&&!t.startsWith("d"))return{valid:!1,message:"malformed"};let e=t.slice(1).toUpperCase();try{let r=l4.decodeTime(e);if(t.startsWith("d"))return{valid:!0,message:"ok"};if(Date.now()-r>fS)return{valid:!1,message:"expired"}}catch{return{valid:!1,message:"malformed"}}return{valid:!0,message:"ok"}}var wt={apiKey(t){let e=t.query.get(u1.ApiKey.QueryString)??t.header("X-LINZ-Api-Key"),r=dS(e);if(!r.valid)throw new ee(400,"API Key Invalid: "+r.message);return t.set("api",e),e},getTileMatrixSet(t){return Yn.find(t)},getRequestedFormats(t){let e=[...t.query.getAll("format"),...t.query.getAll("tileFormat")];if(e.length===0)return null;let r=new Set;for(let i of e){let n=md(i);n!=null&&r.add(n)}return r.size===0?null:[...r.values()]},getTileFormat(t){let e=md(t);return e||(t===rr.MapboxVectorTiles?rr.MapboxVectorTiles:null)},xyz(t){wt.apiKey(t),t.set("tileSet",t.params.tileSet);let e=parseInt(t.params.x,10),r=parseInt(t.params.y,10),i=parseInt(t.params.z,10),n=wt.getTileMatrixSet(t.params.tileMatrix);if(n==null)throw new ee(404,"Tile Matrix not found");t.set("tileMatrix",n.identifier),t.set("projection",n.projection.code);let o=wt.getTileFormat(t.params.tileType);if(o==null)throw new ee(404,"Tile extension not found");if(t.set("extension",o),isNaN(i)||i>n.maxZoom||i<0)throw new ee(404,`Zoom not found: ${i}`);let a=n.zooms[i];if(isNaN(e)||e<0||e>a.matrixWidth)throw new ee(404,`X not found: ${e}`);if(isNaN(r)||r<0||r>a.matrixHeight)throw new ee(404,`Y not found: ${r}`);let h={tile:{x:e,y:r,z:i},tileSet:t.params.tileSet,tileMatrix:n,tileType:o};t.set("xyz",h.tile);let d=jr.tileCenterToLatLon(n,h.tile);return t.set("location",d),h}};var mS=1+1e-10,u4=10**8;function pd(t){return Math.round(t*u4)/u4}function pS(t){return[pd(t[0]),pd(t[1])]}function gS(t,e,r){if(Sn.delta(t[0],t[2])<=0)return Sn.bboxToMultiPolygon(t);let i=[];for(let o of e){let a=[xe.fromJson(o).pad(mS).toPolygon()];i=Qp(i,a)}return Yu(i,o=>pS(r.toWgs84(o)))}async function yS(t,e,r){let i=jr.get(r),n=[],o=[],a=await _e.getAllImagery(e.layers,[r.projection]),h=await _e.Provider.get(_e.Provider.id("linz"));if(h==null)return null;for(let d of e.layers){let m=d[i.epsg.code];if(m==null)continue;let p=a.get(m);if(p==null)continue;let M=i.boundsToWgs84BoundingBox(p.bounds).map(pd),R=h6(p.name);if(R[0]===-1)throw new Error("Missing date in imagery name: "+p.name);let x=[R.map(C=>`${C}-01-01T00:00:00Z`)],w={spatial:{bbox:[M]},temporal:{interval:x}};o.push({type:"Feature",stac_version:Ka.Version,id:m+"_item",collection:m,assets:{},links:[],bbox:M,geometry:{type:"MultiPolygon",coordinates:gS(M,p.files,i)},properties:{title:p.title??X0(p.name),category:p.category,datetime:null,start_datetime:x[0][0],end_datetime:x[0][1]}});let E=Mt.convertZoomLevel(d.minZoom?d.minZoom:0,lt,r,!0),T=Mt.convertZoomLevel(d.maxZoom?d.maxZoom:32,lt,r,!0);n.push({stac_version:Ka.Version,license:Ka.License,id:p.id,providers:[{name:h.serviceProvider.name,url:h.serviceProvider.site,roles:["host"]}],title:p.title??X0(p.name),description:"No description",extent:w,links:[],summaries:{"linz:category":p.category,"linz:zoom":{min:E,max:T},"linz:priority":[1e3+e.layers.indexOf(d)]}})}return{id:e.id,type:"FeatureCollection",stac_version:Ka.Version,stac_extensions:["single-file-stac"],title:e.title??"No title",description:e.description??"No Description",features:o,collections:n,links:[]}}async function gd(t){let e=wt.getTileMatrixSet(t.params.tileMatrix);if(e==null)throw new ee(404,"Tile Matrix not found");t.timer.start("tileset:load");let r=await _e.TileSet.get(_e.TileSet.id(t.params.tileSet));if(t.timer.end("tileset:load"),r==null||r.type===vt.Vector)return be();let i=qe.key(r);if(qe.isNotModified(t,i))return ct();t.timer.start("stac:load");let n=await yS(t,r,e);if(t.timer.end("stac:load"),n==null)return be();let o=new ee(200,"ok");return o.header(re.ETag,i),o.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),o.json(n),o}var Ph=de(require("path"),1);var Cr;(function(t){t.NONE="application/octet-stream",t.JPEG="image/jpeg",t.JP2="image/jp2",t.WEBP="image/webp",t.LZW="application/lzw",t.DEFLATE="application/deflate"})(Cr||(Cr={}));var yd={1:Cr.NONE,5:Cr.LZW,6:Cr.JPEG,7:Cr.JPEG,8:Cr.DEFLATE,34712:Cr.JP2,50001:Cr.WEBP};var ae;(function(t){t[t.Artist=315]="Artist",t[t.BitsPerSample=258]="BitsPerSample",t[t.CellLength=265]="CellLength",t[t.CellWidth=264]="CellWidth",t[t.ColorMap=320]="ColorMap",t[t.Compression=259]="Compression",t[t.Copyright=33432]="Copyright",t[t.DateTime=306]="DateTime",t[t.ExtraSamples=338]="ExtraSamples",t[t.FillOrder=266]="FillOrder",t[t.FreeByteCounts=289]="FreeByteCounts",t[t.FreeOffsets=288]="FreeOffsets",t[t.GrayResponseCurve=291]="GrayResponseCurve",t[t.GrayResponseUnit=290]="GrayResponseUnit",t[t.HostComputer=316]="HostComputer",t[t.ImageDescription=270]="ImageDescription",t[t.ImageHeight=257]="ImageHeight",t[t.ImageWidth=256]="ImageWidth",t[t.Make=271]="Make",t[t.MaxSampleValue=281]="MaxSampleValue",t[t.MinSampleValue=280]="MinSampleValue",t[t.Model=272]="Model",t[t.NewSubFileType=254]="NewSubFileType",t[t.Orientation=274]="Orientation",t[t.PhotometricInterpretation=262]="PhotometricInterpretation",t[t.PlanarConfiguration=284]="PlanarConfiguration",t[t.ResolutionUnit=296]="ResolutionUnit",t[t.RowsPerStrip=278]="RowsPerStrip",t[t.SamplesPerPixel=277]="SamplesPerPixel",t[t.Software=305]="Software",t[t.StripByteCounts=279]="StripByteCounts",t[t.StripOffsets=273]="StripOffsets",t[t.SubFileType=255]="SubFileType",t[t.Threshholding=263]="Threshholding",t[t.XResolution=282]="XResolution",t[t.YResolution=283]="YResolution",t[t.BadFaxLines=326]="BadFaxLines",t[t.CleanFaxData=327]="CleanFaxData",t[t.ClipPath=343]="ClipPath",t[t.ConsecutiveBadFaxLines=328]="ConsecutiveBadFaxLines",t[t.Decode=433]="Decode",t[t.DefaultImageColor=434]="DefaultImageColor",t[t.DocumentName=269]="DocumentName",t[t.DotRange=336]="DotRange",t[t.HalftoneHints=321]="HalftoneHints",t[t.Indexed=346]="Indexed",t[t.JPEGTables=347]="JPEGTables",t[t.PageName=285]="PageName",t[t.PageNumber=297]="PageNumber",t[t.Predictor=317]="Predictor",t[t.PrimaryChromaticities=319]="PrimaryChromaticities",t[t.ReferenceBlackWhite=532]="ReferenceBlackWhite",t[t.SampleFormat=339]="SampleFormat",t[t.SMinSampleValue=340]="SMinSampleValue",t[t.SMaxSampleValue=341]="SMaxSampleValue",t[t.StripRowCounts=559]="StripRowCounts",t[t.SubIFDs=330]="SubIFDs",t[t.T4Options=292]="T4Options",t[t.T6Options=293]="T6Options",t[t.TileByteCounts=325]="TileByteCounts",t[t.TileHeight=323]="TileHeight",t[t.TileOffsets=324]="TileOffsets",t[t.TileWidth=322]="TileWidth",t[t.TransferFunction=301]="TransferFunction",t[t.WhitePoint=318]="WhitePoint",t[t.XClipPathUnits=344]="XClipPathUnits",t[t.XPosition=286]="XPosition",t[t.YCbCrCoefficients=529]="YCbCrCoefficients",t[t.YCbCrPositioning=531]="YCbCrPositioning",t[t.YCbCrSubSampling=530]="YCbCrSubSampling",t[t.YClipPathUnits=345]="YClipPathUnits",t[t.YPosition=287]="YPosition",t[t.ApertureValue=37378]="ApertureValue",t[t.ColorSpace=40961]="ColorSpace",t[t.DateTimeDigitized=36868]="DateTimeDigitized",t[t.DateTimeOriginal=36867]="DateTimeOriginal",t[t.ExifIFD=34665]="ExifIFD",t[t.ExifVersion=36864]="ExifVersion",t[t.ExposureTime=33434]="ExposureTime",t[t.FileSource=41728]="FileSource",t[t.Flash=37385]="Flash",t[t.FlashpixVersion=40960]="FlashpixVersion",t[t.FNumber=33437]="FNumber",t[t.ImageUniqueID=42016]="ImageUniqueID",t[t.LightSource=37384]="LightSource",t[t.MakerNote=37500]="MakerNote",t[t.ShutterSpeedValue=37377]="ShutterSpeedValue",t[t.UserComment=37510]="UserComment",t[t.IPTC=33723]="IPTC",t[t.ICCProfile=34675]="ICCProfile",t[t.XMP=700]="XMP",t[t.GDAL_METADATA=42112]="GDAL_METADATA",t[t.GDAL_NODATA=42113]="GDAL_NODATA",t[t.Photoshop=34377]="Photoshop",t[t.ModelPixelScale=33550]="ModelPixelScale",t[t.ModelTiePoint=33922]="ModelTiePoint",t[t.ModelTransformation=34264]="ModelTransformation",t[t.GeoKeyDirectory=34735]="GeoKeyDirectory",t[t.GeoDoubleParams=34736]="GeoDoubleParams",t[t.GeoAsciiParams=34737]="GeoAsciiParams"})(ae||(ae={}));var P1;(function(t){t[t.GTModelTypeGeoKey=1024]="GTModelTypeGeoKey",t[t.GTRasterTypeGeoKey=1025]="GTRasterTypeGeoKey",t[t.GTCitationGeoKey=1026]="GTCitationGeoKey",t[t.GeographicTypeGeoKey=2048]="GeographicTypeGeoKey",t[t.GeogCitationGeoKey=2049]="GeogCitationGeoKey",t[t.GeogGeodeticDatumGeoKey=2050]="GeogGeodeticDatumGeoKey",t[t.GeogPrimeMeridianGeoKey=2051]="GeogPrimeMeridianGeoKey",t[t.GeogLinearUnitsGeoKey=2052]="GeogLinearUnitsGeoKey",t[t.GeogLinearUnitSizeGeoKey=2053]="GeogLinearUnitSizeGeoKey",t[t.GeogAngularUnitsGeoKey=2054]="GeogAngularUnitsGeoKey",t[t.GeogAngularUnitSizeGeoKey=2055]="GeogAngularUnitSizeGeoKey",t[t.GeogEllipsoidGeoKey=2056]="GeogEllipsoidGeoKey",t[t.GeogSemiMajorAxisGeoKey=2057]="GeogSemiMajorAxisGeoKey",t[t.GeogSemiMinorAxisGeoKey=2058]="GeogSemiMinorAxisGeoKey",t[t.GeogInvFlatteningGeoKey=2059]="GeogInvFlatteningGeoKey",t[t.GeogAzimuthUnitsGeoKey=2060]="GeogAzimuthUnitsGeoKey",t[t.GeogPrimeMeridianLongGeoKey=2061]="GeogPrimeMeridianLongGeoKey",t[t.GeogTOWGS84GeoKey=2062]="GeogTOWGS84GeoKey",t[t.ProjectedCSTypeGeoKey=3072]="ProjectedCSTypeGeoKey",t[t.PCSCitationGeoKey=3073]="PCSCitationGeoKey",t[t.ProjectionGeoKey=3074]="ProjectionGeoKey",t[t.ProjCoordTransGeoKey=3075]="ProjCoordTransGeoKey",t[t.ProjLinearUnitsGeoKey=3076]="ProjLinearUnitsGeoKey",t[t.ProjLinearUnitSizeGeoKey=3077]="ProjLinearUnitSizeGeoKey",t[t.ProjStdParallel1GeoKey=3078]="ProjStdParallel1GeoKey",t[t.ProjStdParallel2GeoKey=3079]="ProjStdParallel2GeoKey",t[t.ProjNatOriginLongGeoKey=3080]="ProjNatOriginLongGeoKey",t[t.ProjNatOriginLatGeoKey=3081]="ProjNatOriginLatGeoKey",t[t.ProjFalseEastingGeoKey=3082]="ProjFalseEastingGeoKey",t[t.ProjFalseNorthingGeoKey=3083]="ProjFalseNorthingGeoKey",t[t.ProjFalseOriginLongGeoKey=3084]="ProjFalseOriginLongGeoKey",t[t.ProjFalseOriginLatGeoKey=3085]="ProjFalseOriginLatGeoKey",t[t.ProjFalseOriginEastingGeoKey=3086]="ProjFalseOriginEastingGeoKey",t[t.ProjFalseOriginNorthingGeoKey=3087]="ProjFalseOriginNorthingGeoKey",t[t.ProjCenterLongGeoKey=3088]="ProjCenterLongGeoKey",t[t.ProjCenterLatGeoKey=3089]="ProjCenterLatGeoKey",t[t.ProjCenterEastingGeoKey=3090]="ProjCenterEastingGeoKey",t[t.ProjCenterNorthingGeoKey=3091]="ProjCenterNorthingGeoKey",t[t.ProjScaleAtNatOriginGeoKey=3092]="ProjScaleAtNatOriginGeoKey",t[t.ProjScaleAtCenterGeoKey=3093]="ProjScaleAtCenterGeoKey",t[t.ProjAzimuthAngleGeoKey=3094]="ProjAzimuthAngleGeoKey",t[t.ProjStraightVertPoleLongGeoKey=3095]="ProjStraightVertPoleLongGeoKey",t[t.ProjRectifiedGridAngleGeoKey=3096]="ProjRectifiedGridAngleGeoKey",t[t.VerticalCSTypeGeoKey=4096]="VerticalCSTypeGeoKey",t[t.VerticalCitationGeoKey=4097]="VerticalCitationGeoKey",t[t.VerticalDatumGeoKey=4098]="VerticalDatumGeoKey",t[t.VerticalUnitsGeoKey=4099]="VerticalUnitsGeoKey"})(P1||(P1={}));var Ae;(function(t){t[t.BYTE=1]="BYTE",t[t.ASCII=2]="ASCII",t[t.SHORT=3]="SHORT",t[t.LONG=4]="LONG",t[t.RATIONAL=5]="RATIONAL",t[t.SBYTE=6]="SBYTE",t[t.UNDEFINED=7]="UNDEFINED",t[t.SSHORT=8]="SSHORT",t[t.SLONG=9]="SLONG",t[t.SRATIONAL=10]="SRATIONAL",t[t.FLOAT=11]="FLOAT",t[t.DOUBLE=12]="DOUBLE",t[t.LONG8=16]="LONG8",t[t.SLONG8=17]="SLONG8",t[t.IFD8=18]="IFD8"})(Ae||(Ae={}));var ve;(function(t){t[t.UInt8=1]="UInt8",t[t.UInt16=2]="UInt16",t[t.UInt32=4]="UInt32",t[t.UInt64=8]="UInt64",t[t.Double=8]="Double",t[t.Float=4]="Float"})(ve||(ve={}));var h4=2**32,bS=typeof setImmediate>"u"?setTimeout:setImmediate,Dt=()=>{throw new Error("Method not implemented.")},ci=class{constructor(){this.isLittleEndian=!0,this.delayMs=ci.DefaultDelayMs,this.maxChunkCount=10,this.chunks=ci.DefaultChunkCache(),this.blankFillCount=16,this.maxConcurrentRequests=50,this.toFetch=new Set,this.toFetchPromise=null,this.byteOffset=0,this.getFloat32=Dt,this.getFloat64=Dt,this.getInt8=Dt,this.getInt16=Dt,this.getInt32=Dt,this.setFloat32=Dt,this.setFloat64=Dt,this.setInt8=Dt,this.setInt16=Dt,this.setInt32=Dt,this.setUint8=Dt,this.setUint16=Dt,this.setUint32=Dt,this.setBigInt64=Dt,this.setBigUint64=Dt}static getByteRanges(e,r=32,i=16){if(e.size===0)return{chunks:[],blankFill:[]};let n=[...e.values()].sort((d,m)=>d-m),o=[],a=[];o.push(a);let h=[];for(let d=0;d<n.length;++d){let m=n[d],p=n[d-1];if(a.length>=r)a=[m],o.push(a);else if(d===0||m===p+1)a.push(m);else if(m<p+i){for(let M=p;M<m;M++)a.push(M+1),h.push(M+1);h.pop()}else a=[m],o.push(a)}return{chunks:o,blankFill:h}}async fetchData(){if(this.toFetch.size===0)return;let e=this.toFetch;this.toFetch=new Set,this.toFetchPromise=null;let r=ci.getByteRanges(e,this.maxChunkCount,this.blankFillCount),i=[];for(let n of r.chunks){let o=n[0],a=n[n.length-1],h=o*this.chunkSize,d=a*this.chunkSize+this.chunkSize-h,m=await this.fetchBytes(h,d);if(n.length===1){i[o]=m,this.chunks.set(o,new DataView(m));continue}let p=o*this.chunkSize;for(let M of n){let R=M*this.chunkSize-p,x=m.slice(R,R+this.chunkSize);i[M]=x,this.chunks.set(M,new DataView(x))}}}async loadBytes(e,r){if(e<0)throw new Error("Offset must be positive");let i=Math.floor(e/this.chunkSize),n=Math.ceil((e+r)/this.chunkSize)-1;for(let o=i;o<=n;o++)this.chunks.has(o)||this.toFetch.add(o);if(this.toFetch.size!==0){if(this.toFetchPromise==null&&(this.toFetchPromise=new Promise(o=>bS(o,this.delayMs)).then(()=>this.fetchData())),this.toFetch.size>this.maxConcurrentRequests)throw new Error("Too many outstanding requests");await this.toFetchPromise}}getChunkId(e){return Math.floor(e/this.chunkSize)}getUint(e,r){switch(r){case ve.UInt8:return this.getUint8(e);case ve.UInt16:return this.getUint16(e);case ve.UInt32:return this.getUint32(e);case ve.UInt64:return this.getUint64(e)}}bytes(e,r){let i=this.isOneChunk(e,r);if(i){let m=this.getView(i),p=e-i*this.chunkSize;return new Uint8Array(m.buffer.slice(p,p+r))}let n=new Uint8Array(r),o=e+r,a=Math.floor(e/this.chunkSize),h=Math.ceil((e+r)/this.chunkSize)-1,d=0;for(let m=a;m<=h;m++){let p=e+d,M=m*this.chunkSize,R=this.getView(m),x=Math.min(o,M+this.chunkSize),w=R.buffer.slice(p-M,x-M);n.set(new Uint8Array(w),d),d+=w.byteLength}return n}getView(e){let r=this.chunks.get(e);if(r==null)throw new Error(`Chunk:${e} is not ready`);return r}isOneChunk(e,r){let i=e+r-1,n=Math.floor(e/this.chunkSize);return Math.floor(i/this.chunkSize)-n<1?n:null}hasBytes(e,r=1){let i=Math.floor(e/this.chunkSize),n=Math.ceil((e+r)/this.chunkSize)-1;for(let o=i;o<=n;o++)if(!this.chunks.has(o))return!1;return!0}toRange(e,r){if(r==null)return`bytes=${e}`;if(e<0)throw new Error("Cannot read from remote source with negative offset and length");return`bytes=${e}-${e+r}`}parseContentRange(e){let[r,i]=e.split(" ");if(r!=="bytes")throw new Error("Failed to parse content-range: "+e);if(i==null)throw new Error("Failed to parse content-range: "+e);let[,n]=i.split("/"),o=Number(n);if(isNaN(o))throw new Error("Failed to parse content-range: "+e);return o}get buffer(){throw new Error("Method not implemented.")}get byteLength(){if(this._byteLength)return this._byteLength;throw Error(".size() has not been fetched.")}getUint8(e){let r=Math.floor(e/this.chunkSize),i=this.chunks.get(r);if(i==null)throw new Error(`Chunk:${r} is not ready`);return i.getUint8(e-r*this.chunkSize)}getUint16(e){let r=this.isOneChunk(e,ve.UInt16);if(r!=null)return this.getView(r).getUint16(e-r*this.chunkSize,this.isLittleEndian);let i=this.getUint8(e),n=this.getUint8(e+ve.UInt8);return this.isLittleEndian?i+(n<<8):(i<<8)+n}getUint32(e){let r=this.isOneChunk(e,ve.UInt32);if(r!=null)return this.getView(r).getUint32(e-r*this.chunkSize,this.isLittleEndian);let i=this.getUint16(e),n=this.getUint16(e+ve.UInt16);return this.isLittleEndian?i+n*65536:i*65536+n}getUint64(e){let r=this.isOneChunk(e,ve.UInt64);if(r!=null){let o=this.getView(r);return Number(o.getBigUint64(e-r*this.chunkSize,this.isLittleEndian))}let i=this.getUint32(e),n=this.getUint32(e+ve.UInt32);return this.isLittleEndian?i+n*h4:i*h4+n}getBigUint64(e){let r=this.isOneChunk(e,ve.UInt64);if(r!=null)return this.getView(r).getBigUint64(e-r*this.chunkSize,this.isLittleEndian);let i=BigInt(this.getUint32(e)),n=BigInt(this.getUint32(e+ve.UInt32));return this.isLittleEndian?i+(n<<BigInt(32)):(i<<BigInt(32))+n}getBigInt64(){throw new Error("Not implemented.")}};ci.DefaultChunkCache=()=>new Map;ci.DefaultDelayMs=1;var c4=de(vd(),1);function f4(t){switch(t){case Ae.BYTE:case Ae.ASCII:case Ae.SBYTE:case Ae.UNDEFINED:return 1;case Ae.SHORT:case Ae.SSHORT:return 2;case Ae.LONG:case Ae.SLONG:case Ae.FLOAT:return 4;case Ae.RATIONAL:case Ae.SRATIONAL:case Ae.DOUBLE:case Ae.LONG8:case Ae.SLONG8:case Ae.IFD8:return 8;default:throw new Error(`Invalid fieldType ${t}`)}}var Es={char:(t,e)=>String.fromCharCode(t.getUint8(e)),uint8:(t,e)=>t.getUint8(e),uint16:(t,e)=>t.getUint16(e),uint32:(t,e)=>t.getUint32(e),uint64:(t,e)=>t.getUint64(e),double:(t,e)=>c4.read(t.bytes(e,ve.Double),0,t.isLittleEndian,52,8),rational:(t,e)=>[t.getUint32(e),t.getUint32(e+4)]};function hh(t){switch(t){case Ae.ASCII:return Es.char;case Ae.BYTE:case Ae.UNDEFINED:case Ae.SBYTE:return Es.uint8;case Ae.SHORT:case Ae.SSHORT:return Es.uint16;case Ae.LONG:case Ae.SLONG:return Es.uint32;case Ae.RATIONAL:case Ae.SRATIONAL:return Es.rational;case Ae.DOUBLE:return Es.double;case Ae.LONG8:return Es.uint64;default:throw new Error(`Unknown read type "${t}" "${Ae[t]}"`)}}var Cn=class{constructor(e,r,i){this.tiff=r,this.byteOffset=i,this.id=e,this.name=ae[this.id],this.dataType=this.tiff.source.getUint16(i+2),this.dataCount=this.tiff.source.getUint(i+4,this.tiff.ifdConfig.pointer),this.dataTypeSize=f4(this.dataType),this.dataLength=this.dataTypeSize*this.dataCount}get hasBytes(){return this.tiff.source.hasBytes(this.valuePointer,this.dataLength)}get isReady(){return!0}get dataTypeName(){return Ae[this.dataType]}get valuePointer(){let e=this.size-this.tiff.ifdConfig.pointer;return this.isValueInline?this.byteOffset+e:this.tiff.source.getUint(this.byteOffset+e,this.tiff.ifdConfig.pointer)}get size(){return this.tiff.ifdConfig.ifd}get isValueInline(){return this.dataLength<=this.tiff.ifdConfig.pointer}readValue(){let e=this.valuePointer,r=this.dataTypeSize,i=hh(this.dataType),n=this.dataCount,o=n*r;if(n===1)return i(this.tiff.source,e);let a=[];for(let h=0;h<o;h+=r)a.push(i(this.tiff.source,e+h));return this.dataType===Ae.ASCII?a.join("").trim():a}toJSON(){return{id:this.id,name:this.name,offset:this.byteOffset,isReady:this.isReady,type:this.dataTypeName,value:this.value}}};var Rs=class extends Cn{constructor(){super(...arguments),this.value=null}get isReady(){return this.value!=null}async fetch(){return this.tiff.source.hasBytes(this.valuePointer,this.dataLength)===!1&&await this.tiff.source.loadBytes(this.valuePointer,this.dataLength),this.value=this.readValue(),this.value}};var O1=class extends Cn{constructor(e,r,i){super(e,r,i),this.loadedValues=null}get value(){return this.loadedValues!=null?this.loadedValues:this.hasBytes?(this.readValue(),this.loadedValues):null}async load(){await this.tiff.source.loadBytes(this.valuePointer,this.dataLength),this.readValue()}readValue(){let e=super.readValue();return typeof e=="number"?this.loadedValues=[e]:this.loadedValues=e,this.loadedValues}async getValueAt(e){if(this.loadedValues)return this.loadedValues[e];let r=this.dataTypeSize,i=this.valuePointer+r*e,n=hh(this.dataType);return this.tiff.source.hasBytes(i,r)||await this.tiff.source.loadBytes(i,r),n(this.tiff.source,i)}};var k1=class extends Cn{constructor(){super(...arguments),this._isRead=!1,this._value=null}get value(){return this._isRead===!1&&(this._value=this.readValue(),this._isRead=!0),this._value}};var ch={create(t,e){let r=t.source.getUint16(e);if(r===ae.TileOffsets||r===ae.TileByteCounts||r===ae.StripByteCounts||r===ae.StripOffsets)return new O1(r,t,e);let i=new k1(r,t,e);return i.hasBytes?i:new Rs(r,t,e)},isStatic(t){return t instanceof k1},isLazy(t){return t instanceof Rs},isOffsetArray(t){return t instanceof O1}};var vS=32767,fh=class{constructor(e,r,i){this.tagsGeoLoaded=!1,this.tagsGeo=new Map,this.tif=e,this.id=r,this.tags=i}async init(e=!1){let r=[this.fetch(ae.Compression),this.fetch(ae.ImageHeight),this.fetch(ae.ImageWidth),this.fetch(ae.ModelPixelScale),this.fetch(ae.ModelTiePoint),this.fetch(ae.ModelTransformation),this.fetch(ae.TileHeight),this.fetch(ae.TileWidth)];e&&(r.push(this.fetch(ae.GeoKeyDirectory)),r.push(this.fetch(ae.GeoAsciiParams)),r.push(this.fetch(ae.GeoDoubleParams))),await Promise.all(r),e&&await this.loadGeoTiffTags()}value(e){let r=this.tags.get(e);return r==null?null:r.value}async loadGeoTiffTags(){if(this.tagsGeoLoaded)return;let e=this.tags.get(ae.GeoKeyDirectory);if(e==null){this.tagsGeoLoaded=!0;return}if(!e.isReady&&e instanceof Rs&&await Promise.all([this.fetch(ae.GeoKeyDirectory),this.fetch(ae.GeoAsciiParams),this.fetch(ae.GeoDoubleParams)]),this.tagsGeoLoaded=!0,e.value==null)return;let r=e.value;if(!Array.isArray(r))throw new Error("Invalid geo tags found");for(let i=4;i<=r[3]*4;i+=4){let n=r[i],o=r[i+1],a=r[i+3];if(o===0){this.tagsGeo.set(n,a);continue}let h=this.tags.get(o);if(h==null||h.value==null)continue;let d=r[i+2];Array.isArray(h.value)?this.tagsGeo.set(n,h.value[a+d-1]):typeof h.value=="string"&&this.tagsGeo.set(n,h.value.substr(a,a+d-1).trim())}}valueGeo(e){if(this.tagsGeoLoaded===!1)throw new Error("loadGeoTiffTags() has not been called");return this.tagsGeo.get(e)}async fetch(e){let r=this.tags.get(e);return r==null?null:ch.isLazy(r)?r.fetch():r.value}get origin(){let e=this.value(ae.ModelTiePoint);if(e!=null&&e.length===6)return[e[3],e[4],e[5]];let r=this.value(ae.ModelTransformation);if(r!=null)return[r[3],r[7],r[11]];if(this.value(ae.NewSubFileType)===1&&this.id!==0)return this.tif.images[0].origin;throw new Error("Image does not have a geo transformation.")}get isGeoLocated(){return this.value(ae.ModelPixelScale)!=null||this.value(ae.ModelTransformation)!=null?!0:this.value(ae.NewSubFileType)===1&&this.id!==0?this.tif.images[0].isGeoLocated:!1}get resolution(){let e=this.value(ae.ModelPixelScale);if(e!=null)return[e[0],-e[1],e[2]];let r=this.value(ae.ModelTransformation);if(r!=null)return[r[0],r[5],r[10]];if(this.value(ae.NewSubFileType)===1&&this.id!==0){let i=this.tif.images[0],[n,o,a]=i.resolution,h=i.size,d=this.size;return[n*h.width/d.width,o*h.height/d.height,a]}throw new Error("Image does not have a geo transformation.")}get bbox(){let e=this.size,r=this.origin,i=this.resolution;if(r==null||e==null||i==null)throw new Error("Unable to calculate bounding box");let n=r[0],o=r[1],a=n+i[0]*e.width,h=o+i[1]*e.height;return[Math.min(n,a),Math.min(o,h),Math.max(n,a),Math.max(o,h)]}get compression(){let e=this.value(ae.Compression);return e==null||typeof e!="number"?null:yd[e]}get epsg(){let e=this.valueGeo(P1.ProjectedCSTypeGeoKey);return e===vS?null:e}get size(){return{width:this.value(ae.ImageWidth),height:this.value(ae.ImageHeight)}}get tagList(){return[...this.tags.keys()].map(e=>ae[e])}isTiled(){return this.value(ae.TileWidth)!==null}get tileSize(){return{width:this.value(ae.TileWidth),height:this.value(ae.TileHeight)}}get tileCount(){let e=this.size,r=this.tileSize,i=Math.ceil(e.width/r.width),n=Math.ceil(e.height/r.height);return{x:i,y:n}}get tileOffset(){let e=this.tags.get(ae.TileOffsets);if(e==null)throw new Error("No tile offsets found");return e}get stripCount(){let e=this.tags.get(ae.StripByteCounts);return e==null?0:e.dataCount}async getTileOffset(e){let r=this.tileOffset;if(e<0||e>r.dataCount)throw new Error(`Tile offset: ${e} out of range: 0 -> ${r.dataCount}`);return r.getValueAt(e)}getTileBounds(e,r){let{size:i,tileSize:n}=this,o=r*n.height,a=e*n.width,h=a+n.width>=i.width?i.width-a:n.width,d=o+n.height>=i.height?i.height-o:n.height;return{x:a,y:o,width:h,height:d}}async getStrip(e){if(this.isTiled())throw new Error("Cannot read stripes, tiff is tiled");let r=this.tags.get(ae.StripByteCounts),i=this.tags.get(ae.StripOffsets);if(e>=r.dataCount)throw new Error("Cannot read strip, index out of bounds");let[n,o]=await Promise.all([i.getValueAt(e),r.getValueAt(e)]);return this.getBytes(n,o)}getJpegHeader(e){let r=this.value(ae.JPEGTables);if(r==null)throw new Error("Unable to find Jpeg header");let i=r.slice(0,r.length-2),n=new Uint8Array(e.byteLength+i.length-2);return n.set(i,0),n.set(e.slice(2),i.length),n}async getBytes(e,r){let i=this.compression;if(i==null)throw new Error("Unsupported compression: "+this.value(ae.Compression));if(r===0)return null;await this.tif.source.loadBytes(e,r);let n=this.tif.source.bytes(e,r);return this.compression===Cr.JPEG?{mimeType:i,bytes:this.getJpegHeader(n)}:{mimeType:i,bytes:n}}async getTile(e,r){let i=this.compression,n=this.size,o=this.tileSize;if(o==null)throw new Error("Tiff is not tiled");if(i==null)throw new Error("Unsupported compression: "+this.value(ae.Compression));let a=Math.ceil(n.height/o.height),h=Math.ceil(n.width/o.width);if(e>=h||r>=a)throw new Error(`Tile index is outside of range x:${e} >= ${h} or y:${r} >= ${a}`);let d=r*h+e,m=h*a;if(d>=m)throw new Error(`Tile index is outside of tile range: ${d} >= ${m}`);let{offset:p,imageSize:M}=await this.getTileSize(d);return this.getBytes(p,M)}async getTileSize(e){if(this.tif.options.tileLeaderByteSize){let o=await this.getTileOffset(e);if(o===0)return{offset:0,imageSize:0};let a=this.tif.options.tileLeaderByteSize;return await this.tif.source.loadBytes(o-a,a),{offset:o,imageSize:this.tif.source.getUint(o-a,a)}}let r=this.tags.get(ae.TileByteCounts);if(r==null)throw new Error("No tile byte counts found");let[i,n]=await Promise.all([this.getTileOffset(e),r.getValueAt(e)]);return{offset:i,imageSize:n}}};var L1;(function(t){t[t.Big=19789]="Big",t[t.Little=18761]="Little"})(L1||(L1={}));var Ar;(function(t){t[t.BigTiff=43]="BigTiff",t[t.Tiff=42]="Tiff"})(Ar||(Ar={}));var wd="__reverse";function d4(t,e){if(t[wd]==null){let r={};for(let i of Object.keys(t)){let n=t[i];r[n]=i}Object.defineProperty(t,wd,{enumerable:!1,value:r,writable:!1})}return t[wd][e]}var An;(function(t){t.GDAL_STRUCTURAL_METADATA_SIZE="GDAL_STRUCTURAL_METADATA_SIZE",t.LAYOUT="LAYOUT",t.BLOCK_ORDER="BLOCK_ORDER",t.BLOCK_LEADER="BLOCK_LEADER",t.BLOCK_TRAILER="BLOCK_TRAILER",t.KNOWN_INCOMPATIBLE_EDITION="KNOWN_INCOMPATIBLE_EDITION",t.MASK_INTERLEAVED_WITH_IMAGERY="MASK_INTERLEAVED_WITH_IMAGERY"})(An||(An={}));var _d;(function(t){t.RowMajor="ROW_MAJOR"})(_d||(_d={}));var xd;(function(t){t.uint32="SIZE_AS_UINT4"})(xd||(xd={}));var wS={uint32:ve.UInt32},dh=class{constructor(){this.options=new Map}get isCogOptimized(){return this.isBroken?!1:this.options.get(An.LAYOUT)==="IFDS_BEFORE_DATA"}get isBroken(){return this.options.get(An.KNOWN_INCOMPATIBLE_EDITION)==="YES"}set(e,r){this.options.set(e,r)}process(e,r,i){let n=[];for(let a=r;a<r+i;a++){let h=e.getUint8(a);h!==0&&n.push(String.fromCharCode(h))}let o=n.join("").trim().split(`
184
184
  `).map(a=>a.split("="));for(let[a,h]of o)this.options.set(An[a],h)}_getReverse(e,r){let i=this.options.get(r);return i==null?null:d4(e,i)}get tileOrder(){return this._getReverse(_d,An.BLOCK_ORDER)}get tileLeader(){return this._getReverse(xd,An.BLOCK_LEADER)}get tileLeaderByteSize(){return this.tileLeader==null?null:wS[this.tileLeader]}get isMaskInterleaved(){return this.options.get(An.MASK_INTERLEAVED_WITH_IMAGERY)==="YES"}};var Sd={version:Ar.Tiff,pointer:ve.UInt32,offset:ve.UInt16,ifd:ve.UInt16+ve.UInt16+2*ve.UInt32},Md={version:Ar.BigTiff,pointer:ve.UInt64,offset:ve.UInt64,ifd:ve.UInt16+ve.UInt16+2*ve.UInt64},xk={[Ar.BigTiff]:Md,[Ar.Tiff]:Sd};var Ed=de(vd(),1),mh=class{constructor(e,r=0){this.tiff=e,this.byteOffset=r,this.relativeOffset=0}get currentOffset(){return this.byteOffset+this.relativeOffset}seekTo(e){return this.byteOffset=e,this.relativeOffset=0,this}seek(e){let r=this.currentOffset;return this.relativeOffset+=e,r}bytes(e){return this.tiff.source.bytes(this.seek(e),e)}uint(e){return this.tiff.source.getUint(this.seek(e),e)}uint8(){return this.tiff.source.getUint8(this.seek(ve.UInt8))}uint16(){return this.tiff.source.getUint16(this.seek(ve.UInt16))}uint32(){return this.tiff.source.getUint32(this.seek(ve.UInt32))}uint64(){return this.tiff.source.getUint64(this.seek(ve.UInt64))}pointer(){let e=this.tiff.ifdConfig.pointer;return this.tiff.source.getUint(this.seek(e),e)}offset(){let e=this.tiff.ifdConfig.offset;return this.tiff.source.getUint(this.seek(e),e)}float(){return Ed.read(this.bytes(ve.Float),0,this.tiff.source.isLittleEndian,23,4)}double(){return Ed.read(this.bytes(ve.Double),0,this.tiff.source.isLittleEndian,52,8)}};function m4(t,e=4,r=!0){let i=t.toString(16).padStart(e,"0");return r?"0x"+i:i}var la=class{constructor(e){this.version=Ar.Tiff,this.images=[],this.options=new dh,this.ifdConfig=Sd,this.isInitialized=!1,this.source=e,this.cursor=new mh(this)}static create(e){return new la(e).init()}init(e=!1){return this._initPromise?this._initPromise:(this._initPromise=this.doInit(e),this._initPromise)}async doInit(e=!1){return this.isInitialized?this:(await this.source.loadBytes(0,this.source.chunkSize),await this.fetchIfd(),await Promise.all(this.images.map(r=>r.init(e))),this.isInitialized=!0,this)}async fetchIfd(){let e=this.cursor.seekTo(0),r=e.uint16();if(this.source.isLittleEndian=r===L1.Little,!this.source.isLittleEndian)throw new Error("Only little endian is supported");this.version=e.uint16();let i;if(this.version===Ar.BigTiff){if(this.ifdConfig=Md,e.uint16()!==8)throw new Error("Only 8byte pointers are supported");if(e.uint16()!==0)throw new Error("Invalid big tiff header");i=e.pointer()}else if(this.version===Ar.Tiff)i=e.pointer();else throw new Error(`Only tiff supported version:${this.version}`);let n=i-this.cursor.currentOffset;return n>0&&n<16*1024,this.processIfd(i)}getImage(e){return this.images[e]}getImageByResolution(e){let r=this.images[0],i=r.size,[n]=r.resolution,o=n*i.width;for(let a=this.images.length-1;a>0;a--){let h=this.images[a],d=h.size;if(o/d.width-e<=.01)return h}return r}async getTile(e,r,i){let n=this.getImage(i);if(n==null)throw new Error(`Missing z: ${i}`);if(!n.isTiled())throw new Error("Tif is not tiled");return n.getTile(e,r)}async processIfd(e){this.source.hasBytes(e,4096)||await this.source.loadBytes(e,4096);let{image:r,nextOffset:i}=await this.readIfd(e);this.images.push(r),i&&await this.processIfd(i)}async readIfd(e){this.source.hasBytes(e,1024)||await this.source.loadBytes(e,this.source.chunkSize);let i=this.cursor.seekTo(e).offset(),n=e+this.ifdConfig.offset,o=new Map,a=n;for(let m=0;m<i;m++){let p=ch.create(this,a);if(a+=p.size,p.name==null)throw new Error("Unknown IFD Tag: "+m4(p.id));o.set(p.id,p)}let h=new fh(this,this.images.length,o);return{nextOffset:this.source.getUint(a,this.ifdConfig.pointer),image:h}}async close(){var e,r;await((r=(e=this.source)===null||e===void 0?void 0:e.close)===null||r===void 0?void 0:r.call(e))}};var Le=class{constructor(e){this.name=e}raw(e,r=0){return this.parse(e,{offset:r,startOffset:0})}read(e,r=0){let i={offset:r,startOffset:r};return{value:this.parse(e,i),offset:i.offset}}refine(e){return new Rd(this,e)}},Rd=class extends Le{constructor(e,r){super("Function:"+e.name),this.input=e,this.cb=r}get size(){return this.input.size}parse(e,r){let i=this.input.parse(e,r);return this.cb(i,e,r)}};var ph=class extends Le{constructor(e,r,i){super(`Array:${e}:${r.name}x${i}`),this.count=i,this.type=r}get size(){return this.count*this.type.size}parse(e,r){let i=[];for(let n=0;n<this.count;n++)i.push(this.type.parse(e,r));return i}},gh=class extends Le{constructor(e,r,i,n){super("Array:Offset:"+e),this.isLookupRequired=!0,this.isMaxLength=n,this.lengthName=i,this.type=r}get size(){throw new Error("Unable to calculate size of dynamic object: "+this.name)}parse(e,r,i){let n=[],o=i?.[this.lengthName];if(o==null||typeof o!="number")throw new Error(`${this.name}: Missing variable a "${this.lengthName}"`);this.isMaxLength&&(o-=r.offset-r.startOffset);for(let a=0;a<o;a++)n.push(this.type.parse(e,r));return n}};var p4=[];for(let t=0;t<64;t++)p4[t]=Math.pow(2,t);var N1=class{constructor(e,r=0,i=e.length,n=!0){if(this.buffer=e,this.offset=r*8,this.maxOffset=i*8,this.isLittleEndian=n,!this.isLittleEndian)throw new Error("BigEndian is not supported")}get remainingBits(){return this.maxOffset-this.offset}getBitValue(e,r,i){return(e&((1<<r+i)-1&~((1<<r)-1)))>>r}skip(e){this.offset+=e}bit(){if(this.remainingBits<0)throw new Error("BitStream: Overflow "+this.remainingBits);let e=Math.floor(this.offset/8),r=this.offset%8,i=this.buffer[e];return this.offset++,this.getBitValue(i,r,1)}bool(){return this.bit()===1}bits(e){let r=e,i=0;for(;e>0;)this.bit()===1&&(i+=p4[r-e]),e--;return i}string(e){let r=[];e==null&&(e=Math.floor(this.remainingBits/8));for(let i=0;i<e;i++){let n=this.bits(8);if(n===0)break;r.push(String.fromCharCode(n))}return r.join("")}};var yh=class extends Le{constructor(e,r){super("Bits:"+e);let i=0;this.fields=Object.keys(r).map(n=>{let o=r[n];return i+=o,{key:n,bits:o}}),this.size=Math.ceil(i/8)}parse(e,r){let i=r.offset,n={},o=new N1(e,i,i+this.size);for(let{key:a,bits:h}of this.fields)n[a]=o.bits(h);return r.offset+=this.size,n}},bh=class extends Le{constructor(e,r,i){super("BitsFlags:"+e),this.type=r,this.fields=Object.entries(i)}get size(){return this.type.size}parse(e,r){let i=this.type.parse(e,r),n={};for(let[o,a]of this.fields){let h=(i&a)===a;h&&(n[o]=h)}return n}};var vh=class extends Le{constructor(e){super("Bytes:"+e),this.size=e}parse(e,r){let i=e.slice(r.offset,r.offset+this.size);return r.offset+=this.size,i}};var Cd=class extends Le{constructor(){super(...arguments),this.size=1}parse(e,r){let i=r.offset;return r.offset+=this.size,e[i]}},Ad=class extends Le{constructor(){super(...arguments),this.size=2}parse(e,r){let i=r.offset,n=e[i++],o=e[i++]<<8;return r.offset+=2,n|o}},Td=class extends Le{constructor(){super(...arguments),this.size=4}parse(e,r){let i=r.offset,n=e[i++],o=e[i++]<<8,a=e[i++]<<16,h=e[i++]*16777216;return r.offset=i,(n|o|a)+h}},_S=2**32,Id=class extends Le{constructor(){super(...arguments),this.size=8}parse(e,r){let i=ua.parse(e,r),n=ua.parse(e,r);return i+n*_S}},Pd=class extends Le{constructor(){super(...arguments),this.size=8}parse(e,r){let i=BigInt(ua.parse(e,r)),n=BigInt(ua.parse(e,r));return i+(n<<BigInt(32))}},g4=new Cd("UInt8"),y4=new Ad("LUInt16"),ua=new Td("LUInt32"),b4=new Id("LUInt64"),v4=new Pd("BigLUInt64");var wh=class extends Le{constructor(e,r,i){super("Lookup:"+e),this.lookup=i,this.type=r}get size(){return this.type.size}parse(e,r){let i=this.type.parse(e,r),n=this.lookup(i);if(n==null)throw new Error(`${this.name}: Failed to lookup ${i}`);return{id:i,name:n}}},_h=class extends Le{constructor(e,r,i){super("Enum:"+e),this.enumeration=i,this.type=r}get size(){return this.type.size}parse(e,r){let i=this.type.parse(e,r),n=this.enumeration[i];if(n==null)throw new Error(`${this.name}: Failed to lookup ${i}`);return{id:i,name:n}}};var ha=class extends Le{constructor(e,r){super(e),this._size=-1,this.fields=[];for(let[i,n]of Object.entries(r))this.fields.push({key:i,parser:n})}get size(){if(this._size>-1)return this._size;let e=0;for(let r of this.fields)e+=r.parser.size;return this._size=e,this._size}parse(e,r){let i={};for(let n of this.fields)i[n.key]=n.parser.parse(e,r,i);return i}},xh=class extends Le{constructor(e,r){super(e),this.fields=[],this._size=-1;let i=Object.entries(r),n=!1;for(let[o,a]of i)a.isLookupRequired&&(n=!0),this.fields.push({key:o,parser:a});i.length!==0&&(n?this.generateObjectAssign():this.generateSingleObject())}generateSingleObject(){let e=[],r='"use strict"; return {';for(let n=0;n<this.fields.length;n++)e.push(this.fields[n].parser),r+=` ${JSON.stringify(this.fields[n].key)}: _bp[${n}].parse(buf, ctx),`;r+=" };";let i=new Function("_bp","buf","ctx",r);this.parse=i.bind(null,e)}generateObjectAssign(){let e=[],r=`"use strict"; const ret = {};
185
185
  `;for(let n=0;n<this.fields.length;n++)e.push(this.fields[n].parser),r+=`ret[${JSON.stringify(this.fields[n].key)}] = _bp[${n}].parse(buf, ctx, ret)
186
186
  `;r+="return ret";let i=new Function("_bp","buf","ctx",r);this.parse=i.bind(null,e)}get size(){if(this._size>-1)return this._size;let e=0;for(let r of this.fields)e+=r.parser.size;return this._size=e,this._size}parse(e,r){return{}}};function ca(t,e=2){return"0x"+t.toString(16).padStart(e,"0")}var Sh=class extends Le{constructor(e,r){super("Offset:"+e.name+":"+r.name),this.type=r,this.offset=e}get size(){return this.type.size}parse(e,r){let i=this.offset.parse(e,r);if(i>e.length||i<0)throw new Error(`[${this.name}]: BufferOverflow attempted read at ${ca(i)}`);return this.type.parse(e,{offset:i,startOffset:i})}};var Mh=class extends Le{constructor(e){super("Skip:"+e),this.size=e}parse(e,r){r.offset+=this.size}};var Eh=class extends Le{constructor(){super("String")}get size(){throw new Error("Unable to calculate size from dynamic object")}parse(e,r){let i=r.offset,n=[],o=0;for(;o+i<e.length;){let a=e[i+o];if(a===0)break;n.push(String.fromCharCode(a)),o++}return r.offset+=o+1,n.join("")}},Rh=class extends Le{constructor(e){super("String:"+e),this.size=e}parse(e,r){let i=r.offset;if(this.size+i>e.length)throw new Error(`BufferOverflow: ${this.name} offset: ${ca(r.offset)}`);let n=[],o=0;for(;o<this.size;){let a=e[i+o];if(a===0)break;n.push(String.fromCharCode(a)),o++}return r.offset+=this.size,n.join("")}};function xS(t,e,r,i){return typeof r=="number"?new ph(t,e,r):new gh(t,e,r,i??!1)}var lr={u8:g4,lu16:y4,lu32:ua,lu64:b4,blu64:v4,empty:new ha("Empty",{}),offset(t,e){return new Sh(t,e)},string(t){return t==null?new Eh:new Rh(t)},bits(t,e){return new yh(t,e)},flags(t,e,r){return new bh(t,e,r)},object(t,e){return new xh(t,e)},static(t,e){return new ha(t,e)},lookup(t,e,r){return new wh(t,e,r)},enum(t,e,r){return new _h(t,e,r)},bytes(t){return new vh(t)},skip(t){return new Mh(t)},array:xS};var w4;(function(t){t[t.File="0".charCodeAt(0)]="File",t[t.HardLink="1".charCodeAt(0)]="HardLink",t[t.SymLink="2".charCodeAt(0)]="SymLink",t[t.CharDeviceNode="3".charCodeAt(0)]="CharDeviceNode",t[t.BlockDeviceNode="4".charCodeAt(0)]="BlockDeviceNode",t[t.Directory="5".charCodeAt(0)]="Directory",t[t.FifoNode="6".charCodeAt(0)]="FifoNode",t[t.Reserved="7".charCodeAt(0)]="Reserved",t[t.LongName="L".charCodeAt(0)]="LongName",t[t.LongLink="K".charCodeAt(0)]="LongLink"})(w4||(w4={}));var SS=lr.object("TarHeader",{path:lr.string(100),skip1:lr.skip(24),size:lr.bytes(12).refine(t=>parseInt(t.toString(),8)),skip2:lr.skip(20),type:lr.u8,linkName:lr.string(100)});var _4={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},MS={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n};function Od(t,{size:e=32}={}){if(!_4[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");let r=MS[e],i=_4[e],n=!1;for(let o=0;o<t.length;o++){let a=t.charCodeAt(o);a>127&&!n&&(t=unescape(encodeURIComponent(t)),a=t.charCodeAt(o),n=!0),r^=BigInt(a),r=BigInt.asUintN(e,r*i)}return r}var Ch="COT";var ES=BigInt(0),RS=BigInt(32),CS=BigInt(2**32-1),x4=lr.object("CotarMetadata",{magic:lr.string(Ch.length),version:lr.u8,count:lr.lu32}),qr=class{constructor(e,r,i=0){this.isHeader=!0,this.source=e,this.sourceOffset=i,this.metadata=r}static hash(e){return Od(e,{size:64})}static async loadMetadata(e,r,i){if(i){await e.loadBytes(r,e.chunkSize);let o=e.bytes(r,8);return x4.read(o).value}let n=await e.fetchBytes(-8);return x4.read(new Uint8Array(n)).value}static async getMetadata(e,r,i){let n=await this.loadMetadata(e,r,i);if(n.magic!==Ch)throw new Error(`Invalid source: ${e.uri} invalid magic found: ${n.magic}`);if(n.version===1||n.version===2)return n;throw new Error(`Invalid source: ${e.uri} invalid version found: ${n.version}`)}static async create(e,r=0,i=!0){let n=await this.getMetadata(e,r,i);return new qr(e,n,r)}async find(e){if(this.metadata.version===1)return this._findV1(e);if(this.metadata.version===2)return this._findV2(e);throw new Error("Invalid metadata version")}async _findV2(e){let r=qr.hash(e),i=this.metadata.count,n=Number(r%BigInt(i)),o=Number(r>>RS),a=Number(r&CS),h=null,d=null,m=n;for(;;){let p=this.sourceOffset+m*16+8;if(await this.source.loadBytes(p,16),d=this.source.getUint32(p),h=this.source.getUint32(p+4),h===o&&d===a){let M=this.source.getUint32(p+8)*512,R=this.source.getUint32(p+12);return{offset:M,size:R}}if(h===0&&d===0||(m++,m>=i&&(m=0),m===n))return null}}async _findV1(e){let r=qr.hash(e),i=this.metadata.count,n=Number(r%BigInt(i)),o=null,a=n;for(;;){let h=this.sourceOffset+a*24+8;if(await this.source.loadBytes(h,24),o=this.source.getBigUint64(h),o===r){let d=this.source.getUint64(h+8),m=this.source.getUint64(h+16);return{offset:d,size:m}}if(o===ES||(a++,a>=i&&(a=0),a===n))return null}}};var WL=BigInt(0);var Cs=class{constructor(e,r){this.source=e,this.index=r}static async fromTar(e){let r=await qr.getMetadata(e,0,!1),i=await e.size,n=r.version===1?24:16,o=i-(r.count*n+16),a=new qr(e,r,o);return new Cs(e,a)}async get(e){let r=await this.index.find(e);return r==null?null:(await this.source.loadBytes(r.offset,r.size),this.source.bytes(r.offset,r.size))}};var kd=class{constructor(){this.requests=[]}reset(){this.requests=[]}trace(e){let r=e.fetchBytes;e.fetchBytes=async(i,n)=>{let o={source:e.uri,offset:i,length:n},a=Qn(`${o.source}:${o.offset}:${o.length}`);o.id=a,this.requests.push(o);let h=Date.now(),d=await r.apply(e,[i,n]);return o.duration=Date.now()-h,d}}},Tn=new kd;var Th=class{constructor(e){this.cacheA=new Map;this.cacheB=new Map;this.hits=0;this.misses=0;this.resets=0;this._lastCheckedAt=-1;this.maxSize=e}get(e){let r=this.cacheA.get(e);if(r)return this.hits++,r;let i=this.cacheB.get(e);return i==null?(this.misses++,null):(this.hits++,this.cacheA.set(e,i),this.cacheB.delete(e),i)}clear(){this.cacheA.clear(),this.cacheB.clear()}set(e,r){this.cacheA.set(e,r),this.check()}check(){this._lastCheckedAt=Date.now(),!(this.maxSize<=0)&&(this.currentSize<=this.maxSize||(this.resets++,this.cacheB=this.cacheA,this.cacheA=new Map))}get currentSize(){let e=0;for(let r of this.cacheA.values())e+=r.size;return e}};var Ih=class{constructor(e){this.ob=e,this.ob._value==null&&this.ob.value.then(r=>this.ob._value=r)}get size(){let e=this.ob._value;return e==null?0:e.source.chunkSize*e.source.chunks.size}},Ld=class{constructor(e){this.cache=new Th(e)}getCog(e){let r=this.cache.get(e)?.ob;if(r!=null){if(r.type==="cog")return r.value;throw new Error(`Existing object of type: ${r.type} made for location: ${e}`)}let i=Er.source(e);Tn.trace(i);let n=la.create(i);return this.cache.set(e,new Ih({type:"cog",value:n})),n}getCotar(e){let r=this.cache.get(e)?.ob;if(r!=null){if(r.type==="cotar")return r.value;throw new Error(`Existing object of type: ${r.type} made for location: ${e}`)}let i=Er.source(e);Tn.trace(i);let n=Cs.fromTar(i);return this.cache.set(e,new Ih({type:"cotar",value:n})),n}},ur=new Ld(256*1024*1024);async function z1(t,e,r,i){let n=await ur.getCotar(e);if(n==null)return be();let o=await n.get(r);if(o==null)return be();let a=Buffer.from(o),h=qe.key(a);if(qe.isNotModified(t,h))return ct();let d=ee.ok().buffer(a,i);return d.header(re.ETag,h),d.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Ui(a)&&d.header(re.ContentEncoding,"gzip"),d}function Ui(t){return t[0]===31&&t[1]===139}async function M4(t){let e=Qe.get(Qe.AssetLocation);if(e==null)return be();let r=Ph.default.join("fonts",t.params.fontStack,t.params.range)+".pbf";if(e.endsWith(".tar.co"))return z1(t,e,r,"application/x-protobuf");try{let i=nt.join(e,r),n=await nt.read(i),o=qe.key(n);if(qe.isNotModified(t,o))return ct();let a=ee.ok().buffer(n,"application/x-protobuf");return a.header(re.ETag,o),a.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Ui(n)&&a.header(re.ContentEncoding,"gzip"),a}catch(i){if(i.code===404)return be();throw i}}async function TS(t){let e=new Set;for await(let r of nt.list(t)){if(!r.endsWith(".pbf"))continue;let i=Ph.default.basename(Ph.default.dirname(r));i.includes("/")||e.add(i)}return[...e].sort()}async function E4(t){let e=Qe.get(Qe.AssetLocation);if(e==null)return be();if(e.endsWith(".tar.co"))return z1(t,e,"fonts.json","application/json");try{let r=nt.join(e,"/fonts"),i=await TS(r),n=qe.key(i);if(qe.isNotModified(t,n))return ct();let o=ee.ok().buffer(JSON.stringify(i),"application/json");return o.header(re.ETag,n),o.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),o}catch(r){if(r.code===404)return be();throw r}}var jd=de(require("fs"),1),Bh=de(require("path"),1),L4=de(O4(),1),$d=de(require("sharp"),1),N4=de(require("url"),1);var Lh=de(require("sharp"),1);function OS(t){return t!=null}var kh=new Map,In=class{constructor(e){this.tileSize=e}isTooLarge(e){return!!(e.resize&&(e.resize.width>=In.MaxImageSize||e.resize.height>=In.MaxImageSize))}getEmptyImage(e,r){let i=[e,r.r,r.g,r.b,r.alpha].join("-"),n=kh.get(i);return n||(n=this.toImage(e,this.createImage(r)),kh.size>128&&kh.clear(),kh.set(i,n),n)}toImage(e,r){switch(e){case He.Jpeg:return r.jpeg().toBuffer();case He.Png:return r.png().toBuffer();case He.Webp:return r.webp().toBuffer();case He.Avif:return r.avif().toBuffer();default:throw new Error(`Invalid image format "${e}"`)}}async getImageBuffer(e,r,i){return e.length===0?this.getEmptyImage(r,i):this.toImage(r,this.createImage(i).composite(e))}isDirectImage(e){var r;if(e.layers.length!==1)return!1;let i=e.layers[0];if(i.x!==0||i.y!==0||i.crop!=null||i.extract!=null||i.resize!=null)return!1;let n=i.tiff.getImage(i.source.imageId),o=n.tileSize;return!(o.height!==this.tileSize||o.width!==this.tileSize||!(!((r=n.compression)===null||r===void 0)&&r.includes(e.format))||e.background.alpha!==0)}async compose(e){var r;let i=(r=e.metrics)!==null&&r!==void 0?r:new _s;if(i.start("compose:overlay"),this.isDirectImage(e)){let h=e.layers[0],d=await h.tiff.getTile(h.source.x,h.source.y,h.source.imageId);return i.end("compose:overlay"),d==null?{buffer:await this.getEmptyImage(e.format,e.background),metrics:i,layers:0}:(i.start("compose:direct"),i.end("compose:direct"),{buffer:Buffer.from(d.bytes),metrics:i,layers:1})}let n=[];for(let h of e.layers)this.isTooLarge(h)||n.push(this.composeTile(h,e.resizeKernel));let o=await Promise.all(n).then(h=>h.filter(OS));i.end("compose:overlay"),i.start("compose:compress");let a=await this.getImageBuffer(o,e.format,e.background);return i.end("compose:compress"),{buffer:a,metrics:i,layers:o.length}}async composeTile(e,r){let i=await e.tiff.getTile(e.source.x,e.source.y,e.source.imageId);if(i==null)return null;let n=(0,Lh.default)(Buffer.from(i.bytes)),{extract:o,resize:a,crop:h}=e;if(o&&n.extract({top:0,left:0,width:o.width,height:o.height}),a){let d={fit:Lh.default.fit.cover,kernel:a.scale>1?r.in:r.out};n.resize(a.width,a.height,d)}return h&&n.extract({top:h.y,left:h.x,width:h.width,height:h.height}),{input:await n.toBuffer(),top:e.y,left:e.x}}createImage(e){return(0,Lh.default)({create:{width:this.tileSize,height:this.tileSize,channels:4,background:e}})}};In.MaxImageSize=256*2**15;var zd=class{constructor(e){Hc(this,"value");Hc(this,"next");this.value=e}},fi,Ts,Is,U1=class{constructor(){bt(this,fi,void 0);bt(this,Ts,void 0);bt(this,Is,void 0);this.clear()}enqueue(e){let r=new zd(e);Ee(this,fi)?(Ee(this,Ts).next=r,Ze(this,Ts,r)):(Ze(this,fi,r),Ze(this,Ts,r)),Gc(this,Is)._++}dequeue(){let e=Ee(this,fi);if(!!e)return Ze(this,fi,Ee(this,fi).next),Gc(this,Is)._--,e.value}clear(){Ze(this,fi,void 0),Ze(this,Ts,void 0),Ze(this,Is,0)}get size(){return Ee(this,Is)}*[Symbol.iterator](){let e=Ee(this,fi);for(;e;)yield e.value,e=e.next}};fi=new WeakMap,Ts=new WeakMap,Is=new WeakMap;function Ud(t){if(!((Number.isInteger(t)||t===Number.POSITIVE_INFINITY)&&t>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let e=new U1,r=0,i=()=>{r--,e.size>0&&e.dequeue()()},n=async(h,d,m)=>{r++;let p=(async()=>h(...m))();d(p);try{await p}catch{}i()},o=(h,d,m)=>{e.enqueue(n.bind(void 0,h,d,m)),(async()=>(await Promise.resolve(),r<t&&e.size>0&&e.dequeue()()))()},a=(h,...d)=>new Promise(m=>{o(h,m,d)});return Object.defineProperties(a,{activeCount:{get:()=>r},pendingCount:{get:()=>e.size},clearQueue:{value:()=>{e.clear()}}}),a}var kS=Ud(Qe.getNumber(Qe.TiffConcurrency,25));function LS(t){let e=t.toLowerCase();return e.endsWith(".tif")||e.endsWith(".tiff")?t:`${t}.tiff`}var NS=new In(256),BS={in:"lanczos3",out:"lanczos3"},DS={r:0,g:0,b:0,alpha:0},Nh={async getTiffsForTile(t,e,r){let i=await _e.getAllImagery(e.layers,[r.tileMatrix.projection]),n=[],o=r.tileMatrix.tileToSourceBounds(r.tile),a=Mt.convertZoomLevel(r.tile.z,r.tileMatrix,Yn.get(Re.Google));for(let h of e.layers){if(h.maxZoom!=null&&a>h.maxZoom||h.minZoom!=null&&a<h.minZoom)continue;let d=h[r.tileMatrix.projection.code];if(d==null){t.log.warn({layer:h.name,projection:r.tileMatrix.projection.code},"Failed to lookup imagery");continue}let m=i.get(d);if(m==null){t.log.warn({layer:h.name,projection:r.tileMatrix.projection.code,imgId:d},"Failed to lookup imagery");continue}if(!!o.intersects(xe.fromJson(m.bounds)))for(let p of m.files){if(!o.intersects(xe.fromJson(p)))continue;let M=Er.join(m.uri,LS(p.name));n.push(M)}}return n},async tile(t,e,r){if(r.tileType===rr.MapboxVectorTiles)return be();let i=await this.getTiffsForTile(t,e,r),n=qe.key(i);if(qe.isNotModified(t,n))return ct();let o=[];for(let M of i)o.push(kS(()=>ur.getCog(M).catch(R=>(t.log.warn({error:R,tiff:M},"TiffLoadFailed"),null))));let a=(await Promise.all(o)).filter(M=>M!=null),d=await new aa(r.tileMatrix).tile(a,r.tile.x,r.tile.y,r.tile.z),m=await NS.compose({layers:d,format:r.tileType,background:e.background??DS,resizeKernel:e.resizeKernel??BS,metrics:t.timer});t.set("layersUsed",m.layers),t.set("bytes",m.buffer.byteLength);let p=new ee(200,"ok");return p.header(re.ETag,n),p.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),p.buffer(m.buffer,"image/"+r.tileType),p}};var jS={},zS=[{tileSet:"health",tileMatrix:lt,tileType:He.Png,tile:{x:252,y:156,z:8}},{tileSet:"health",tileMatrix:on,tileType:He.Png,tile:{x:30,y:33,z:6}}],k4=256;async function US(t){if(Buffer.isBuffer(t.buf))return t.buf;let e=t.tile,r=`static/expected_tile_${t.tileMatrix.identifier}_${e.x}_${e.y}_z${e.z}.${t.tileType}`;try{return await jd.promises.readFile(r)}catch(i){if(i.code!=="ENOENT")throw i;let n=Bh.join(Bh.dirname(N4.default.fileURLToPath(jS.url)),"..","..",r);return await jd.promises.readFile(n)}}async function qd(t){let e=await _e.TileSet.get(_e.TileSet.id("health"));if(e==null)throw new ee(500,'TileSet: "health" not found');for(let i of zS){let n=await Nh.tile(t,e,i);if(n.status!==200)return new ee(500,n.statusDescription);if(!Buffer.isBuffer(n._body))throw new ee(500,"Not a Buffer response content.");let o=await(0,$d.default)(n._body).raw().toBuffer(),a=await US(i);i.buf=a;let h=await(0,$d.default)(a).raw().toBuffer(),d=Buffer.alloc(h.length),m=(0,L4.default)(h,o,d,k4,k4);if(m)return t.log.error({missMatchedPixels:m,projection:i.tileMatrix.identifier,xyz:i.tile},"Health:MissMatch"),new ee(500,"TileSet does not match.")}let r=new ee(200,"ok");return r.header(re.CacheControl,"no-store"),r}var B4=require("util"),D4=require("zlib");var $S=(0,B4.promisify)(D4.gzip);function qS(t){return t==null?!1:!!(t.endsWith(".geojson")||t.endsWith(".json"))}async function z4(t){let e=t.params.fileName;if(!qS(e))return be();let r=await _e.Imagery.get(_e.Imagery.id(t.params.imageryId));if(r==null)return be();let i=Er.join(r.uri,e);try{let n=await Er.read(i),o=qe.key(n);if(qe.isNotModified(t,o))return ct();let a=new ee(200,"ok");return a.header(re.ETag,o),a.header(re.ContentEncoding,"gzip"),a.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),a.buffer(Ui(n)?n:await $S(n),"application/json"),t.set("bytes",n.byteLength),a}catch{return t.log.warn({targetPath:i},"ImageryMetadata:Failed"),be()}}var U4=new ee(200,"ok");U4.header(re.CacheControl,"no-store");async function Fd(){return U4}var j4=de(require("path"),1);var Wd=new Map;Wd.set(".png","image/png");Wd.set(".json","application/json");async function $4(t){let e=Qe.get(Qe.AssetLocation);if(e==null)return be();let r=j4.default.extname(t.params.spriteName),i=Wd.get(r);if(i==null)return be();let n=nt.join("sprites",t.params.spriteName);if(e.endsWith(".tar.co"))return z1(t,e,n,i);try{let o=nt.join(e,n);t.set("target",o);let a=await nt.read(o),h=qe.key(a);if(qe.isNotModified(t,h))return ct();let d=ee.ok().buffer(a,i);return d.header(re.ETag,h),d.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Ui(a)&&d.header(re.ContentEncoding,"gzip"),d}catch(o){if(o.code===404)return be();throw o}}async function q4(t){let e=wt.getTileMatrixSet(t.params.tileMatrix);if(e==null)return be();let r=wt.apiKey(t);t.timer.start("tileset:load");let i=await _e.TileSet.get(_e.TileSet.id(t.params.tileSet));if(t.timer.end("tileset:load"),i==null)return be();let n=wt.getRequestedFormats(t)??[i.format],h={tiles:[[Qe.get(Qe.PublicUrlBase)??"","v1","tiles",i.name,e.identifier,"{z}","{x}","{y}"].join("/")+`.${n[0]}?api=${r}`],tilejson:"3.0.0"},d=Mt.convertZoomLevel(i.maxZoom??30,lt,e,!0),m=Mt.convertZoomLevel(i.minZoom??0,lt,e,!0);i.maxZoom&&(h.maxzoom=d),i.minZoom&&(h.minzoom=m);let p=JSON.stringify(h),M=Buffer.from(p),R=new ee(200,"ok");return R.header(re.CacheControl,"no-store"),R.buffer(M,"application/json"),t.set("bytes",M.byteLength),R}var F4=require("url");function Dh(t,e){if(t==null)return"";let r=Qe.get(Qe.PublicUrlBase)??"";if(!t.startsWith("/"))return t;let i=new F4.URL(nt.join(r,t));return e&&i.searchParams.set("api",e),i.toString().replace(/%7B/g,"{").replace(/%7D/g,"}")}function FS(t,e){let r=JSON.parse(JSON.stringify(t.sources));for(let[i,n]of Object.entries(r)){if(n.type==="vector")n.url=Dh(n.url,e);else if(n.type==="raster"&&Array.isArray(n.tiles))for(let o=0;o<n.tiles.length;o++)n.tiles[o]=Dh(n.tiles[o],e);r[i]=n}return{version:8,id:t.id,name:t.name,sources:r,layers:t.layers,metadata:t.metadata??{},glyphs:Dh(t.glyphs),sprite:Dh(t.sprite)}}async function Hd(t){let e=wt.apiKey(t),r=t.params.styleName,i=_e.Style.id(r),n=await _e.Style.get(i);if(n==null)return be();let o=FS(n.style,e),a=Buffer.from(JSON.stringify(o)),h=qe.key(a);if(qe.isNotModified(t,h))return ct();let d=new ee(200,"ok");return d.header(re.ETag,h),d.header(re.CacheControl,"no-store"),d.buffer(a,"application/json"),t.set("bytes",a.byteLength),d}var K4=require("crypto");var WS={xmlns:"http://www.opengis.net/wmts/1.0","xmlns:ows":"http://www.opengis.net/ows/1.1","xmlns:xlink":"http://www.w3.org/1999/xlink","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","xmlns:gml":"http://www.opengis.net/gml","xsi:schemaLocation":"http://www.opengis.net/wmts/1.0 http://schemas.opengis.net/wmts/1.0/wmtsGetCapabilities_response.xsd",version:"1.0.0"};function W4(t,e){return jr.get(t).boundsToWgs84BoundingBox(e)}var H4=6,G4=4;function V4(t,e){return Number(t.toFixed(e)).toString()}function zh(t,e,r){return`${V4(t,r)} ${V4(e,r)}`}var Uh=class{constructor(e){this.tileMatrixSets=new Map;this.isIndividualLayers=!1;this.httpBase=e.httpBase,this.provider=e.provider,this.tileSet=e.tileSet,this.isIndividualLayers=e.isIndividualLayers;for(let r of e.tileMatrix)this.tileMatrixSets.set(r.identifier,r);this.apiKey=e.apiKey,this.formats=e.formats??a4,this.imagery=e.imagery}async loadImagery(){let e=new Set;for(let r of this.tileMatrixSets.values())for(let i of this.tileSet.layers){let n=i[r.projection.code];n!=null&&e.add(n)}this.imagery=await _e.Imagery.getAll(e)}buildWgs84BoundingBox(e,r){let i;if(r.length>0){let n=r[0];for(let o=1;o<r.length;o++)n=n.union(r[o]);i=W4(e,n.toJson())}else i=W4(e,e.extent);return i[2]<i[0]&&(i[0]=-180,i[2]=180),X("ows:WGS84BoundingBox",{crs:"urn:ogc:def:crs:OGC:2:84"},[X("ows:LowerCorner",zh(i[0],i[1],H4)),X("ows:UpperCorner",zh(i[2],i[3],H4))])}buildBoundingBoxFromImagery(e,r){let i;for(let o of r){let a=o[e.projection.code];if(a==null)continue;let h=this.imagery.get(a);h!=null&&(i==null?i=xe.fromJson(h.bounds):i=i.union(xe.fromJson(h.bounds)))}if(i==null)return null;let n=i.toBbox();return X("ows:BoundingBox",{crs:e.projection.toUrn()},[X("ows:LowerCorner",zh(n[e.indexX],n[e.indexY],G4)),X("ows:UpperCorner",zh(n[e.indexX+2],n[e.indexY+2],G4))])}buildProvider(){if(this.provider==null)return[];let{serviceIdentification:e,serviceProvider:r}=this.provider,{contact:i}=r;return[X("ows:ServiceIdentification",[X("ows:Title",e.title),X("ows:Abstract",e.description),X("ows:ServiceType","OGC WMTS"),X("ows:ServiceTypeVersion","1.0.0"),X("ows:Fees",e.fees),X("ows:AccessConstraints",e.accessConstraints)]),X("ows:ServiceProvider",[X("ows:ProviderName",r.name),X("ows:ProviderSite",{"xlink:href":r.site}),X("ows:ServiceContact",[X("ows:IndividualName",i.individualName),X("ows:PositionName",i.position),X("ows:ContactInfo",[X("ows:Phone",[X("ows:Voice",i.phone)]),X("ows:Address",[X("ows:DeliveryPoint",i.address.deliveryPoint),X("ows:City",i.address.city),X("ows:PostalCode",i.address.postalCode),X("ows:Country",i.address.country),X("ows:ElectronicMailAddress",i.address.email)])])])])]}buildTileUrl(e,r){let i=this.apiKey?`?api=${this.apiKey}`:"";return[this.httpBase,"v1","tiles",e,"{TileMatrixSet}","{TileMatrix}","{TileCol}",`{TileRow}.${r}${i}`].join("/")}buildResourceUrl(e,r){return X("ResourceURL",{format:"image/"+r,resourceType:"tile",template:this.buildTileUrl(e,r)})}buildLayerFromImagery(e){let r=new Set,i=[];for(let d of this.tileMatrixSets.values()){let m=e[d.projection.code];m==null||this.imagery.get(m)==null||(i.push(X("TileMatrixSetLink",[X("TileMatrixSet",d.identifier)])),r.add(d))}let n=vo(e.name),o=[...r.values()],a=o[0];if(a==null)return null;let h=this.imagery.get(e[a.projection.code]??"");return h==null?null:X("Layer",[X("ows:Title",e.title??n),X("ows:Abstract",""),X("ows:Identifier",n),this.buildKeywords(h),...o.map(d=>this.buildBoundingBoxFromImagery(d,[e])),this.buildWgs84BoundingBox(a,[xe.fromJson(h.bounds)]),this.buildStyle(),...this.formats.map(d=>X("Format","image/"+d)),...i,...this.formats.map(d=>this.buildResourceUrl(n,d))])}buildLayer(e){let r=new Set,i=[];for(let m of this.tileMatrixSets.values())e.layers.find(p=>p[m.projection.code]!=null)&&(i.push(X("TileMatrixSetLink",[X("TileMatrixSet",m.identifier)])),r.add(m));let n=vo(e.name),o=[...r.values()],a=o[0];if(a==null)throw new Error("No matrix sets found for layer "+e.name);let h=o.find(m=>m.identifier===lt.identifier)??a,d=[];for(let m of e.layers){let p=this.imagery.get(m[h.projection.code]??"");p!=null&&d.push(xe.fromJson(p.bounds))}return X("Layer",[X("ows:Title",e.title??n),X("ows:Abstract",e.description??""),X("ows:Identifier",n),this.buildKeywords(e),...[...r.values()].map(m=>this.buildBoundingBoxFromImagery(m,e.layers)),this.buildWgs84BoundingBox(h,d),this.buildStyle(),...this.formats.map(m=>X("Format","image/"+m)),...i,...this.formats.map(m=>this.buildResourceUrl(n,m))])}buildKeywords(e){return e.category==null?X("ows:Keywords"):X("ows:Keywords",[X("ows:Keyword",e.category)])}buildStyle(){return X("Style",{isDefault:"true"},[X("ows:Title","Default Style"),X("ows:Identifier","default")])}buildTileMatrixSet(e){return X("TileMatrixSet",[X("ows:Title",e.def.title),e.def.abstract?X("ows:Abstract",e.def.abstract):null,X("ows:Identifier",e.identifier),X("ows:SupportedCRS",e.projection.toUrn()),e.def.wellKnownScaleSet?X("WellKnownScaleSet",e.def.wellKnownScaleSet):null,...e.def.tileMatrix.map(r=>X("TileMatrix",[X("ows:Identifier",r.identifier),X("ScaleDenominator",r.scaleDenominator),X("TopLeftCorner",r.topLeftCorner.join(" ")),X("TileWidth",r.tileWidth),X("TileHeight",r.tileHeight),X("MatrixWidth",r.matrixWidth),X("MatrixHeight",r.matrixHeight)]))])}toVNode(){let e=[];if(e.push(this.buildLayer(this.tileSet)),this.isIndividualLayers){let r=new Map;for(let n of this.tileSet.layers)r.set(vo(n.name),n);let i=Array.from(r.values()).sort((n,o)=>(n.title??n.name).localeCompare(o.title??o.name));for(let n of i)e.push(this.buildLayerFromImagery(n))}for(let r of this.tileMatrixSets.values())e.push(this.buildTileMatrixSet(r));return X("Capabilities",WS,[...this.buildProvider(),X("Contents",e)])}toXml(){return`<?xml version="1.0" encoding="utf-8"?>
187
- `+this.toVNode().toString()}};function HS(t){if(t==null)return[lt,on];let e=wt.getTileMatrixSet(t);return e==null?null:[e]}async function jh(t){let e=wt.apiKey(t),r=t.params.tileSet??"aerial",i=HS(t.params.tileMatrix);if(i==null)return be();let n=Qe.get(Qe.PublicUrlBase)??"";t.timer.start("tileset:load");let o=await _e.TileSet.get(_e.TileSet.id(r??"aerial"));if(t.timer.end("tileset:load"),o==null||o.type!==vt.Raster)return be();let a=await _e.Provider.get(_e.Provider.id("linz"));t.timer.start("imagery:load");let h=await _e.getAllImagery(o.layers,i.map(R=>R.projection));t.timer.end("imagery:load");let d=new Uh({httpBase:n,provider:a??void 0,tileSet:o,tileMatrix:i,isIndividualLayers:t.params.tileMatrix==null,imagery:h,apiKey:e,formats:wt.getRequestedFormats(t)}).toXml();if(d==null)return be();let m=Buffer.from(d),p=(0,K4.createHash)("sha256").update(m).digest("base64");if(qe.isNotModified(t,p))return ct();let M=new ee(200,"ok");return M.header(re.ETag,p),M.header(re.CacheControl,"no-store"),M.buffer(m,"text/xml"),t.set("bytes",m.byteLength),M}var J4={async tile(t,e,r){if(r.tileType!==rr.MapboxVectorTiles)return be();if(r.tileMatrix.identifier!==lt.identifier)return be();if(e.layers.length>1)return new ee(500,"Too many layers in tileset");let[i]=e.layers,n=i[3857];if(n==null)return new ee(500,"Layer url not found from tileset Config");let o=(1<<r.tile.z)-1-r.tile.y,a=`tiles/${r.tile.z}/${r.tile.x}/${o}.pbf.gz`,h=`${n}#${a}`,d=qe.key(h);if(qe.isNotModified(t,d))return ct();t.timer.start("cotar:load");let m=await ur.getCotar(n);if(m==null)return new ee(500,"Failed to load VectorTiles");t.timer.end("cotar:load"),t.timer.start("cotar:tile");let p=await m.get(a);if(p==null)return be();t.timer.end("cotar:tile");let M=Buffer.from(p),R=ee.ok().buffer(M,"application/x-protobuf");return R.header(re.ETag,d),R.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Ui(M)&&R.header(re.ContentEncoding,"gzip"),R}};async function Z4(t){let e=wt.xyz(t);t.timer.start("tileset:load");let r=await _e.TileSet.get(_e.TileSet.id(e.tileSet));if(t.timer.end("tileset:load"),r==null)return be();switch(r.type){case vt.Vector:return J4.tile(t,r,e);case vt.Raster:return Nh.tile(t,r,e);default:return new ee(400,"Invalid tileset")}}async function Gd(){let t=new ee(200,"ok");return t.header(re.CacheControl,"no-store"),t.json({version:"v6.32.0",hash:"cf9e8d4e61f7634acf51b9a837bbab6889761f1b"}),t}var Ye=ar.http(Hu.get());Ye.router.hook("request",t=>{t.set("name","LambdaTiler"),Tn.reset()});Ye.router.hook("response",(t,e)=>{Tn.requests.length>0&&(t.set("requests",Tn.requests.slice(0,100)),t.set("requestCount",Tn.requests.length)),t.set("sources",{hits:ur.cache.hits,misses:ur.cache.misses,size:ur.cache.currentSize,resets:ur.cache.resets,cacheA:ur.cache.cacheA.size,cacheB:ur.cache.cacheB.size}),!(t instanceof Rn)&&t.headers.has("origin")&&e.header("access-control-allow-origin","*")});Ye.router.options("*",t=>Ye.router.router.find("GET",t.path)==null?be():ee.ok());Ye.router.get("/ping",Fd);Ye.router.get("/health",qd);Ye.router.get("/version",Gd);Ye.router.get("/v1/ping",Fd);Ye.router.get("/v1/health",qd);Ye.router.get("/v1/version",Gd);Ye.router.get("/v1/imagery/:imageryId/:fileName",z4);Ye.router.get("/v1/sprites/:spriteName",$4);Ye.router.get("/v1/fonts.json",E4);Ye.router.get("/v1/fonts/:fontStack/:range.pbf",M4);Ye.router.get("/v1/styles/:styleName.json",Hd);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/style/:styleName.json",Hd);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/tile.json",q4);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/:z/:x/:y.:tileType",Z4);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/attribution.json",gd);Ye.router.get("/v1/attribution/:tileSet/:tileMatrix/summary.json",gd);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/WMTSCapabilities.xml",jh);Ye.router.get("/v1/tiles/:tileSet/WMTSCapabilities.xml",jh);Ye.router.get("/v1/tiles/WMTSCapabilities.xml",jh);0&&(module.exports={handler});
187
+ `+this.toVNode().toString()}};function HS(t){if(t==null)return[lt,on];let e=wt.getTileMatrixSet(t);return e==null?null:[e]}async function jh(t){let e=wt.apiKey(t),r=t.params.tileSet??"aerial",i=HS(t.params.tileMatrix);if(i==null)return be();let n=Qe.get(Qe.PublicUrlBase)??"";t.timer.start("tileset:load");let o=await _e.TileSet.get(_e.TileSet.id(r??"aerial"));if(t.timer.end("tileset:load"),o==null||o.type!==vt.Raster)return be();let a=await _e.Provider.get(_e.Provider.id("linz"));t.timer.start("imagery:load");let h=await _e.getAllImagery(o.layers,i.map(R=>R.projection));t.timer.end("imagery:load");let d=new Uh({httpBase:n,provider:a??void 0,tileSet:o,tileMatrix:i,isIndividualLayers:t.params.tileMatrix==null,imagery:h,apiKey:e,formats:wt.getRequestedFormats(t)}).toXml();if(d==null)return be();let m=Buffer.from(d),p=(0,K4.createHash)("sha256").update(m).digest("base64");if(qe.isNotModified(t,p))return ct();let M=new ee(200,"ok");return M.header(re.ETag,p),M.header(re.CacheControl,"no-store"),M.buffer(m,"text/xml"),t.set("bytes",m.byteLength),M}var J4={async tile(t,e,r){if(r.tileType!==rr.MapboxVectorTiles)return be();if(r.tileMatrix.identifier!==lt.identifier)return be();if(e.layers.length>1)return new ee(500,"Too many layers in tileset");let[i]=e.layers,n=i[3857];if(n==null)return new ee(500,"Layer url not found from tileset Config");let o=(1<<r.tile.z)-1-r.tile.y,a=`tiles/${r.tile.z}/${r.tile.x}/${o}.pbf.gz`,h=`${n}#${a}`,d=qe.key(h);if(qe.isNotModified(t,d))return ct();t.timer.start("cotar:load");let m=await ur.getCotar(n);if(m==null)return new ee(500,"Failed to load VectorTiles");t.timer.end("cotar:load"),t.timer.start("cotar:tile");let p=await m.get(a);if(p==null)return be();t.timer.end("cotar:tile");let M=Buffer.from(p),R=ee.ok().buffer(M,"application/x-protobuf");return R.header(re.ETag,d),R.header(re.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Ui(M)&&R.header(re.ContentEncoding,"gzip"),R}};async function Z4(t){let e=wt.xyz(t);t.timer.start("tileset:load");let r=await _e.TileSet.get(_e.TileSet.id(e.tileSet));if(t.timer.end("tileset:load"),r==null)return be();switch(r.type){case vt.Vector:return J4.tile(t,r,e);case vt.Raster:return Nh.tile(t,r,e);default:return new ee(400,"Invalid tileset")}}async function Gd(){let t=new ee(200,"ok");return t.header(re.CacheControl,"no-store"),t.json({version:"v6.32.1",hash:"4544a7d98667c5274142f1bb6bf61f02e4e5f618"}),t}var Ye=ar.http(Hu.get());Ye.router.hook("request",t=>{t.set("name","LambdaTiler"),Tn.reset()});Ye.router.hook("response",(t,e)=>{Tn.requests.length>0&&(t.set("requests",Tn.requests.slice(0,100)),t.set("requestCount",Tn.requests.length)),t.set("sources",{hits:ur.cache.hits,misses:ur.cache.misses,size:ur.cache.currentSize,resets:ur.cache.resets,cacheA:ur.cache.cacheA.size,cacheB:ur.cache.cacheB.size}),!(t instanceof Rn)&&t.headers.has("origin")&&e.header("access-control-allow-origin","*")});Ye.router.options("*",t=>Ye.router.router.find("GET",t.path)==null?be():ee.ok());Ye.router.get("/ping",Fd);Ye.router.get("/health",qd);Ye.router.get("/version",Gd);Ye.router.get("/v1/ping",Fd);Ye.router.get("/v1/health",qd);Ye.router.get("/v1/version",Gd);Ye.router.get("/v1/imagery/:imageryId/:fileName",z4);Ye.router.get("/v1/sprites/:spriteName",$4);Ye.router.get("/v1/fonts.json",E4);Ye.router.get("/v1/fonts/:fontStack/:range.pbf",M4);Ye.router.get("/v1/styles/:styleName.json",Hd);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/style/:styleName.json",Hd);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/tile.json",q4);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/:z/:x/:y.:tileType",Z4);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/attribution.json",gd);Ye.router.get("/v1/attribution/:tileSet/:tileMatrix/summary.json",gd);Ye.router.get("/v1/tiles/:tileSet/:tileMatrix/WMTSCapabilities.xml",jh);Ye.router.get("/v1/tiles/:tileSet/WMTSCapabilities.xml",jh);Ye.router.get("/v1/tiles/WMTSCapabilities.xml",jh);0&&(module.exports={handler});
188
188
  /*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
189
189
  /*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
190
190
  /*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basemaps/lambda-tiler",
3
- "version": "6.32.0",
3
+ "version": "6.32.1",
4
4
  "lockfileVersion": 2,
5
5
  "requires": true,
6
6
  "packages": {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@basemaps/lambda-tiler",
3
- "version": "6.32.0",
3
+ "version": "6.32.1",
4
4
  "lockfileVersion": 2,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@basemaps/lambda-tiler",
9
- "version": "6.32.0",
9
+ "version": "6.32.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "sharp": "0.30.7"
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basemaps/lambda-tiler",
3
- "version": "6.32.0",
3
+ "version": "6.32.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/linz/basemaps.git",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basemaps/lambda-tiler",
3
- "version": "6.32.0",
3
+ "version": "6.32.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/linz/basemaps.git",
@@ -22,16 +22,16 @@
22
22
  "types": "./build/index.d.ts",
23
23
  "license": "MIT",
24
24
  "dependencies": {
25
- "@basemaps/config": "^6.32.0",
26
- "@basemaps/geo": "^6.31.0",
25
+ "@basemaps/config": "^6.32.1",
26
+ "@basemaps/geo": "^6.32.1",
27
27
  "@basemaps/lambda": "^6.7.0",
28
- "@basemaps/shared": "^6.32.0",
29
- "@basemaps/tiler": "^6.31.0",
30
- "@basemaps/tiler-sharp": "^6.32.0",
28
+ "@basemaps/shared": "^6.32.1",
29
+ "@basemaps/tiler": "^6.32.1",
30
+ "@basemaps/tiler-sharp": "^6.32.1",
31
31
  "@chunkd/fs": "^8.4.0",
32
32
  "@cogeotiff/core": "^7.0.0",
33
33
  "@cotar/core": "^5.4.0",
34
- "@linzjs/geojson": "^6.28.1",
34
+ "@linzjs/geojson": "^6.32.1",
35
35
  "@linzjs/lambda": "^3.2.1",
36
36
  "p-limit": "^4.0.0",
37
37
  "path-to-regexp": "^6.1.0",
@@ -52,12 +52,12 @@
52
52
  "bundle": "./bundle.sh"
53
53
  },
54
54
  "devDependencies": {
55
- "@basemaps/attribution": "^6.31.0",
55
+ "@basemaps/attribution": "^6.32.1",
56
56
  "@types/aws-lambda": "^8.10.75",
57
57
  "@types/node": "^17.0.34",
58
58
  "@types/pixelmatch": "^5.0.0",
59
59
  "@types/sharp": "^0.30.3",
60
60
  "pretty-json-log": "^1.0.0"
61
61
  },
62
- "gitHead": "cf9e8d4e61f7634acf51b9a837bbab6889761f1b"
62
+ "gitHead": "4544a7d98667c5274142f1bb6bf61f02e4e5f618"
63
63
  }