riverforecastsystem 0.0.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,32 @@
1
+ The Clear BSD License
2
+
3
+ Copyright (c) 2026 Riley Chad Hales PhD
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted (subject to the limitations in the disclaimer
8
+ below) provided that the following conditions are met:
9
+
10
+ * Redistributions of source code must retain the above copyright notice,
11
+ this list of conditions and the following disclaimer.
12
+
13
+ * Redistributions in binary form must reproduce the above copyright
14
+ notice, this list of conditions and the following disclaimer in the
15
+ documentation and/or other materials provided with the distribution.
16
+
17
+ * Neither the name of the copyright holder nor the names of its
18
+ contributors may be used to endorse or promote products derived from this
19
+ software without specific prior written permission.
20
+
21
+ NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
22
+ THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
23
+ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
25
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
26
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
29
+ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
30
+ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
+ POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1 @@
1
+ class e extends Error{}class t extends e{_tag="NotFoundError";name="NotFoundError";path;found;constructor(e,t={}){super(`Not found: ${e}`,{cause:t.cause}),this.path=t.path,this.found=t.found}}class n extends e{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(e,t={}){super(e,{cause:t.cause}),this.path=t.path}}class r extends e{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(e){super(`Unknown codec: ${e}`),this.codec=e}}class a extends e{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(e){super([`Failed to ${e.direction} chunk`,e.codec&&`via codec "${e.codec}"`,e.chunkPath&&`at ${e.chunkPath}`].filter(Boolean).join(" "),{cause:e.cause}),this.direction=e.direction,this.codec=e.codec,this.chunkPath=e.chunkPath}}class s extends e{_tag="InvalidSelectionError";name="InvalidSelectionError"}class i extends e{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(e){super(`Unsupported: ${e}`),this.feature=e}}function o(e){return()=>{throw new i(`${e} encode`)}}class c{kind="array_to_array";constructor(e,t){if(e.keepbits<0)throw new n("keepbits must be zero or positive")}static fromConfig(e,t){return new c(e,t)}encode=o("bitround");decode(e){return e}}function u(e){return e instanceof ArrayBuffer||e instanceof SharedArrayBuffer}class d{#e;constructor(e,t,n){"number"==typeof e?this.#e=new Uint8Array(e):u(e)?this.#e=new Uint8Array(e,t,n):this.#e=new Uint8Array(Array.from(e,e=>e?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#e.byteOffset}get byteLength(){return this.#e.byteLength}get buffer(){return this.#e.buffer}get length(){return this.#e.length}get(e){let t=this.#e[e];return"number"==typeof t?0!==t:t}set(e,t){this.#e[e]=t?1:0}fill(e){this.#e.fill(e?1:0)}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.get(e)}}class l{_data;chars;#t;constructor(e,t,n,r){if(this.chars=e,this.#t=new TextEncoder,"number"==typeof t)this._data=new Uint8Array(t*e);else if(u(t))r&&(r*=e),this._data=new Uint8Array(t,n,r);else{let n=Array.from(t);this._data=new Uint8Array(n.length*e);for(let e=0;e<n.length;e++)this.set(e,n[e])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(e){const t=new Uint8Array(this.buffer,this.byteOffset+this.chars*e,this.chars);return(new TextDecoder).decode(t).replace(/\x00/g,"")}set(e,t){const n=new Uint8Array(this.buffer,this.byteOffset+this.chars*e,this.chars);n.fill(0),n.set(this.#t.encode(t))}fill(e){const t=this.#t.encode(e);for(let e=0;e<this.length;e++)this._data.set(t,e*this.chars)}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.get(e)}}class f{#n;chars;constructor(e,t,n,r){if(this.chars=e,"number"==typeof t)this.#n=new Int32Array(t*e);else if(u(t))r&&(r*=e),this.#n=new Int32Array(t,n,r);else{const n=t,r=new f(e,1);this.#n=new Int32Array(function*(){for(let e of n)r.set(0,e),yield*r.#n}())}}get BYTES_PER_ELEMENT(){return this.#n.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#n.byteLength}get byteOffset(){return this.#n.byteOffset}get buffer(){return this.#n.buffer}get length(){return this.#n.length/this.chars}get(e){const t=this.chars*e;let n="";for(let e=0;e<this.chars;e++)n+=String.fromCodePoint(this.#n[t+e]);return n.replace(/\u0000/g,"")}set(e,t){const n=this.chars*e,r=this.#n.subarray(n,n+this.chars);r.fill(0);for(let e=0;e<this.chars;e++)r[e]=t.codePointAt(e)??0}fill(e){this.set(0,e);let t=this.#n.subarray(0,this.chars);for(let e=1;e<this.length;e++)this.#n.set(t,e*this.chars)}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.get(e)}}function h(){if("undefined"==typeof SharedArrayBuffer)throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function y(e,t){return new SharedArrayBuffer(e)}function p(e){const t=(new TextDecoder).decode(e);try{return JSON.parse(t)}catch(e){throw new n("Failed to decode JSON",{cause:e})}}function g(e,t){const n=t/2,r=t-1;let a=0;for(let s=0;s<e.length;s+=t)for(let t=0;t<n;t+=1)a=e[s+t],e[s+t]=e[s+r-t],e[s+r-t]=a}function m(e){if("v2:object"===e)return globalThis.Array;let t=e.match(/v2:([US])(\d+)/);if(t){let[,e,n]=t;return("U"===e?f:l).bind(null,Number(n))}if("string"===e)return globalThis.Array;let r={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:d}[e];if(!r)throw new n(`Unknown or unsupported dataType: ${e}`);return r}function w(e,t){const n=e.length;"string"==typeof t&&(t="C"===t?Array.from({length:n},(e,t)=>t):Array.from({length:n},(e,t)=>n-1-t)),v(n===t.length,"Order length must match the number of dimensions.");let r=1,a=new Array(n);for(let n=t.length-1;n>=0;n--)a[t[n]]=r,r*=e[t[n]];return a}function b({name:e,configuration:t}){if("default"===e){const e=t?.separator??"/";return t=>["c",...t].join(e)}if("v2"===e){const e=t?.separator??".";return t=>t.join(e)||"0"}throw new n(`Unknown chunk key encoding: ${e}`)}function _(e){if("|O"===e)return{dataType:"v2:object"};let t=e.match(/^([<|>])(.*)$/);if(!t)throw new n(`Invalid dtype: ${e}`);let[,r,a]=t,s={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[a]??(a.startsWith("S")||a.startsWith("U")?`v2:${a}`:void 0);if(!s)throw new n(`Unsupported or unknown dtype: ${e}`);return"|"===r?{dataType:s}:{dataType:s,endian:"<"===r?"little":"big"}}function E(e){return!("fixedscaleoffset"!==e.id&&"numcodecs.fixedscaleoffset"!==e.id||"number"!=typeof e.scale||"number"!=typeof e.offset||void 0!==e.astype&&"string"!=typeof e.astype||void 0!==e.dtype&&"string"!=typeof e.dtype)}function T(e,t){if("number"!==t&&"bigint"!==t&&"boolean"!==t&&"object"!==t&&"string"!==t)return e===t;let n="bool"===e;if("boolean"===t)return n;let r=e.startsWith("v2:U")||e.startsWith("v2:S")||"string"===e;if("string"===t)return r;let a="int64"===e||"uint64"===e;if("bigint"===t)return a;let s="v2:object"===e;return"object"===t?s:!(r||a||n||s)}function k(e){return"sharding_indexed"===e?.name}function A(e){if(("uint64"===e.data_type||"int64"===e.data_type)&&null!=e.fill_value)return BigInt(e.fill_value);let t="float16"===e.data_type||"float32"===e.data_type||"float64"===e.data_type;if("string"==typeof e.fill_value&&t){let t={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(e.fill_value in t)return t[e.fill_value]}return e.fill_value}function S(e,...t){if(!t.some(t=>e instanceof t))throw e}function v(e,t=""){if(!e)throw new Error(t)}async function C(e,{format:t,signal:n}){let r;if(e instanceof ArrayBuffer)r=new Response(e);else{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);r=new Response(t.slice().buffer)}v(r.body,"Response does not contain body.");try{const e=new Response(r.body.pipeThrough(new DecompressionStream(t),{signal:n}));return await e.arrayBuffer()}catch{throw n?.throwIfAborted(),new Error(`Failed to decode ${t}`)}}const N=function(){const e=new Uint32Array([305419896]);return!(18===new Uint8Array(e.buffer,e.byteOffset,e.byteLength)[0])}();function B(e){return"BYTES_PER_ELEMENT"in e?e.BYTES_PER_ELEMENT:4}class M{kind="array_to_bytes";#r;#a;#s;#i;#o;constructor(e,t){this.#o=e?.endian,this.#a=m(t.dataType),this.#i=t.shape,this.#r=w(t.shape,"C");const n=new this.#a(0);this.#s=n.BYTES_PER_ELEMENT}static fromConfig(e,t){return new M(e,t)}encode(e){let t=new Uint8Array(e.data.buffer);return N&&"big"===this.#o&&(t=t.slice(),g(t,B(this.#a))),t}computeEncodedSize(e){return e}decode(e){return N&&"big"===this.#o&&g(e=e.slice(),B(this.#a)),{data:new this.#a(e.buffer,e.byteOffset,e.byteLength/this.#s),shape:this.#i,stride:this.#r}}}const L={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},x={float16:2,float32:4,float64:8};function I(e){return e in x}function $(e){return"int64"===e||"uint64"===e}function U(e,t){if($(e)){if("number"!=typeof t||!Number.isInteger(t))throw new n(`Expected an integer value for data type "${e}", got ${JSON.stringify(t)}`);return BigInt(t)}if("number"==typeof t){if(!I(e)&&!Number.isInteger(t))throw new n(`Expected an integer value for data type "${e}", got ${t}`);return t}if(!I(e))throw new n(`String-encoded scalar "${t}" is not valid for non-float data type "${e}"`);return t in L?L[t]:function(e,t){const n=BigInt(e),r=new ArrayBuffer(t),a=new DataView(r);if(2===t){if("function"!=typeof a.getFloat16)throw new i("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return a.setUint16(0,Number(n)),a.getFloat16(0)}return 4===t?(a.setUint32(0,Number(n)),a.getFloat32(0)):(a.setBigUint64(0,n),a.getFloat64(0))}(t,x[e])}const P=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),O={int8:[-128,127],uint8:[0,255],int16:[-32768,32767],uint16:[0,65535],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},R={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function z(e,t,n){return e.map(([e,r])=>({src:U(t,e),tgt:U(n,r)}))}function F(e){if(!Number.isFinite(e))return e;if(.5===Math.abs(e-Math.trunc(e))){const t=Math.floor(e),n=Math.ceil(e);return t%2==0?t:n}return Math.round(e)}function Y(e){return Math.sign(e)*Math.floor(Math.abs(e)+.5)}function V(e){switch(e){case"nearest-even":return F;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return Y}}function j(e,t,n){const r=t-e+1;switch(n){case"clamp":return n=>n<e?e:n>t?t:n;case"wrap":return n=>n>=e&&n<=t?n:((n-e)%r+r)%r+e;default:return n=>{if(n>=e&&n<=t)return n;throw new Error(`Value ${n} out of range [${e}, ${t}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function J(e,t,n){const r=t-e+1n;switch(n){case"clamp":return n=>n<e?e:n>t?t:n;case"wrap":return n=>n>=e&&n<=t?n:((n-e)%r+r)%r+e;default:return n=>{if(n>=e&&n<=t)return n;throw new Error(`Value ${n} out of range [${e}, ${t}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class D{kind="array_to_array";#c;#u;#d;#l;constructor(e,t,n,r,a,s){this.#c=t,this.#u=m(e),this.#d=W(t,e,n,r,a),this.#l=W(e,t,n,r,s)}getEncodedMeta(e){let t=e.fillValue;return null!=t&&(t=this.#l(t)),{...e,dataType:this.#c,fillValue:t}}static fromConfig(e,t){const r=t.dataType,a=e.data_type;if(!P.has(r))throw new n(`cast_value codec does not support array data type: ${r}`);if(!P.has(a))throw new n(`cast_value codec does not support encoded data type: ${a}`);const s=e.rounding??"nearest-even",i=e.scalar_map?.decode?z(e.scalar_map.decode,a,r):[],o=e.scalar_map?.encode?z(e.scalar_map.encode,r,a):[];return new D(r,a,s,e.out_of_range,i,o)}encode=o("cast_value");decode(e){const t=e.data,n=new this.#u(t.length);for(let e=0;e<t.length;e++)n[e]=this.#d(t[e]);return{data:n,shape:e.shape,stride:e.stride}}}function W(e,t,r,a,s){const i=I(e),o=$(e),c=I(t),u=$(t);let d;if(i&&c){if("nearest-even"!==r)throw new n(`cast_value float -> float only supports "nearest-even" rounding, got "${r}"`);d=e=>e}else if(!i||c||u)if(i&&u){const e=V(r),n=J(...R[t],a);d=t=>{if(!Number.isFinite(t))throw new Error(`Cannot cast ${t} to integer type without scalar_map`);return n(BigInt(e(t)))}}else if(i||o||!c)if(o&&c)d=e=>Number(e);else if(i||o||c||u)if(i||o||!u)if(!o||c||u){if(!o||!u)throw new Error(`Unhandled type combination: ${e} -> ${t}`);d=J(...R[t],a)}else{const e=j(...O[t],a);d=t=>e(Number(t))}else{const e=J(...R[t],a);d=t=>e(BigInt(t))}else d=j(...O[t],a);else d=e=>e;else{const e=V(r),n=j(...O[t],a);d=t=>{if(!Number.isFinite(t))throw new Error(`Cannot cast ${t} to integer type without scalar_map`);return n(e(t))}}if(0===s.length)return d;return e=>{const t=function(e,t){for(const n of t)if("number"==typeof n.src&&Number.isNaN(n.src)){if("number"==typeof e&&Number.isNaN(e))return n.tgt}else if(e===n.src)return n.tgt}(e,s);return void 0!==t?t:d(e)}}class q{kind="bytes_to_bytes";static fromConfig(){return new q}encode=o("crc32c");decode(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength-4)}computeEncodedSize(e){return e+4}}const G=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function K(e,t){const n=e.length;let r=0===n||1===t[n-1];for(let a=n-2;a>=0&&r;a--)r=t[a]===t[a+1]*e[a+1];if(r)return;let a=0===n||1===t[0];for(let r=1;r<n&&a;r++)a=t[r]===t[r-1]*e[r-1];if(!a)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(e)} stride=${JSON.stringify(t)}`)}class X{kind="array_to_array";#f;constructor(e){this.#f=e}static fromConfig(e,t){if(!G.has(t.dataType))throw new n(`Delta codec does not support data type: ${t.dataType}`);return new X(m(t.dataType))}encode(e){K(e.shape,e.stride);const t=e.data,n=new this.#f(t.length);n[0]=t[0];for(let e=1;e<t.length;e++)n[e]=t[e]-t[e-1];return{data:n,shape:e.shape,stride:e.stride}}decode(e){K(e.shape,e.stride);const t=e.data,n=new this.#f(t.length);n[0]=t[0];for(let e=1;e<t.length;e++)n[e]=n[e-1]+t[e];return{data:n,shape:e.shape,stride:e.stride}}}class Q{kind="bytes_to_bytes";static fromConfig(e){return new Q}encode=o("gzip");async decode(e){const t=await C(e,{format:"gzip"});return new Uint8Array(t)}}function H(e,t){return v(!Number.isNaN(t),"JsonCodec allow_nan is false but NaN was encountered during encoding."),v(t!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),v(t!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),t}function Z(e,t){return t instanceof Object&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t}class ee{configuration;kind="array_to_bytes";#h;#y;constructor(e={}){this.configuration=e;const{encoding:t="utf-8",skipkeys:n=!1,ensure_ascii:r=!0,check_circular:a=!0,allow_nan:s=!0,sort_keys:i=!0,indent:o,strict:c=!0}=e;let u=e.separators;u||(u=o?[", ",": "]:[",",":"]),this.#h={encoding:t,skipkeys:n,ensure_ascii:r,check_circular:a,allow_nan:s,indent:o,separators:u,sort_keys:i},this.#y={strict:c}}static fromConfig(e){return new ee(e)}encode(e){const{indent:t,encoding:n,ensure_ascii:r,check_circular:a,allow_nan:s,sort_keys:i}=this.#h;v("utf-8"===n,"JsonCodec does not yet support non-utf-8 encoding.");const o=[];v(a,"JsonCodec does not yet support skipping the check for circular references during encoding."),s||o.push(H),i&&o.push(Z);const c=Array.from(e.data);let u;c.push("|O"),c.push(e.shape),o.length&&(u=(e,t)=>{let n=t;for(let t of o)n=t(e,n);return n});let d=JSON.stringify(c,u,t);return r&&(d=d.replace(/[\u007F-\uFFFF]/g,e=>{const t=`0000${e.charCodeAt(0).toString(16)}`;return`\\u${t.substring(t.length-4)}`})),(new TextEncoder).encode(d)}decode(e){const{strict:t}=this.#y;v(t,"JsonCodec does not yet support non-strict decoding.");const n=p(e),r=n.pop();n.pop(),v(r,"0D not implemented for JsonCodec.");return{data:n,shape:r,stride:w(r,"C")}}}const te=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class ne{kind="array_to_array";#f;#p;#g;constructor(e,t,n){this.#p=e,this.#g=t,this.#f=n}static fromConfig(e,t){if(!te.has(t.dataType))throw new n(`scale_offset codec does not support data type: ${t.dataType}`);return new ne(U(t.dataType,e.scale??1),U(t.dataType,e.offset??0),m(t.dataType))}encode=o("scale_offset");decode(e){const t=e.data,n=new this.#f(t.length);for(let e=0;e<t.length;e++)n[e]=t[e]/this.#p+this.#g;return{data:n,shape:e.shape,stride:e.stride}}}class re{kind="bytes_to_bytes";#s;constructor(e,t){if(t){let e=new(m(t.dataType))(0);v("BYTES_PER_ELEMENT"in e,`Shuffle codec requires a fixed-size dtype, got "${t.dataType}"`),this.#s=e.BYTES_PER_ELEMENT}else this.#s=e.elementsize??4}static fromConfig(e,t){return new re(e,t)}encode(e){return function(e,t){let n=e.length,r=Math.floor(n/t),a=new Uint8Array(n);for(let n=0;n<t;n++)for(let s=0;s<r;s++)a[n*r+s]=e[s*t+n];return a}(e,this.#s)}decode(e){return function(e,t){let n=e.length,r=Math.floor(n/t),a=new Uint8Array(n);for(let n=0;n<t;n++)for(let s=0;s<r;s++)a[s*t+n]=e[n*r+s];return a}(e,this.#s)}}function ae(e){if(e instanceof d||e instanceof l||e instanceof f){return new Proxy(e,{get:(e,t)=>e.get(Number(t)),set:(e,t,n)=>(e.set(Number(t),n),!0)})}return e}function se(e,t){let n=function(e,t){let n;return n=e.data instanceof l||e.data instanceof f?new e.data.constructor(e.data.chars,e.data.length):new e.data.constructor(e.data.length),{data:n,shape:e.shape,stride:w(e.shape,t)}}(e,t),r=e.shape.length,a=e.shape.reduce((e,t)=>e*t,1),s=Array(r).fill(0),i=ae(e.data),o=ae(n.data);for(let t=0;t<a;t++){let t=0,a=0;for(let i=0;i<r;i++)t+=s[i]*e.stride[i],a+=s[i]*n.stride[i];o[a]=i[t],s[0]+=1;for(let t=0;t<r;t++)if(s[t]===e.shape[t]){if(t+1===r)break;s[t]=0,s[t+1]+=1}}return n}function ie(e,t){let n=function(e){return v(e.shape.length===e.stride.length,"Shape and stride must have the same length."),e.stride.map((e,t)=>({stride:e,index:t})).sort((e,t)=>t.stride-e.stride).map(e=>e.index)}(e);return v(n.length===t.length,"Orders must match"),n.every((e,n)=>e===t[n])}class oe{kind="array_to_array";#m;constructor(e,t){let n=e.order??"C",r=t.shape.length,a=new Array(r);if("C"===n)for(let e=0;e<r;++e)a[e]=e;else if("F"===n)for(let e=0;e<r;++e)a[e]=r-e-1;else{a=n;let e=new Array(r);a.forEach(t=>{v(!e[t],`Invalid permutation: ${JSON.stringify(n)}`),e[t]=!0})}this.#m=a}static fromConfig(e,t){return new oe(e,t)}encode(e){return ie(e,this.#m)?e:se(e,this.#m)}decode(e){return{data:e.data,shape:e.shape,stride:w(e.shape,this.#m)}}}class ce{kind="array_to_bytes";#i;#w;constructor(e){this.#i=e,this.#w=w(e,"C")}static fromConfig(e,t){return new ce(t.shape)}encode=o("vlen-utf8");decode(e){let t=new TextDecoder,n=new DataView(e.buffer),r=Array(n.getUint32(0,!0)),a=4;for(let s=0;s<r.length;s++){let i=n.getUint32(a,!0);a+=4,r[s]=t.decode(e.buffer.slice(a,a+i)),a+=i}return{data:r,shape:this.#i,stride:this.#w}}}class ue{kind="bytes_to_bytes";static fromConfig(e){return new ue}encode=o("zlib");async decode(e){const t=await C(e,{format:"deflate"});return new Uint8Array(t)}}const de=function(){let e=()=>import("numcodecs/blosc").then(e=>e.default),t=()=>import("./BVsLaBME.esm.js").then(e=>e.default),n=()=>import("./DpGLeScB.esm.js").then(e=>e.default),r=()=>Q,a=()=>ue;return(new Map).set("blosc",e).set("lz4",t).set("zstd",n).set("gzip",r).set("zlib",a).set("transpose",()=>oe).set("bytes",()=>M).set("crc32c",()=>q).set("vlen-utf8",()=>ce).set("json2",()=>ee).set("bitround",()=>c).set("cast_value",()=>D).set("scale_offset",()=>ne).set("numcodecs.blosc",e).set("numcodecs.lz4",t).set("numcodecs.zstd",n).set("numcodecs.gzip",r).set("numcodecs.zlib",a).set("numcodecs.vlen-utf8",()=>ce).set("numcodecs.shuffle",()=>re).set("numcodecs.delta",()=>X).set("numcodecs.bitround",()=>c).set("numcodecs.json2",()=>ee)}();function le(e){let t;function s(){return t||(t=async function(e){let t,a=e.codecs.map(async e=>{let t=await(de.get(e.name)?.());if(!t)throw new r(e.name);return{Codec:t,meta:e}}),s=[],i=[],o={...e};for await(let{Codec:e,meta:n}of a){let r=e.fromConfig(n.configuration,o);switch(r.kind){case"array_to_array":s.push({name:n.name,codec:r}),r.getEncodedMeta&&(o=r.getEncodedMeta(o));break;case"array_to_bytes":t={name:n.name,codec:r};break;default:i.push({name:n.name,codec:r})}}if(!t){if("v2:object"===(c=o).dataType||"string"===c.dataType)throw new n(`Cannot encode ${o.dataType} to bytes without a codec`);t={name:"bytes",codec:M.fromConfig({endian:"little"},o)}}var c;return{arrayToArray:s,arrayToBytes:t,bytesToBytes:i}}(e)),t}async function i(e,t,n){try{return await n()}catch(n){throw new a({direction:e,codec:t,cause:n})}}return{async encode(e){let t=await s();for(const{name:n,codec:r}of t.arrayToArray)e=await i("encode",n,()=>r.encode(e));let n=await i("encode",t.arrayToBytes.name,()=>t.arrayToBytes.codec.encode(e));for(const{name:e,codec:r}of t.bytesToBytes)n=await i("encode",e,()=>r.encode(n));return n},async decode(e){let t=await s();for(let n=t.bytesToBytes.length-1;n>=0;n--){const{name:r,codec:a}=t.bytesToBytes[n];e=await i("decode",r,()=>a.decode(e))}let n=await i("decode",t.arrayToBytes.name,()=>t.arrayToBytes.codec.decode(e));for(let e=t.arrayToArray.length-1;e>=0;e--){const{name:r,codec:a}=t.arrayToArray[e];n=await i("decode",r,()=>a.decode(n))}return n},async computeEncodedSize(e){let t=await s(),n=fe(t.arrayToBytes.name,t.arrayToBytes.codec,e);for(const{name:e,codec:r}of t.bytesToBytes)n=fe(e,r,n);return n}}}function fe(e,t,r){if(!t.computeEncodedSize)throw new n(`Codec "${e}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return t.computeEncodedSize(r)}const he=18446744073709551615n;function ye(e,t,n,r){if(!e.store.getRange)throw new i("sharding requires a store with getRange");let a=e.store.getRange.bind(e.store),s=t.map((e,t)=>e/r.chunk_shape[t]),o=le({dataType:"uint64",shape:[...s,2],codecs:r.index_codecs,fillValue:null}),c=16*s.reduce((e,t)=>e*t,1),u={};return async(t,r)=>{let i=t.map((e,t)=>Math.floor(e/s[t])),d=e.resolve(n(i)).path;d in u||(u[d]=(async()=>{let e=await o.computeEncodedSize(c),t=await a(d,{suffixLength:e},r);return t?await o.decode(t):null})().catch(e=>{throw delete u[d],e}));let l=await u[d];if(null===l)return;let{data:f,shape:h,stride:y}=l,p=t.map((e,t)=>e%h[t]).reduce((e,t,n)=>e+t*y[n],0),g=f[p],m=f[p+1];return g!==he||m!==he?a(d,{offset:Number(g),length:Number(m)},r):void 0}}class pe{store;path;constructor(e,t="/"){this.store=e,this.path=t}resolve(e){let t=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new pe(this.store,decodeURIComponent(new URL(e,t).pathname))}}function ge(e){return new pe(e??new Map)}class me extends pe{kind="group";#b;constructor(e,t,n){super(e,t),this.#b=n}get attrs(){return this.#b.attributes}}function we(e){const t=e.find(e=>"transpose"===e.name);return t?.configuration?.order??"C"}function be(e){return(t,n)=>{let r=globalThis.Array.isArray(e)&&n?function(e,t){let n=new Map(t.map((e,t)=>[e,t]));return e.filter(e=>n.has(e)).map(e=>n.get(e))}(e,n):e;return w(t,r)}}const _e=Symbol("zarrita.context");let Ee=class extends pe{kind="array";#b;[_e];constructor(e,t,n){super(e,t),this.#b={...n,fill_value:A(n)},this[_e]=function(e,t){let{configuration:n}=t.codecs.find(k)??{},r={encodeChunkKey:b(t.chunk_key_encoding),TypedArray:m(t.data_type),fillValue:t.fill_value};if(n){let a=we(n.codecs);return{...r,kind:"sharded",chunkShape:n.chunk_shape,codec:le({dataType:t.data_type,shape:n.chunk_shape,codecs:n.codecs,fillValue:t.fill_value}),getStrides:be(a),getChunkBytes:ye(e,t.chunk_grid.configuration.chunk_shape,r.encodeChunkKey,n)}}let a=we(t.codecs);return{...r,kind:"regular",chunkShape:t.chunk_grid.configuration.chunk_shape,codec:le({dataType:t.data_type,shape:t.chunk_grid.configuration.chunk_shape,codecs:t.codecs,fillValue:t.fill_value}),getStrides:be(a),async getChunkBytes(t,n){let a=r.encodeChunkKey(t),s=e.resolve(a).path;return e.store.get(s,n)}}}(this,this.#b)}get attrs(){return this.#b.attributes}get dimensionNames(){return this.#b.dimension_names}get fillValue(){return this.#b.fill_value}get shape(){return this.#b.shape}get chunks(){return this[_e].chunkShape}get dtype(){return this.#b.data_type}async getChunk(e,t,n){n?.useSharedArrayBuffer&&h();let r=this[_e],a=await r.getChunkBytes(e,t);if(!a){let e,t=r.chunkShape.reduce((e,t)=>e*t,1);if(n?.useSharedArrayBuffer){let n=new r.TypedArray(0);if("BYTES_PER_ELEMENT"in n){let a=y(t*n.BYTES_PER_ELEMENT);e=new r.TypedArray(a,0,t)}else console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),e=new r.TypedArray(t)}else e=new r.TypedArray(t);return e.fill(r.fillValue),{data:e,shape:r.chunkShape,stride:r.getStrides(r.chunkShape)}}return r.codec.decode(a)}is(e){return T(this.dtype,e)}};function Te(e,...t){return function(e,t){let n=e;for(let e of t)n=n instanceof Promise?n.then(t=>e(t)):e(n);return n}(e,t)}async function ke(e){let t=e.store.arrayExtensions;if(!t?.length)return e;let n=Te;return await n(e,...t)}let Ae=function(){let e=new WeakMap;function t(t){let n=e.get(t)??{v2:0,v3:0};return e.set(t,n),n}return{increment(e,n){t(e)[n]+=1},versionMax(e){let n=t(e);return n.v3>n.v2?"v3":"v2"}}}();async function Se(e,r,a){let{path:s}=e.resolve(".zarray"),i=await e.store.get(s,{signal:a});if(!i)throw new t("v2 array",{path:s});return Ae.increment(e.store,"v2"),ke(new Ee(e.store,e.path,function(e,t={}){let r,a=[],s=_(e.dtype);"F"===e.order&&a.push({name:"transpose",configuration:{order:"F"}});for(let t of e.filters??[]){if("fixedscaleoffset"===t.id||"numcodecs.fixedscaleoffset"===t.id){if(!E(t))throw new n(`Invalid fixedscaleoffset filter: ${JSON.stringify(t)}`);a.push({name:"scale_offset",configuration:{scale:t.scale,offset:t.offset}});let r=t.astype??t.dtype;if(void 0!==r&&r!==e.dtype){let e=_(r).dataType;if(!T(e,"number")&&!T(e,"bigint"))throw new n(`fixedscaleoffset astype must be a numeric data type, got ${r}`);a.push({name:"cast_value",configuration:{data_type:e,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:r,...s}=t;a.push({name:`numcodecs.${r}`,configuration:s})}if("endian"in s&&"big"===s.endian&&a.push({name:"bytes",configuration:{endian:"big"}}),e.compressor){let{id:t,...n}=e.compressor;a.push({name:`numcodecs.${t}`,configuration:n})}return globalThis.Array.isArray(t._ARRAY_DIMENSIONS)&&(r=t._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:e.shape,data_type:s.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:e.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:e.dimension_separator??"."}},codecs:a,fill_value:e.fill_value,dimension_names:r,attributes:t}}(p(i),r)))}async function ve(e,n,r){let{path:a}=e.resolve(".zgroup"),s=await e.store.get(a,{signal:r});if(!s)throw new t("v2 group",{path:a});return Ae.increment(e.store,"v2"),new me(e.store,e.path,function(e,t={}){return{zarr_format:3,node_type:"group",attributes:t}}(p(s),n))}async function Ce(e,r={}){let a="store"in e?e.store:e,s=Ae.versionMax(a),i="v2"===s?Ce.v2:Ce.v3,o="v2"===s?Ce.v3:Ce.v2;return i(e,r).catch(a=>(S(a,t,n),o(e,r)))}function Ne(e){if(null==e)return null;if("bigint"==typeof e){if(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER)throw new s(`Cannot safely convert ${e} to a number. Value exceeds Number.MAX_SAFE_INTEGER.`);return Number(e)}return e}function Be(e,t,n=null){return void 0===t&&(t=e,e=null),{start:Ne(e),stop:Ne(t),step:Ne(n)}}function Me(e,t){e.length>t.length&&function(e,t){throw new s(`too many indicies for array; expected ${t.length}, got ${e.length}`)}(e,t)}function Le(e,t){return(e=Math.trunc(e))<0&&(e=t+e),(e>=t||e<0)&&function(e){throw new s(`index out of bounds for dimension with length ${e}`)}(t),e}Ce.v2=async function(e,r={}){let a="store"in e?e:new pe(e),{signal:s}=r,i={};return(r.attrs??!0)&&(i=await async function(e,t){let n=await e.store.get(e.resolve(".zattrs").path,{signal:t});return n?p(n):{}}(a,s)),s?.throwIfAborted(),"array"===r.kind?Se(a,i,s):"group"===r.kind?ve(a,i,s):Se(a,i,s).catch(e=>(S(e,t,n),ve(a,i,s)))},Ce.v3=async function(e,n={}){let r="store"in e?e:new pe(e),a=await async function(e,n){let{store:r,path:a}=e.resolve("zarr.json"),s=await e.store.get(a,{signal:n});if(!s)throw new t("v3 array or group",{path:a});let i=p(s);return"array"===i.node_type&&(i.fill_value=A(i)),"array"===i.node_type?ke(new Ee(r,e.path,i)):new me(r,e.path,i)}(r,n.signal);if(Ae.increment(r.store,"v3"),void 0===n.kind)return a;if("array"===n.kind&&a instanceof Ee)return a;if("group"===n.kind&&a instanceof me)return a;let s=a instanceof Ee?"array":"group";throw new t(`${n.kind} at ${r.path}`,{path:r.path,found:s})};class xe{dimSel;dimLen;dimChunkLen;nitems;constructor({dimSel:e,dimLen:t,dimChunkLen:n}){e=Le(e,t),this.dimSel=e,this.dimLen=t,this.dimChunkLen=n,this.nitems=1}*[Symbol.iterator](){const e=Math.floor(this.dimSel/this.dimChunkLen),t=e*this.dimChunkLen,n=this.dimSel-t;yield{dimChunkIx:e,dimChunkSel:n}}}class Ie{start;stop;step;dimLen;dimChunkLen;nitems;nchunks;constructor({dimSel:e,dimLen:t,dimChunkLen:n}){const[r,a,i]=function({start:e,stop:t,step:n},r){if(0===n)throw new s("slice step cannot be zero");const a=(n=n??1)<0,[i,o]=a?[-1,r-1]:[0,r];return null===e?e=a?o:i:e<0?(e+=r)<i&&(e=i):e>o&&(e=o),null===t?t=a?i:o:t<0?(t+=r)<i&&(t=i):t>o&&(t=o),[e,t,n]}(e,t);this.start=r,this.stop=a,this.step=i,this.step<1&&function(){throw new s("only slices with step >= 1 are supported")}(),this.dimLen=t,this.dimChunkLen=n,this.nitems=Math.max(0,Math.ceil((this.stop-this.start)/this.step)),this.nchunks=Math.ceil(this.dimLen/this.dimChunkLen)}*[Symbol.iterator](){const e=Math.floor(this.start/this.dimChunkLen),t=Math.ceil(this.stop/this.dimChunkLen);for(const n of function*(e,t,n=1){void 0===t&&(t=e,e=0);for(let r=e;r<t;r+=n)yield r}(e,t)){const e=n*this.dimChunkLen,t=Math.min(this.dimLen,(n+1)*this.dimChunkLen),r=t-e;let a=0,s=0;if(this.start<e){const t=(e-this.start)%this.step;t&&(s+=this.step-t),a=Math.ceil((e-this.start)/this.step)}else s=this.start-e;const i=this.stop>t?r:this.stop-e,o=[s,i,this.step],c=[a,a+Math.ceil((i-s)/this.step),1];yield{dimChunkIx:n,dimChunkSel:o,dimOutSel:c}}}}class $e{dimIndexers;shape;outputAxes;constructor({selection:e,shape:t,chunkShape:n}){this.dimIndexers=function(e,t){let n=[];return null===e?n=t.map(e=>Be(null)):Array.isArray(e)&&(n=e.map(e=>e??Be(null))),Me(n,t),n}(e,t).map((e,r)=>new("number"==typeof e?xe:Ie)({dimSel:e,dimLen:t[r],dimChunkLen:n[r]})),this.shape=this.dimIndexers.filter(e=>e instanceof Ie).map(e=>e.nitems),this.outputAxes=this.dimIndexers.map((e,t)=>({ixr:e,axis:t})).filter(({ixr:e})=>e instanceof Ie).map(({axis:e})=>e)}*[Symbol.iterator](){for(const e of function*(...e){if(0===e.length)return;const t=e.map(e=>e[Symbol.iterator]()),n=t.map(e=>e.next());if(n.some(e=>e.done))throw new Error("Input contains an empty iterator.");for(let r=0;;){if(n[r].done){if(t[r]=e[r][Symbol.iterator](),n[r]=t[r].next(),++r>=t.length)return}else yield n.map(({value:e})=>e),r=0;n[r]=t[r].next()}}(...this.dimIndexers)){const t=e.map(e=>e.dimChunkIx),n=e.map(e=>"dimOutSel"in e?{from:e.dimChunkSel,to:e.dimOutSel}:{from:e.dimChunkSel,to:null});yield{chunkCoords:t,mapping:n}}}}function Ue(e,t){return"get"in e?e.get(t):e[t]}async function Pe(e,t,n,r){n.useSharedArrayBuffer&&h();let a=function(e){let t=e.signal,n=e.opts?.signal;return t&&n?AbortSignal.any([t,n]):t??n}(n),s=e[_e];let i=new $e({selection:t,shape:e.shape,chunkShape:e.chunks});if(0===e.shape.length){let{data:t}=await e.getChunk([],{signal:a},{useSharedArrayBuffer:n.useSharedArrayBuffer});return Ue(t,0)}let o,c=i.shape.reduce((e,t)=>e*t,1);if(n.useSharedArrayBuffer){let e=new s.TypedArray(0);if("BYTES_PER_ELEMENT"in e){let t=y(c*e.BYTES_PER_ELEMENT);o=new s.TypedArray(t,0,c)}else console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),o=new s.TypedArray(c)}else o=new s.TypedArray(c);let u=r.prepare(o,i.shape,s.getStrides(i.shape,i.outputAxes)),d=n.createQueue?.()??function(){const e=[];return{add:t=>e.push(t()),onIdle:()=>Promise.all(e)}}();for(const{chunkCoords:t,mapping:s}of i)d.add(async()=>{a?.throwIfAborted();let{data:i,shape:o,stride:c}=await e.getChunk(t,{signal:a},{useSharedArrayBuffer:n.useSharedArrayBuffer}),d=r.prepare(i,o,c);r.setFromChunk(u,d,s)});return await d.onIdle(),0===i.shape.length?Ue(u.data,0):u}function Oe(e,t=0,n){let r=n??e.length-t;return{length:r,subarray:(n,a=r)=>Oe(e,t+n,a-n),set(n,r=0){for(let a=0;a<n.length;a++)e[t+r+a]=n.get(a)},get:n=>e[t+n]}}function Re(e){return globalThis.Array.isArray(e.data)?{data:Oe(e.data),stride:e.stride,bytesPerElement:1}:{data:new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength),stride:e.stride,bytesPerElement:e.data.BYTES_PER_ELEMENT}}const ze={prepare:(e,t,n)=>({data:e,shape:t,stride:n}),setScalar(e,t,n){let r=Re(e);Ve(r,t,function(e,t){if(globalThis.Array.isArray(e.data))return Oe([t]);let n=new(function(e){return"chars"in e?e.constructor.bind(null,e.chars):e.constructor}(e.data))([t]);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}(e,n),r.bytesPerElement)},setFromChunk(e,t,n){let r=Re(e);je(r,Re(t),r.bytesPerElement,n)}};async function Fe(e,t=null,n={}){return Pe(e,t,n,ze)}function Ye(e,t,n){return n<0&&t<e?Math.floor((e-t-1)/-n)+1:e<t?Math.floor((t-e-1)/n)+1:0}function Ve(e,t,n,r){if(0===t.length)return void e.data.set(n,0);const[a,...s]=t,[i,...o]=e.stride;if("number"==typeof a){return void Ve({data:e.data.subarray(i*a*r),stride:o},s,n,r)}const[c,u,d]=a,l=Ye(c,u,d);if(0!==s.length)for(let t=0;t<l;t++){Ve({data:e.data.subarray(i*(c+d*t)*r),stride:o},s,n,r)}else for(let t=0;t<l;t++)e.data.set(n,i*(c+d*t)*r)}function je(e,t,n,r){const a=function(e,t,n){if(e.length!==t.length||e.length!==n.length)return null;let r=1,a=0,s=0;for(let i=e.length-1;i>=0;i--){const o=e[i];if(null===o.from||null===o.to)return null;if(t[i]!==r||n[i]!==r)return null;const[c,u,d]=o.to,[l,,f]=o.from;if(1!==d||1!==f)return null;a+=r*c,s+=r*l,r*=Ye(c,u,d)}return{size:r,destOffset:a,srcOffset:s}}(r,e.stride,t.stride);if(null!==a){const r=a.srcOffset*n;return void e.data.set(t.data.subarray(r,r+a.size*n),a.destOffset*n)}const[s,...i]=r,[o,...c]=e.stride,[u,...d]=t.stride;if(null===s.from)return 0===i.length?void e.data.set(t.data.subarray(0,n),o*s.to*n):void je({data:e.data.subarray(o*s.to*n),stride:c},t,n,i);if(null===s.to){if(0===i.length){let r=u*s.from*n;return void e.data.set(t.data.subarray(r,r+n),0)}return void je(e,{data:t.data.subarray(u*s.from*n),stride:d},n,i)}const[l,f,h]=s.to,[y,p,g]=s.from,m=Ye(l,f,h);if(0!==i.length)for(let r=0;r<m;r++)je({data:e.data.subarray(o*(l+r*h)*n),stride:c},{data:t.data.subarray(u*(y+r*g)*n),stride:d},n,i);else for(let r=0;r<m;r++){let a=u*(y+g*r)*n;e.data.set(t.data.subarray(a,a+n),o*(l+h*r)*n)}}export{Fe as g,Ce as o,ge as r,Be as s};
@@ -0,0 +1 @@
1
+ var e={fromConfig(){throw new Error("riverforecastsystem excludes numcodecs/lz4: the v3 stores are written with blosc(zstd, shuffle) and blosc is the only numcodecs wasm build bundled. A store compressed with this codec cannot be read by this build.")}};export{e as default};
@@ -0,0 +1 @@
1
+ const e="https://cdn.apps.geoglows.org/rfs-v3-sample-data",r={v3Base:""},s=e=>"string"==typeof e?e.trim().replace(/\/+$/,""):"",a=({v3Base:e}={})=>{void 0!==e&&(r.v3Base=s(e))},t=()=>r.v3Base||s(e),o=()=>({v3Base:t()}),i=({group:e}={})=>`${t()}/hydrography/group=${e}`,l=({group:e="0"}={})=>`${i({group:e})}/metadata.zarr`,d=["hourly","daily","monthly","yearly"],n=({resolution:e="hourly"}={})=>{if(!d.includes(e))throw new Error(`Invalid resolution: ${e}. Must be one of ${d.join(", ")}.`);return`${t()}/retrospective/${e}.zarr`},p=()=>`${t()}/retrospective/return-periods.zarr`,u=()=>`${t()}/retrospective/maximums.zarr`,$=({date:e})=>`${t()}/forecasts15/${(e=>{if(!/^\d{4}-?\d{2}-?\d{2}$/.test(e))throw new Error(`Invalid date format: ${e}. Must be YYYYMMDD or YYYY-MM-DD.`);const r=e.replace(/-/g,"");return`year=${r.slice(0,4)}/month=${r.slice(4,6)}/day=${r.slice(6,8)}`})(e)}`,m=({date:e})=>`${$({date:e})}/discharge.zarr`,f=()=>`${t()}/flood-maps`,y=()=>`${f()}/zarr.json`,c=()=>`${f()}/network_graph_fim.json`,h=Object.freeze(["timeseries","max-flow","time-to-peak","below-q95"]);var v=Object.freeze({__proto__:null,floodMapsBase:f,floodMapsManifest:()=>`${f()}/manifest.json`,floodMapsRoot:y,floodMapsTileBoundaries:()=>`${f()}/tile_boundaries.pmtiles`,forecastDir:$,forecastZarr:m,hydrographyGroup:i,hydrographyMetadataZarr:l,maximumsZarr:u,retrospectiveZarr:n,returnPeriodsZarr:p,riverNetworkGraph:c,streamsPmtiles:()=>`${i({group:"0"})}/streams.pmtiles`,streamsStyles:({date:e,styleset:r})=>{if(!r)throw new Error("streamsStyles requires a styleset, consult stylesets for valid values");if(!h.includes(r))throw new Error(`Invalid styleset: ${r}. Must be one of ${h.join(", ")}.`);return`${$({date:e})}/maps/${r}/styles`},stylesets:h});export{p as a,f as b,a as c,y as d,c as e,m as f,o as g,l as h,u as m,n as r,v as u};
@@ -0,0 +1 @@
1
+ import{c as e,g as r,u as o}from"./BcUKIvbV.esm.js";var s=Object.freeze({__proto__:null,configure:e,getConfig:r,urls:o});export{s as v};
@@ -0,0 +1 @@
1
+ import{F as r}from"./pq2-5-mb.esm.js";import{o as a,g as e}from"./B3OxysOz.esm.js";const i=async({zarrUrl:r,riverId:a,idx:e,idVariable:i})=>{if(void 0===e&&void 0===a)throw new Error("Either 'riverId' or 'idx' must be provided.");return void 0===e&&(e=await s({zarrUrl:r,variable:i,value:a})),e},l=async({zarrUrl:i,variable:l,selection:t=null})=>{const s=new r(`${i}/${l}`),o=await a.v2(s);return[...(await e(o,t)).data]},t=async({zarrUrl:r,variable:a})=>await l({zarrUrl:r,variable:a,selection:[null]}),s=async({zarrUrl:r,variable:a,value:e})=>(await t({zarrUrl:r,variable:a})).indexOf(e),o=async({zarrUrl:i})=>{const l=new r(`${i}/time`),t=await a.v2(l),s=await e(t,[null]),o=t.attrs.units,n=new Date(o.split("since")[1].trim()),d={seconds:1,minutes:60,hours:3600,days:86400}[o.split("since")[0].trim()],c=n.getTime();return[...s.data].map(r=>new Date(c+Number(r)*d*1e3))};async function n({baseUrl:r,date:a,riverId:e,idx:t}){if(!/^\d{8}$/.test(a))throw new Error(`Invalid date format: ${a}. Must be YYYYMMDD.`);const s=`${r||"http://geoglows-v2-forecasts.s3-website-us-west-2.amazonaws.com"}/${a}00.zarr`,n=await i({zarrUrl:s,riverId:e,idx:t,idVariable:"rivid"});let[d,c]=await Promise.all([o({zarrUrl:s}),l({zarrUrl:s,variable:"Qout",selection:[{start:0,stop:51,step:1},null,n]})]);const m=c.slice(0,d.length).map((r,a)=>isNaN(r)?-1:a).filter(r=>-1!==r),u=Array(51).fill(0).map((r,a)=>a*d.length);c=u.map(r=>c.slice(r,r+d.length)).map(r=>m.map(a=>r[a])),d=m.map(r=>d[r]);const v=(r=>{const a=r.length,e=r[0].length;let i={min:Array(e).fill(0),p20:Array(e).fill(0),p25:Array(e).fill(0),median:Array(e).fill(0),p75:Array(e).fill(0),p80:Array(e).fill(0),max:Array(e).fill(0),average:Array(e).fill(0)};return Array(e).fill(0).forEach((e,l)=>{const t=r.map(r=>r[l]).sort((r,a)=>r-a);i.min[l]=t[0],i.p20[l]=t[Math.floor(.2*a)],i.p25[l]=t[Math.floor(.25*a)],i.median[l]=t[Math.floor(.5*a)],i.p75[l]=t[Math.floor(.75*a)],i.p80[l]=t[Math.floor(.8*a)],i.max[l]=t[a-1],i.average[l]=t.reduce((r,a)=>r+a,0)/a}),i})(c);return{time:d,discharge:c,stats:v}}async function d({baseUrl:r,resolution:a="daily",riverId:e,idx:t}){if(!["hourly","daily","monthly","yearly"].includes(a))throw new Error(`Invalid resolution: ${a}. Must be one of 'hourly', 'daily', 'monthly', 'yearly'.`);["monthly","yearly"].includes(a)&&(a=`${a}-timeseries`);const s=`${r||"http://geoglows-v2.s3-us-west-2.amazonaws.com"}/retrospective/${a}.zarr`,n=await i({zarrUrl:s,riverId:e,idx:t,idVariable:"river_id"}),[d,c]=await Promise.all([o({zarrUrl:s}),l({zarrUrl:s,variable:"Q",selection:[null,n]})]);return{time:d,discharge:c}}async function c({baseUrl:r,riverId:a,idx:e}){const s=`${r||"http://geoglows-v2.s3-us-west-2.amazonaws.com"}/retrospective/return-periods.zarr`,o=await i({zarrUrl:s,riverId:a,idx:e,idVariable:"river_id"}),[n,d]=await Promise.all([t({zarrUrl:s,variable:"return_period"}),l({zarrUrl:s,variable:"gumbel",selection:[null,o]})]);return n.reduce((r,a,e)=>(r[Number(a)]=Number(d[e]),r),{})}var m=Object.freeze({__proto__:null,forecast:n,retrospective:d,returnPeriods:c});export{c as a,n as f,d as r,m as v};
@@ -0,0 +1 @@
1
+ var e={fromConfig(){throw new Error("riverforecastsystem excludes numcodecs/zstd: the v3 stores are written with blosc(zstd, shuffle) and blosc is the only numcodecs wasm build bundled. A store compressed with this codec cannot be read by this build.")}};export{e as default};
@@ -0,0 +1 @@
1
+ var a={"chart.cumulativeVolume":"Volumen anual acumulado","chart.dailyTimeseries":"Caudal diario retrospectivo · río {riverId}","chart.flowDurationCurve":"Curva de duración de caudales","chart.forecastHydrograph":"Pronóstico por conjuntos a 15 días · río {riverId}","chart.monthlyStatus":"Estado mensual del caudal","chart.rasterHydrograph":"Hidrograma ráster","chart.yearlyPeaks":"Caudal máximo anual","chart.yearlyVolumes":"Volúmenes anuales","axis.cumulativeVolume":"Volumen acumulado (Mm³)","axis.datetime":"Fecha y hora (UTC+00:00)","axis.dayOfPeak":"Día del pico","axis.dayOfYear":"Día del año","axis.discharge":"Caudal (m³/s)","axis.flow":"Caudal (m³/s)","axis.month":"Mes","axis.percentile":"Percentil (%)","axis.volume":"Volumen (m³ × 10⁶)","axis.year":"Año","tooltip.day":"día","series.allMonths":"Todos los meses","series.annualVolume":"Volumen anual","series.dailyMean":"Caudal medio diario","series.fiveYearAverage":"Media de 5 años","series.monthlyAverage":"Media mensual","series.ensembleMedian":"Mediana del conjunto","series.iqr":"RIC (25–75 %)","series.medianDay":"Día mediano","series.range":"Rango (mín–máx)","series.temporalOutlier":"Valor atípico temporal","label.returnPeriodYears":"{n} años","control.all":"Todo","control.resetZoom":"Restablecer zoom","control.yearsShort":"{n} a","control.zoomHint":"arrastra un recuadro para ampliar · mayús+arrastrar para desplazar",months:["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"],status:["Alto","Sobre lo normal","Normal","Bajo lo normal","Bajo"]};export{a as default};
@@ -0,0 +1 @@
1
+ import{g as r,o as a}from"./B3OxysOz.esm.js";import{F as e}from"./pq2-5-mb.esm.js";const i="riverId",t="member",s="Q",n=async({zarrUrl:r,variable:i})=>{const t=new e(`${r}/${i}`);return await a.v3(t,{kind:"array"})},l=r=>Math.round(100*r)/100,o=async({zarrUrl:r,riverIndex:a,riverId:e})=>{if(void 0===a&&void 0===e)throw new Error("Either 'riverIndex' or 'riverId' must be provided.");return void 0===a?await m({zarrUrl:r,variable:i,value:e}):a},d=async({zarrUrl:r,riverIds:a})=>{const e=await u({zarrUrl:r,variable:i}),t=new Map;return e.forEach((r,a)=>t.set(Number(r),a)),a.map(r=>t.get(Number(r))??-1)},v=async({zarrUrl:a,variable:e,selection:i=null,round:t=!0})=>{const s=await n({zarrUrl:a,variable:e}),o=((r,a)=>{const e=a?.scale_factor,i=a?.add_offset,t=a?._FillValue;return void 0===e&&void 0===i&&void 0===t?r:r.map(r=>{const a=Number(r);return void 0!==t&&a===Number(t)?NaN:a*(e??1)+(i??0)})})([...(await r(s,i)).data],s.attrs);return t?(r=>r.map(l))(o):o},u=async({zarrUrl:r,variable:a})=>await v({zarrUrl:r,variable:a,selection:[null],round:!1}),m=async({zarrUrl:r,variable:a,value:e})=>(await u({zarrUrl:r,variable:a})).indexOf(e),c=async({zarrUrl:a})=>{const e=await n({zarrUrl:a,variable:"time"}),i=await r(e,[null]),t=e.attrs.units,s=new Date(t.split("since")[1].trim()),l={seconds:1,minutes:60,hours:3600,days:86400}[t.split("since")[0].trim()],o=s.getTime();return[...i.data].map(r=>new Date(o+Number(r)*l*1e3))};export{u as a,d as b,l as c,s as d,v as f,c as g,t as m,n as o,o as r};
@@ -0,0 +1 @@
1
+ function e(e,t){const s="string"==typeof e?new URL(e):e;s.pathname.endsWith("/")||(s.pathname+="/");const r=new URL(t.slice(1),s);return r.search=s.search,r}async function t(e){if(404!==e.status){if(200===e.status||206===e.status)return new Uint8Array(await e.arrayBuffer());throw new Error(`Unexpected response status ${e.status} ${e.statusText}`)}}class s{url;#e;#t;#s;constructor(e,t={}){this.url=e,this.#e=t.fetch??(e=>fetch(e)),this.#t=t.overrides??{},this.#s=t.useSuffixRequest??!1}#r(e,t){return new Request(e,(s=this.#t,r=t,{...s,...r,headers:{...s.headers,...r.headers}}));var s,r}async get(s,r={}){let i=e(this.url,s).href,h=this.#r(i,r);return t(await this.#e(h))}async getRange(s,r,i={}){let h,u=e(this.url,s);if("suffixLength"in r)h=await this.#i(u,r.suffixLength,i);else{let e={...i,headers:{...i.headers,Range:`bytes=${r.offset}-${r.offset+r.length-1}`}},t=this.#r(u,e);h=await this.#e(t)}return t(h)}async#i(e,t,s){if(this.#s){let r={...s,headers:{...s.headers,Range:`bytes=-${t}`}};return this.#e(this.#r(e,r))}let r=this.#r(e,{...s,method:"HEAD"}),i=await this.#e(r);if(!i.ok)return i;let h=i.headers.get("Content-Length"),u=Number(h),a=u-t,f={...s,headers:{...s.headers,Range:`bytes=${a}-${u-1}`}};return this.#e(this.#r(e,f))}}export{s as F};
@@ -0,0 +1 @@
1
+ var e={"chart.cumulativeVolume":"Volume annuel cumulé","chart.dailyTimeseries":"Débit journalier rétrospectif · rivière {riverId}","chart.flowDurationCurve":"Courbe des débits classés","chart.forecastHydrograph":"Prévision d'ensemble à 15 jours · rivière {riverId}","chart.monthlyStatus":"État mensuel du débit","chart.rasterHydrograph":"Hydrogramme raster","chart.yearlyPeaks":"Débit de pointe annuel","chart.yearlyVolumes":"Volumes annuels","axis.cumulativeVolume":"Volume cumulé (Mm³)","axis.datetime":"Date et heure (UTC+00:00)","axis.dayOfPeak":"Jour du pic","axis.dayOfYear":"Jour de l'année","axis.discharge":"Débit (m³/s)","axis.flow":"Débit (m³/s)","axis.month":"Mois","axis.percentile":"Centile (%)","axis.volume":"Volume (m³ × 10⁶)","axis.year":"Année","tooltip.day":"jour","series.allMonths":"Tous les mois","series.annualVolume":"Volume annuel","series.dailyMean":"Débit moyen journalier","series.fiveYearAverage":"Moyenne sur 5 ans","series.monthlyAverage":"Moyenne mensuelle","series.ensembleMedian":"Médiane d'ensemble","series.iqr":"EIQ (25–75 %)","series.medianDay":"Jour médian","series.range":"Plage (min–max)","series.temporalOutlier":"Valeur aberrante temporelle","label.returnPeriodYears":"{n} ans","control.all":"Tout","control.resetZoom":"Réinitialiser le zoom","control.yearsShort":"{n} a","control.zoomHint":"glisser un cadre pour zoomer · maj+glisser pour déplacer",months:["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],status:["Élevé","Au-dessus de la normale","Normale","En dessous de la normale","Faible"]};export{e as default};
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- function t(t,e,r,n={}){return void 0!==e&&void 0!==r&&(n={...n,headers:{...n.headers,Range:`bytes=${e}-${e+r-1}`}}),fetch(t,n)}function e(t,e){const r="string"==typeof t?new URL(t):t;r.pathname.endsWith("/")||(r.pathname+="/");const n=new URL(e.slice(1),r);return n.search=r.search,n}async function r(t){if(404!==t.status){if(200===t.status||206===t.status)return new Uint8Array(await t.arrayBuffer());throw new Error(`Unexpected response status ${t.status} ${t.statusText}`)}}class n{url;#t;#e;constructor(t,e={}){this.url=t,this.#t=e.overrides??{},this.#e=e.useSuffixRequest??!1}#r(t){return e=this.#t,r=t,{...e,...r,headers:{...e.headers,...r.headers}};var e,r}async get(t,n={}){let a=e(this.url,t).href;return r(await fetch(a,this.#r(n)))}async getRange(n,a,s={}){let i,o=e(this.url,n),c=this.#r(s);return i="suffixLength"in a?await async function(e,r,n,a){if(a)return fetch(e,{...n,headers:{...n.headers,Range:`bytes=-${r}`}});let s=await fetch(e,{...n,method:"HEAD"});if(!s.ok)return s;let i=s.headers.get("Content-Length"),o=Number(i);return t(e,o-r,o,n)}(o,a.suffixLength,c,this.#e):await t(o,a.offset,a.length,c),r(i)}}class a{#n;constructor(t,e,r){"number"==typeof t?this.#n=new Uint8Array(t):t instanceof ArrayBuffer?this.#n=new Uint8Array(t,e,r):this.#n=new Uint8Array(Array.from(t,t=>t?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#n.byteOffset}get byteLength(){return this.#n.byteLength}get buffer(){return this.#n.buffer}get length(){return this.#n.length}get(t){let e=this.#n[t];return"number"==typeof e?0!==e:e}set(t,e){this.#n[t]=e?1:0}fill(t){this.#n.fill(t?1:0)}*[Symbol.iterator](){for(let t=0;t<this.length;t++)yield this.get(t)}}class s{_data;chars;#a;constructor(t,e,r,n){if(this.chars=t,this.#a=new TextEncoder,"number"==typeof e)this._data=new Uint8Array(e*t);else if(e instanceof ArrayBuffer)n&&(n*=t),this._data=new Uint8Array(e,r,n);else{let r=Array.from(e);this._data=new Uint8Array(r.length*t);for(let t=0;t<r.length;t++)this.set(t,r[t])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(t){const e=new Uint8Array(this.buffer,this.byteOffset+this.chars*t,this.chars);return(new TextDecoder).decode(e).replace(/\x00/g,"")}set(t,e){const r=new Uint8Array(this.buffer,this.byteOffset+this.chars*t,this.chars);r.fill(0),r.set(this.#a.encode(e))}fill(t){const e=this.#a.encode(t);for(let t=0;t<this.length;t++)this._data.set(e,t*this.chars)}*[Symbol.iterator](){for(let t=0;t<this.length;t++)yield this.get(t)}}class i{#s;chars;constructor(t,e,r,n){if(this.chars=t,"number"==typeof e)this.#s=new Int32Array(e*t);else if(e instanceof ArrayBuffer)n&&(n*=t),this.#s=new Int32Array(e,r,n);else{const r=e,n=new i(t,1);this.#s=new Int32Array(function*(){for(let t of r)n.set(0,t),yield*n.#s}())}}get BYTES_PER_ELEMENT(){return this.#s.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#s.byteLength}get byteOffset(){return this.#s.byteOffset}get buffer(){return this.#s.buffer}get length(){return this.#s.length/this.chars}get(t){const e=this.chars*t;let r="";for(let t=0;t<this.chars;t++)r+=String.fromCodePoint(this.#s[e+t]);return r.replace(/\u0000/g,"")}set(t,e){const r=this.chars*t,n=this.#s.subarray(r,r+this.chars);n.fill(0);for(let t=0;t<this.chars;t++)n[t]=e.codePointAt(t)??0}fill(t){this.set(0,t);let e=this.#s.subarray(0,this.chars);for(let t=1;t<this.length;t++)this.#s.set(e,t*this.chars)}*[Symbol.iterator](){for(let t=0;t<this.length;t++)yield this.get(t)}}function o(t){const e=(new TextDecoder).decode(t);return JSON.parse(e)}function c(t,e){const r=e/2,n=e-1;let a=0;for(let s=0;s<t.length;s+=e)for(let e=0;e<r;e+=1)a=t[s+e],t[s+e]=t[s+n-e],t[s+n-e]=a}function d(t){if("v2:object"===t)return globalThis.Array;let e=t.match(/v2:([US])(\d+)/);if(e){let[,t,r]=e;return("U"===t?i:s).bind(null,Number(r))}let r={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:a}[t];return _(r,`Unknown or unsupported data_type: ${t}`),r}function l(t,e){const r=t.length;"string"==typeof e&&(e="C"===e?Array.from({length:r},(t,e)=>e):Array.from({length:r},(t,e)=>r-1-e)),_(r===e.length,"Order length must match the number of dimensions.");let n=1,a=new Array(r);for(let r=e.length-1;r>=0;r--)a[e[r]]=n,n*=t[e[r]];return a}function u({name:t,configuration:e}){if("default"===t){const t=e?.separator??"/";return e=>["c",...e].join(t)}if("v2"===t){const t=e?.separator??".";return e=>e.join(t)||"0"}throw new Error(`Unknown chunk key encoding: ${t}`)}function h(t,e={}){let r=[],n=function(t){if("|O"===t)return{data_type:"v2:object"};let e=t.match(/^([<|>])(.*)$/);_(e,`Invalid dtype: ${t}`);let[,r,n]=e,a={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[n]??(n.startsWith("S")||n.startsWith("U")?`v2:${n}`:void 0);return _(a,`Unsupported or unknown dtype: ${t}`),"|"===r?{data_type:a}:{data_type:a,endian:"<"===r?"little":"big"}}(t.dtype);"F"===t.order&&r.push({name:"transpose",configuration:{order:"F"}}),"endian"in n&&"big"===n.endian&&r.push({name:"bytes",configuration:{endian:"big"}});for(let{id:e,...n}of t.filters??[])r.push({name:e,configuration:n});if(t.compressor){let{id:e,...n}=t.compressor;r.push({name:e,configuration:n})}return{zarr_format:3,node_type:"array",shape:t.shape,data_type:n.data_type,chunk_grid:{name:"regular",configuration:{chunk_shape:t.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:t.dimension_separator??"."}},codecs:r,fill_value:t.fill_value,attributes:e}}function f(t){return"sharding_indexed"===t?.name}function y(t){return"uint64"!==t.data_type&&"int64"!==t.data_type||null==t.fill_value?t.fill_value:BigInt(t.fill_value)}function p(t,...e){if(!e.some(e=>t instanceof e))throw t}function _(t,e=""){if(!t)throw new Error(e)}async function g(t,{format:e,signal:r}){const n=t instanceof Response?t:new Response(t);_(n.body,"Response does not contain body.");try{const t=new Response(n.body.pipeThrough(new DecompressionStream(e),{signal:r}));return await t.arrayBuffer()}catch{throw r?.throwIfAborted(),new Error(`Failed to decode ${e}`)}}class m{kind="array_to_array";constructor(t,e){_(t.keepbits>=0,"keepbits must be zero or positive")}static fromConfig(t,e){return new m(t,e)}encode(t){throw new Error("`BitroundCodec.encode` is not implemented. Please open an issue at https://github.com/manzt/zarrita.js/issues.")}decode(t){return t}}const b=function(){const t=new Uint32Array([305419896]);return!(18===new Uint8Array(t.buffer,t.byteOffset,t.byteLength)[0])}();function w(t){return"BYTES_PER_ELEMENT"in t?t.BYTES_PER_ELEMENT:4}class v{kind="array_to_bytes";#i;#o;#c;#d;#l;constructor(t,e){this.#l=t?.endian,this.#o=d(e.data_type),this.#d=e.shape,this.#i=l(e.shape,"C");const r=new this.#o(0);this.#c=r.BYTES_PER_ELEMENT}static fromConfig(t,e){return new v(t,e)}encode(t){let e=new Uint8Array(t.data.buffer);return b&&"big"===this.#l&&c(e,w(this.#o)),e}decode(t){return b&&"big"===this.#l&&c(t,w(this.#o)),{data:new this.#o(t.buffer,t.byteOffset,t.byteLength/this.#c),shape:this.#d,stride:this.#i}}}class k{kind="bytes_to_bytes";static fromConfig(){return new k}encode(t){throw new Error("Not implemented")}decode(t){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength-4)}}class E{kind="bytes_to_bytes";static fromConfig(t){return new E}encode(t){throw new Error("Gzip encoding is not enabled by default. Please register a custom codec with `numcodecs/gzip`.")}async decode(t){const e=await g(t,{format:"gzip"});return new Uint8Array(e)}}function A(t,e){return _(!Number.isNaN(e),"JsonCodec allow_nan is false but NaN was encountered during encoding."),_(e!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),_(e!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),e}function U(t,e){return e instanceof Object&&!Array.isArray(e)?Object.keys(e).sort().reduce((t,r)=>(t[r]=e[r],t),{}):e}class x{configuration;kind="array_to_bytes";#u;#h;constructor(t={}){this.configuration=t;const{encoding:e="utf-8",skipkeys:r=!1,ensure_ascii:n=!0,check_circular:a=!0,allow_nan:s=!0,sort_keys:i=!0,indent:o,strict:c=!0}=t;let d=t.separators;d||(d=o?[", ",": "]:[",",":"]),this.#u={encoding:e,skipkeys:r,ensure_ascii:n,check_circular:a,allow_nan:s,indent:o,separators:d,sort_keys:i},this.#h={strict:c}}static fromConfig(t){return new x(t)}encode(t){const{indent:e,encoding:r,ensure_ascii:n,check_circular:a,allow_nan:s,sort_keys:i}=this.#u;_("utf-8"===r,"JsonCodec does not yet support non-utf-8 encoding.");const o=[];_(a,"JsonCodec does not yet support skipping the check for circular references during encoding."),s||o.push(A),i&&o.push(U);const c=Array.from(t.data);let d;c.push("|O"),c.push(t.shape),o.length&&(d=(t,e)=>{let r=e;for(let e of o)r=e(t,r);return r});let l=JSON.stringify(c,d,e);return n&&(l=l.replace(/[\u007F-\uFFFF]/g,t=>{const e=`0000${t.charCodeAt(0).toString(16)}`;return`\\u${e.substring(e.length-4)}`})),(new TextEncoder).encode(l)}decode(t){const{strict:e}=this.#h;_(e,"JsonCodec does not yet support non-strict decoding.");const r=o(t),n=r.pop();r.pop(),_(n,"0D not implemented for JsonCodec.");return{data:r,shape:n,stride:l(n,"C")}}}function T(t){if(t instanceof a||t instanceof s||t instanceof i){return new Proxy(t,{get:(t,e)=>t.get(Number(e)),set:(t,e,r)=>(t.set(Number(e),r),!0)})}return t}function z(t,e){let r=function(t,e){let r;return r=t.data instanceof s||t.data instanceof i?new t.constructor(t.data.length,t.data.chars):new t.constructor(t.data.length),{data:r,shape:t.shape,stride:l(t.shape,e)}}(t,e),n=t.shape.length,a=t.data.length,o=Array(n).fill(0),c=T(t.data),d=T(r.data);for(let e=0;e<a;e++){let a=0;for(let t=0;t<n;t++)a+=o[t]*r.stride[t];d[a]=c[e],o[0]+=1;for(let e=0;e<n;e++)if(o[e]===t.shape[e]){if(e+1===n)break;o[e]=0,o[e+1]+=1}}return r}function N(t,e){let r=function(t){return _(t.shape.length===t.stride.length,"Shape and stride must have the same length."),t.stride.map((t,e)=>({stride:t,index:e})).sort((t,e)=>e.stride-t.stride).map(t=>t.index)}(t);return _(r.length===e.length,"Orders must match"),r.every((t,r)=>t===e[r])}class M{kind="array_to_array";#f;#y;constructor(t,e){let r=t.order??"C",n=e.shape.length,a=new Array(n),s=new Array(n);if("C"===r)for(let t=0;t<n;++t)a[t]=t,s[t]=t;else if("F"===r)for(let t=0;t<n;++t)a[t]=n-t-1,s[t]=n-t-1;else a=r,a.forEach((t,e)=>{_(void 0===s[t],`Invalid permutation: ${JSON.stringify(r)}`),s[t]=e});this.#f=a,this.#y=s}static fromConfig(t,e){return new M(t,e)}encode(t){return N(t,this.#y)?t:z(t,this.#y)}decode(t){return{data:t.data,shape:t.shape,stride:l(t.shape,this.#f)}}}class ${kind="array_to_bytes";#d;#p;constructor(t){this.#d=t,this.#p=l(t,"C")}static fromConfig(t,e){return new $(e.shape)}encode(t){throw new Error("Method not implemented.")}decode(t){let e=new TextDecoder,r=new DataView(t.buffer),n=Array(r.getUint32(0,!0)),a=4;for(let s=0;s<n.length;s++){let i=r.getUint32(a,!0);a+=4,n[s]=e.decode(t.buffer.slice(a,a+i)),a+=i}return{data:n,shape:this.#d,stride:this.#p}}}class I{kind="bytes_to_bytes";static fromConfig(t){return new I}encode(t){throw new Error("Zlib encoding is not enabled by default. Please register a codec with `numcodecs/zlib`.")}async decode(t){const e=await g(t,{format:"deflate"});return new Uint8Array(e)}}const S=(new Map).set("blosc",()=>import("./chunks/BFspFXOv.esm.js").then(t=>t.default)).set("lz4",()=>import("./chunks/CeI1PA9E.esm.js").then(t=>t.default)).set("zstd",()=>import("./chunks/jUha9p1a.esm.js").then(t=>t.default)).set("gzip",()=>E).set("zlib",()=>I).set("transpose",()=>M).set("bytes",()=>v).set("crc32c",()=>k).set("vlen-utf8",()=>$).set("json2",()=>x).set("bitround",()=>m);function C(t){let e;return{async encode(r){e||(e=await L(t));for(const t of e.array_to_array)r=await t.encode(r);let n=await e.array_to_bytes.encode(r);for(const t of e.bytes_to_bytes)n=await t.encode(n);return n},async decode(r){e||(e=await L(t));for(let t=e.bytes_to_bytes.length-1;t>=0;t--)r=await e.bytes_to_bytes[t].decode(r);let n=await e.array_to_bytes.decode(r);for(let t=e.array_to_array.length-1;t>=0;t--)n=await e.array_to_array[t].decode(n);return n}}}async function L(t){let e,r=t.codecs.map(async t=>{let e=await(S.get(t.name)?.());return _(e,`Unknown codec: ${t.name}`),{Codec:e,meta:t}}),n=[],a=[];for await(let{Codec:s,meta:i}of r){let r=s.fromConfig(i.configuration,t);switch(r.kind){case"array_to_array":n.push(r);break;case"array_to_bytes":e=r;break;default:a.push(r)}}return e||(_("v2:object"!==t.data_type,`Cannot encode ${t.data_type} to bytes without a codec`),e=v.fromConfig({endian:"little"},t)),{array_to_array:n,array_to_bytes:e,bytes_to_bytes:a}}class O extends Error{constructor(t,e={}){super(`Node not found: ${t}`,e),this.name="NodeNotFoundError"}}class R extends Error{constructor(t){super(`Missing key: ${t}`),this.name="KeyError"}}const P=18446744073709551615n;function B(t,e,r,n){_(t.store.getRange,"Store does not support range requests");let a=t.store.getRange.bind(t.store),s=e.map((t,e)=>t/n.chunk_shape[e]),i=C({data_type:"uint64",shape:[...s,2],codecs:n.index_codecs}),o={};return async e=>{let n,c=e.map((t,e)=>Math.floor(t/s[e])),d=t.resolve(r(c)).path;if(d in o)n=o[d];else{let t=4,e=16*s.reduce((t,e)=>t*e,1),r=await a(d,{suffixLength:e+t});n=o[d]=r?await i.decode(r):null}if(null===n)return;let{data:l,shape:u,stride:h}=n,f=e.map((t,e)=>t%u[e]).reduce((t,e,r)=>t+e*h[r],0),y=l[f],p=l[f+1];return y!==P||p!==P?a(d,{offset:Number(y),length:Number(p)}):void 0}}class Y{store;path;constructor(t,e="/"){this.store=t,this.path=e}resolve(t){let e=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new Y(this.store,decodeURIComponent(new URL(t,e).pathname))}}class j extends Y{kind="group";#_;constructor(t,e,r){super(t,e),this.#_=r}get attrs(){return this.#_.attributes}}function F(t){const e=t.find(t=>"transpose"===t.name);return e?.configuration?.order??"C"}const D=Symbol("zarrita.context");let J=class extends Y{kind="array";#_;[D];constructor(t,e,r){super(t,e),this.#_={...r,fill_value:y(r)},this[D]=function(t,e){let{configuration:r}=e.codecs.find(f)??{},n={encode_chunk_key:u(e.chunk_key_encoding),TypedArray:d(e.data_type),fill_value:e.fill_value};if(r){let a=F(r.codecs);return{...n,kind:"sharded",chunk_shape:r.chunk_shape,codec:C({data_type:e.data_type,shape:r.chunk_shape,codecs:r.codecs}),get_strides:t=>l(t,a),get_chunk_bytes:B(t,e.chunk_grid.configuration.chunk_shape,n.encode_chunk_key,r)}}let a=F(e.codecs);return{...n,kind:"regular",chunk_shape:e.chunk_grid.configuration.chunk_shape,codec:C({data_type:e.data_type,shape:e.chunk_grid.configuration.chunk_shape,codecs:e.codecs}),get_strides:t=>l(t,a),async get_chunk_bytes(e,r){let a=n.encode_chunk_key(e),s=t.resolve(a).path;return t.store.get(s,r)}}}(this,r)}get attrs(){return this.#_.attributes}get shape(){return this.#_.shape}get chunks(){return this[D].chunk_shape}get dtype(){return this.#_.data_type}async getChunk(t,e){let r=this[D],n=await r.get_chunk_bytes(t,e);if(!n){let t=r.chunk_shape.reduce((t,e)=>t*e,1),e=new r.TypedArray(t);return e.fill(r.fill_value),{data:e,shape:r.chunk_shape,stride:r.get_strides(r.chunk_shape)}}return r.codec.decode(n)}is(t){return function(t,e){if("number"!==e&&"bigint"!==e&&"boolean"!==e&&"object"!==e&&"string"!==e)return t===e;let r="bool"===t;if("boolean"===e)return r;let n=t.startsWith("v2:U")||t.startsWith("v2:S");if("string"===e)return n;let a="int64"===t||"uint64"===t;if("bigint"===e)return a;let s="v2:object"===t;return"object"===e?s:!(n||a||r||s)}(this.dtype,t)}};function V(t,e,r=null){return void 0===e&&(e=t,t=null),{start:t,stop:e,step:r}}class W extends Error{constructor(t){super(t),this.name="IndexError"}}function q(t,e){t.length>e.length&&function(t,e){throw new W(`too many indicies for array; expected ${e.length}, got ${t.length}`)}(t,e)}function G(t,e){return(t=Math.trunc(t))<0&&(t=e+t),(t>=e||t<0)&&function(t){throw new W(`index out of bounds for dimension with length ${t}`)}(e),t}class Q{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:t,dim_len:e,dim_chunk_len:r}){t=G(t,e),this.dim_sel=t,this.dim_len=e,this.dim_chunk_len=r,this.nitems=1}*[Symbol.iterator](){const t=Math.floor(this.dim_sel/this.dim_chunk_len),e=t*this.dim_chunk_len,r=this.dim_sel-e;yield{dim_chunk_ix:t,dim_chunk_sel:r}}}class H{start;stop;step;dim_len;dim_chunk_len;nitems;nchunks;constructor({dim_sel:t,dim_len:e,dim_chunk_len:r}){const[n,a,s]=function({start:t,stop:e,step:r},n){if(0===r)throw new Error("slice step cannot be zero");const a=(r=r??1)<0,[s,i]=a?[-1,n-1]:[0,n];return null===t?t=a?i:s:t<0?(t+=n)<s&&(t=s):t>i&&(t=i),null===e?e=a?s:i:e<0?(e+=n)<s&&(e=s):e>i&&(e=i),[t,e,r]}(t,e);this.start=n,this.stop=a,this.step=s,this.step<1&&function(){throw new W("only slices with step >= 1 are supported")}(),this.dim_len=e,this.dim_chunk_len=r,this.nitems=Math.max(0,Math.ceil((this.stop-this.start)/this.step)),this.nchunks=Math.ceil(this.dim_len/this.dim_chunk_len)}*[Symbol.iterator](){const t=Math.floor(this.start/this.dim_chunk_len),e=Math.ceil(this.stop/this.dim_chunk_len);for(const r of function*(t,e,r=1){void 0===e&&(e=t,t=0);for(let n=t;n<e;n+=r)yield n}(t,e)){const t=r*this.dim_chunk_len,e=Math.min(this.dim_len,(r+1)*this.dim_chunk_len),n=e-t;let a=0,s=0;if(this.start<t){const e=(t-this.start)%this.step;e&&(s+=this.step-e),a=Math.ceil((t-this.start)/this.step)}else s=this.start-t;const i=this.stop>e?n:this.stop-t,o=[s,i,this.step],c=[a,a+Math.ceil((i-s)/this.step),1];yield{dim_chunk_ix:r,dim_chunk_sel:o,dim_out_sel:c}}}}class K{dim_indexers;shape;constructor({selection:t,shape:e,chunk_shape:r}){this.dim_indexers=function(t,e){let r=[];return null===t?r=e.map(t=>V(null)):Array.isArray(t)&&(r=t.map(t=>t??V(null))),q(r,e),r}(t,e).map((t,n)=>new("number"==typeof t?Q:H)({dim_sel:t,dim_len:e[n],dim_chunk_len:r[n]})),this.shape=this.dim_indexers.filter(t=>t instanceof H).map(t=>t.nitems)}*[Symbol.iterator](){for(const t of function*(...t){if(0===t.length)return;const e=t.map(t=>t[Symbol.iterator]()),r=e.map(t=>t.next());if(r.some(t=>t.done))throw new Error("Input contains an empty iterator.");for(let n=0;;){if(r[n].done){if(e[n]=t[n][Symbol.iterator](),r[n]=e[n].next(),++n>=e.length)return}else yield r.map(({value:t})=>t),n=0;r[n]=e[n].next()}}(...this.dim_indexers)){const e=t.map(t=>t.dim_chunk_ix),r=t.map(t=>"dim_out_sel"in t?{from:t.dim_chunk_sel,to:t.dim_out_sel}:{from:t.dim_chunk_sel,to:null});yield{chunk_coords:e,mapping:r}}}}async function Z(t,e,r,n){let a=t[D];let s=new K({selection:e,shape:t.shape,chunk_shape:t.chunks}),i=n.prepare(new a.TypedArray(s.shape.reduce((t,e)=>t*e,1)),s.shape,a.get_strides(s.shape)),o=r.create_queue?.()??function(){const t=[];return{add:e=>t.push(e()),onIdle:()=>Promise.all(t)}}();for(const{chunk_coords:e,mapping:a}of s)o.add(async()=>{let{data:s,shape:o,stride:c}=await t.getChunk(e,r.opts),d=n.prepare(s,o,c);n.set_from_chunk(i,d,a)});return await o.onIdle(),0===s.shape.length?function(t,e){return"get"in t?t.get(e):t[e]}(i.data,0):i}function X(t,e=0,r){let n=r??t.length-e;return{length:n,subarray:(r,a=n)=>X(t,e+r,a-r),set(r,n=0){for(let a=0;a<r.length;a++)t[e+n+a]=r.get(a)},get:r=>t[e+r]}}function tt(t){return globalThis.Array.isArray(t.data)?{data:X(t.data),stride:t.stride,bytes_per_element:1}:{data:new Uint8Array(t.data.buffer,t.data.byteOffset,t.data.byteLength),stride:t.stride,bytes_per_element:t.data.BYTES_PER_ELEMENT}}const et={prepare:(t,e,r)=>({data:t,shape:e,stride:r}),set_scalar(t,e,r){let n=tt(t);at(n,e,function(t,e){if(globalThis.Array.isArray(t.data))return X([e]);let r=new(function(t){return"chars"in t?t.constructor.bind(null,t.chars):t.constructor}(t.data))([e]);return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}(t,r),n.bytes_per_element)},set_from_chunk(t,e,r){let n=tt(t);st(n,tt(e),n.bytes_per_element,r)}};async function rt(t,e=null,r={}){return Z(t,e,r,et)}function nt(t,e,r){return r<0&&e<t?Math.floor((t-e-1)/-r)+1:t<e?Math.floor((e-t-1)/r)+1:0}function at(t,e,r,n){if(0===e.length)return void t.data.set(r,0);const[a,...s]=e,[i,...o]=t.stride;if("number"==typeof a){return void at({data:t.data.subarray(i*a*n),stride:o},s,r,n)}const[c,d,l]=a,u=nt(c,d,l);if(0!==s.length)for(let e=0;e<u;e++){at({data:t.data.subarray(i*(c+l*e)*n),stride:o},s,r,n)}else for(let e=0;e<u;e++)t.data.set(r,i*(c+l*e)*n)}function st(t,e,r,n){const[a,...s]=n,[i,...o]=t.stride,[c,...d]=e.stride;if(null===a.from)return 0===s.length?void t.data.set(e.data.subarray(0,r),a.to*r):void st({data:t.data.subarray(i*a.to*r),stride:o},e,r,s);if(null===a.to){if(0===s.length){let n=a.from*r;return void t.data.set(e.data.subarray(n,n+r),0)}return void st(t,{data:e.data.subarray(c*a.from*r),stride:d},r,s)}const[l,u,h]=a.to,[f,y,p]=a.from,_=nt(l,u,h);if(0!==s.length)for(let n=0;n<_;n++)st({data:t.data.subarray(i*(l+n*h)*r),stride:o},{data:e.data.subarray(c*(f+n*p)*r),stride:d},r,s);else{if(1===h&&1===p&&1===i&&1===c){let n=f*r,a=_*r;return void t.data.set(e.data.subarray(n,n+a),l*r)}for(let n=0;n<_;n++){let a=c*(f+p*n)*r;t.data.set(e.data.subarray(a,a+r),i*(l+h*n)*r)}}}let it=function(){let t=new WeakMap;function e(e){let r=t.get(e)??{v2:0,v3:0};return t.set(e,r),r}return{increment(t,r){e(t)[r]+=1},version_max(t){let r=e(t);return r.v3>r.v2?"v3":"v2"}}}();async function ot(t,e){let{path:r}=t.resolve(".zarray"),n=await t.store.get(r);if(!n)throw new O("v2 array",{cause:new R(r)});return it.increment(t.store,"v2"),new J(t.store,t.path,h(o(n),e))}async function ct(t,e){let{path:r}=t.resolve(".zgroup"),n=await t.store.get(r);if(!n)throw new O("v2 group",{cause:new R(r)});return it.increment(t.store,"v2"),new j(t.store,t.path,function(t,e={}){return{zarr_format:3,node_type:"group",attributes:e}}(o(n),e))}async function dt(t,e={}){let r="store"in t?t.store:t,n=it.version_max(r),a="v2"===n?dt.v2:dt.v3,s="v2"===n?dt.v3:dt.v2;return a(t,e).catch(r=>(p(r,O),s(t,e)))}dt.v2=async function(t,e={}){let r="store"in t?t:new Y(t),n={};return(e.attrs??1)&&(n=await async function(t){let e=await t.store.get(t.resolve(".zattrs").path);return e?o(e):{}}(r)),"array"===e.kind?ot(r,n):"group"===e.kind?ct(r,n):ot(r,n).catch(t=>(p(t,O),ct(r,n)))},dt.v3=async function(t,e={}){let r="store"in t?t:new Y(t),n=await async function(t){let{store:e,path:r}=t.resolve("zarr.json"),n=await t.store.get(r);if(!n)throw new O("v3 array or group",{cause:new R(r)});let a=o(n);return"array"===a.node_type&&(a.fill_value=y(a)),"array"===a.node_type?new J(e,t.path,a):new j(e,t.path,a)}(r);if(it.increment(r.store,"v3"),void 0===e.kind)return n;if("array"===e.kind&&n instanceof J)return n;if("group"===e.kind&&n instanceof j)return n;let a=n instanceof J?"array":"group";throw new Error(`Expected node of kind ${e.kind}, found ${a}.`)};const lt=async({zarrUrl:t,riverId:e,idx:r,idVariable:n})=>{if(void 0===r&&void 0===e)throw new Error("Either 'riverId' or 'idx' must be provided.");return void 0===r&&(r=await ft({zarrUrl:t,variable:n,value:e})),r},ut=async({zarrUrl:t,variable:e,selection:r=null})=>{const a=new n(`${t}/${e}`),s=await dt.v2(a);return[...(await rt(s,r)).data]},ht=async({zarrUrl:t,variable:e})=>await ut({zarrUrl:t,variable:e,selection:[null]}),ft=async({zarrUrl:t,variable:e,value:r})=>(await ht({zarrUrl:t,variable:e})).indexOf(r),yt=async({zarrUrl:t})=>{const e=new n(`${t}/time`),r=await dt.v2(e),a=await rt(r,[null]),s=r.attrs.units,i=new Date(s.split("since")[1].trim()),o={seconds:1,minutes:60,hours:3600,days:86400}[s.split("since")[0].trim()];return[...a.data].map(t=>{let e=new Date(i);return e.setSeconds(e.getSeconds()+Number(t)*o),e})};var pt=Object.freeze({__proto__:null,forecast:async function({baseUrl:t,date:e,riverId:r,idx:n}){if(!/^\d{8}$/.test(e))throw new Error(`Invalid date format: ${e}. Must be YYYYMMDD.`);const a=`${t||"http://geoglows-v2-forecasts.s3-website-us-west-2.amazonaws.com"}/${e}00.zarr`,s=await lt({zarrUrl:a,riverId:r,idx:n,idVariable:"rivid"});let[i,o]=await Promise.all([yt({zarrUrl:a}),ut({zarrUrl:a,variable:"Qout",selection:[{start:0,stop:51,step:1},null,s]})]);const c=o.slice(0,i.length).map((t,e)=>isNaN(t)?-1:e).filter(t=>-1!==t),d=Array(51).fill(0).map((t,e)=>e*i.length);o=d.map(t=>o.slice(t,t+i.length)).map(t=>c.map(e=>t[e])),i=c.map(t=>i[t]);const l=(t=>{const e=t.length,r=t[0].length;let n={min:Array(r).fill(0),p20:Array(r).fill(0),p25:Array(r).fill(0),median:Array(r).fill(0),p75:Array(r).fill(0),p80:Array(r).fill(0),max:Array(r).fill(0),average:Array(r).fill(0)};return Array(r).fill(0).forEach((r,a)=>{const s=t.map(t=>t[a]).sort((t,e)=>t-e);n.min[a]=s[0],n.p20[a]=s[Math.floor(.2*e)],n.p25[a]=s[Math.floor(.25*e)],n.median[a]=s[Math.floor(.5*e)],n.p75[a]=s[Math.floor(.75*e)],n.p80[a]=s[Math.floor(.8*e)],n.max[a]=s[e-1],n.average[a]=s.reduce((t,e)=>t+e,0)/e}),n})(o);return{time:i,discharge:o,stats:l}},retrospective:async function({baseUrl:t,resolution:e="daily",riverId:r,idx:n}){if(!["hourly","daily","monthly","yearly"].includes(e))throw new Error(`Invalid resolution: ${e}. Must be one of 'hourly', 'daily', 'monthly', 'yearly'.`);["monthly","yearly"].includes(e)&&(e=`${e}-timeseries`);const a=`${t||"http://geoglows-v2.s3-us-west-2.amazonaws.com"}/retrospective/${e}.zarr`,s=await lt({zarrUrl:a,riverId:r,idx:n,idVariable:"river_id"}),[i,o]=await Promise.all([yt({zarrUrl:a}),ut({zarrUrl:a,variable:"Q",selection:[null,s]})]);return{time:i,discharge:o}},returnPeriods:async function({baseUrl:t,riverId:e,idx:r}){const n=`${t||"http://geoglows-v2.s3-us-west-2.amazonaws.com"}/retrospective/return-periods.zarr`,a=await lt({zarrUrl:n,riverId:e,idx:r,idVariable:"river_id"}),[s,i]=await Promise.all([ht({zarrUrl:n,variable:"return_period"}),ut({zarrUrl:n,variable:"gumbel",selection:[null,a]})]);return s.reduce((t,e,r)=>(t[Number(e)]=Number(i[r]),t),{})}});const _t={v2:pt};export{_t as default,pt as v2};
1
+ import{v as s}from"./chunks/DZrFLMB9.esm.js";import{v as m}from"./chunks/DYah8QCr.esm.js";import{u as o,g as r,c as e}from"./chunks/BcUKIvbV.esm.js";import"./chunks/pq2-5-mb.esm.js";import"./chunks/B3OxysOz.esm.js";const t={configure:e,getConfig:r,urls:o,v2:s,v3:m};export{e as configure,t as default,r as getConfig,o as urls,s as v2,m as v3};
@@ -0,0 +1 @@
1
+ export{f as forecast,r as retrospective,a as returnPeriods}from"../chunks/DZrFLMB9.esm.js";import"../chunks/pq2-5-mb.esm.js";import"../chunks/B3OxysOz.esm.js";
@@ -0,0 +1 @@
1
+ import{r,g as e,a,f as t,m as n,d as l,b as i,c as s,o}from"../chunks/F6d4L9u4.esm.js";import{f as c,r as u,a as d,m}from"../chunks/BcUKIvbV.esm.js";import{g as f,s as h}from"../chunks/B3OxysOz.esm.js";import"../chunks/pq2-5-mb.esm.js";function v(r){const e=r.length,a=r[0]?.length??0;let t={min:Array(a).fill(NaN),p20:Array(a).fill(NaN),p25:Array(a).fill(NaN),median:Array(a).fill(NaN),p75:Array(a).fill(NaN),p80:Array(a).fill(NaN),max:Array(a).fill(NaN),average:Array(a).fill(NaN),peak:NaN,memberCount:e};return Array(a).fill(0).forEach((e,a)=>{const n=r.map(r=>r[a]).sort((r,e)=>r-e),l=n.length;0!==l&&(t.min[a]=n[0],t.p20[a]=n[Math.floor(.2*l)],t.p25[a]=n[Math.floor(.25*l)],t.median[a]=n[Math.floor(.5*l)],t.p75[a]=n[Math.floor(.75*l)],t.p80[a]=n[Math.floor(.8*l)],t.max[a]=n[l-1],t.average[a]=n.reduce((r,e)=>r+e,0)/l)}),a>0&&(t.peak=t.median.reduce((r,e)=>e>r?e:r,-1/0)),t}async function g({date:i,riverIndex:s,riverId:o}){const u=c({date:i}),d=await r({zarrUrl:u,riverIndex:s,riverId:o});let[m,f,h]=await Promise.all([e({zarrUrl:u}),a({zarrUrl:u,variable:n}),t({zarrUrl:u,variable:l,selection:[null,null,d]})]);return h=f.map((r,e)=>h.slice(e*m.length,(e+1)*m.length)),{riverIndex:d,riverId:o,time:m,discharge:h,stats:v(h)}}function p(r){const e=r.length,a=r[0]?.length??0,t=Array(a).fill(NaN);let n=NaN;for(let e=0;e<a;e++){const a=r.map(r=>r[e]).sort((r,e)=>r-e),l=a.length;if(0===l)continue;const i=a[Math.floor(.5*l)];t[e]=i,i<=n||(n=i)}return{median:t,peak:n,memberCount:e}}const I=new Map,N=({zarrUrl:r})=>{let a=I.get(r);return a||(a=(async({zarrUrl:r})=>{const[a,t]=await Promise.all([o({zarrUrl:r,variable:l}),e({zarrUrl:r})]);return{discharge:a,time:t}})({zarrUrl:r}).catch(e=>{throw I.delete(r),e}),I.set(r,a)),a};async function y({date:r,riverIndices:e,riverIds:a,onProgress:t}){const n=c({date:r}),l=await N({zarrUrl:n}),o=new Map,u=[],d=e??a,m=e??await i({zarrUrl:n,riverIds:a}),v=new Map,g=l.discharge.chunks[2],I=l.discharge.shape[2];d.forEach((r,e)=>{const a=Number(m[e]);if(!Number.isInteger(a)||a<0||a>=I)return void u.push(r);const t=Math.floor(a/g),n=v.get(t);n?n.push([r,a]):v.set(t,[[r,a]])});let y=0;const z=d.length-u.length;for(const r of v.values()){const e=Math.min(...r.map(([,r])=>r)),a=Math.max(...r.map(([,r])=>r)),n=await f(l.discharge,[null,null,h(e,a+1)]),i=n.data,[c,u]=n.shape,[d,m,v]=n.stride;for(const[a,n]of r){const r=(n-e)*v,l=Array.from({length:c},(e,a)=>{const t=new Float64Array(u);for(let e=0;e<u;e++)t[e]=s(i[a*d+e*m+r]);return t});o.set(a,{riverIndex:n,...p(l)}),t?.(++y,z)}}return{date:r,time:l.time,forecasts:o,missing:u}}async function z({resolution:a="daily",riverIndex:n,riverId:i}){const s=u({resolution:a}),o=await r({zarrUrl:s,riverIndex:n,riverId:i}),[c,d]=await Promise.all([e({zarrUrl:s}),t({zarrUrl:s,variable:l,selection:[null,o]})]);return{riverIndex:o,time:c,discharge:d}}const U=["hourly","daily"];async function w({riverIndex:e,riverId:n,resolution:l="hourly"}){if(!U.includes(l))throw new Error(`Invalid resolution: ${l}. Must be one of ${U.join(", ")}.`);const i=d(),s=await r({zarrUrl:i,riverIndex:e,riverId:n}),[o,c]=await Promise.all([a({zarrUrl:i,variable:"recurrence_interval"}),t({zarrUrl:i,variable:`gumbel_${l}`,selection:[null,s]})]);return o.reduce((r,e,a)=>(r[Number(e)]=Number(c[a]),r),{})}async function b({riverIndex:a,riverId:n}){const i=m(),s=await r({zarrUrl:i,riverIndex:a,riverId:n}),[o,c]=await Promise.all([e({zarrUrl:i}),t({zarrUrl:i,variable:l,selection:[null,s]})]);return{riverIndex:s,time:o,discharge:c}}export{g as forecast,y as forecastsBulk,b as maximums,p as membersToMedian,v as membersToStats,z as retrospective,w as returnPeriods};
@@ -0,0 +1 @@
1
+ import{b as e,d as t}from"../chunks/BcUKIvbV.esm.js";import{o as r,g as s,s as i,r as n}from"../chunks/B3OxysOz.esm.js";const a=async e=>{const t=await fetch(e);if(404!==t.status){if(!t.ok)throw new Error(`HTTP ${t.status} for ${e}`);return t.arrayBuffer()}};function o(e,t){return{async get(r){const s=await t(`${e}${r}`);return void 0===s?void 0:new Uint8Array(s)}}}const l=e=>{const t=new Float32Array(e.length);for(let r=0;r<e.length;r++)t[r]=Math.fround(e[r]/1e3);return t},c=(e,t)=>{const r=new Int32Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]+t;return r};function h(e,t){const r=e.get(t);if(void 0!==r)return e.delete(t),e.set(t,r),r}function d(e,t,r,s){for(e.set(t,r);e.size>s;)e.delete(e.keys().next().value);return r}class f{constructor(e,t,r,s){this.dataBase=e,this.fetcher=t,this.tilePath=r,this.riverTiles=s}dataBase;fetcher;tilePath;riverTiles;tiles=new Map;slices=new Map;activeTiles=new Set;riverIndex=null;indexChunks=new Map;static async open({fetcher:i=a,base:l=null}={}){const c=l??e(),h=await i(l?`${l}/zarr.json`:t());if(!h)throw new Error(`zarr.json not found under ${c}`);const d=JSON.parse((new TextDecoder).decode(h)).attributes;if(!d?.tiles||!d.index||!d.tilePaths)throw new Error(`${c}/zarr.json: not a flood-maps root (no tiles/index/tilePaths attrs)`);const u=new Map,w=new Array(d.tilePaths.length);for(const[e,t]of Object.entries(d.tiles))u.set(e,t.path),w[t.id]=e;const v=new f(c,i,u,new Map),p=n(o(`${c}/rivers`,i)),[y,m]=await Promise.all([r.v3(p.resolve("tile"),{kind:"array"}),r.v3(p.resolve("covered"),{kind:"array"})]),x=(await s(m)).data;return v.riverIndex={tileNames:w,tileArr:y,chunk:d.index.chunk,width:d.index.maxTilesPerRiver,nRivers:d.index.nRivers,covered:x},v}static async openTiles({tiles:t,fetcher:r=a,base:s=null}={}){const i=new f(s??e(),r,new Map(Object.entries(t)),new Map);for(const e of i.tilePath.keys()){const t=await i.tile(e);for(const r of t.riverIndices){const t=i.riverTiles.get(r);t?t.push(e):i.riverTiles.set(r,[e])}}return i}coverage(){return Uint32Array.from(this.riverTiles.keys())}hasCoverage(e){const t=this.riverIndex;return t?!(e<0||e>=t.nRivers)&&1==(t.covered[e>>3]>>(7&e)&1):this.riverTiles.has(e)}coveredBits(){return this.riverIndex?.covered??null}indexChunk(e){let t=h(this.indexChunks,e);if(!t){const r=this.riverIndex,n=e*r.chunk,a=Math.min(n+r.chunk,r.nRivers);t=d(this.indexChunks,e,s(r.tileArr,[i(n,a),null]).then(e=>e.data),64)}return t}async resolve(e){const t=new Map,r=(e,r)=>{const s=t.get(e);s?s.push(r):t.set(e,[r])},s=this.riverIndex;if(!s){for(const t of e)for(const e of this.riverTiles.get(t)??[])r(e,t);return t}const i=new Map;for(const t of e){if(t<0||t>=s.nRivers)continue;const e=Math.floor(t/s.chunk),r=i.get(e);r?r.push(t):i.set(e,[t])}return await Promise.all([...i].map(async([e,t])=>{const i=await this.indexChunk(e);for(const n of t){const t=(n-e*s.chunk)*s.width;for(let e=0;e<s.width;e++){const a=i[t+e];if(a<0)break;const o=s.tileNames[a];if(void 0===o)throw new Error(`rivers/tile: riverIndex ${n} names tile id ${a}, not in root tilePaths`);r(o,n)}}})),t}async setActiveTiles(e){for(const t of e){if(this.activeTiles.has(t)||!this.tilePath.has(t))continue;let e;this.activeTiles.add(t);try{e=await this.tile(t)}catch(e){console.warn(`flood-maps: tile ${t} unavailable — ${e.message??e}`),this.activeTiles.delete(t),this.tiles.delete(t);continue}for(const r of e.riverIndices){const e=this.riverTiles.get(r);e?e.includes(t)||e.push(t):this.riverTiles.set(r,[t])}}return this.coverage()}tile(e){let t=h(this.tiles,e);return t||(t=d(this.tiles,e,this.openTile(e),64)),t}async openTile(e){const t=this.tilePath.get(e);if(!t)throw new Error(`tile ${e} not in manifest`);const r=`${this.dataBase}/${t}`,s=await this.fetcher(`${r}/zarr.json`);if(!s)throw new Error(`zarr.json missing for ${e}`);const i=JSON.parse((new TextDecoder).decode(s)).attributes,a=i.rivers?.riverIndex;if(!a)throw new Error(`${e}: store attrs.rivers has no riverIndex list`);const l=new Map;a.forEach((e,t)=>l.set(e,t));const c=n(o(r,this.fetcher));return{attrs:i,riverIndices:a,rank:l,root:c,arrays:new Map}}array(e,t){let s=e.arrays.get(t);return s||(s=r.v3(e.root.resolve(t),{kind:"array"}),e.arrays.set(t,s)),s}async read1d(e,t,r,n){const a=await this.array(e,t);if(0===n)return new(a.shape.length,Uint8Array)(0);return(await s(a,[i(r,r+n)])).data}async read2d(e,t,r,n){if(0===n)return new Float32Array(0);const a=await this.array(e,t);return(await s(a,[i(r,r+n),null])).data}slice(e,t){const r=`${e}/${t}`;let s=h(this.slices,r);return s||(s=d(this.slices,r,this.loadSlice(e,t),512)),s}async loadSlice(e,t){const r=await this.tile(e),s=r.rank.get(t);if(void 0===s)throw new Error(`riverIndex ${t} not in tile ${e}`);const i=r.attrs.rivers,{gRow0:n,gCol0:a}=r.attrs.grid,o=i.visitStart[s],h=i.visitCount[s],d=i.pixStart[s],f=i.pixCount[s],u=i.relStart[s],w=i.relCount[s],[v,p,y,m,x,g,k,T,$,b,I,P,M]=await Promise.all([this.read1d(r,"streams/fsp_local",o,h),this.read1d(r,"streams/row",o,h),this.read1d(r,"streams/col",o,h),this.read1d(r,"streams/bed",o,h),this.read1d(r,"streams/q_baseflow",o,h),this.read2d(r,"streams/q",o,h),this.read2d(r,"streams/wse",o,h),this.read1d(r,"library/pix_row",d,f),this.read1d(r,"library/pix_col",d,f),this.read1d(r,"library/fill_mm",d,f),this.read1d(r,"library/rel_count",d,f),this.read1d(r,"library/fsp_local",u,w),this.read1d(r,"library/dtf_mm",u,w)]),C=i.runStarts[s],A=new Int32Array(C.length+1);return A.set(C),A[C.length]=h,{riverIndex:t,tile:e,nVisit:h,nFsp:i.fspCount[s],runStarts:A,fspLocal:v,row:c(p,n),col:c(y,a),bed:m,qBaseflow:x,q:g,wse:k,nPix:f,pixRow:c(T,n),pixCol:c($,a),fill:l(b),relCount:I,relFspLocal:P,relDtf:l(M)}}async slicesFor(e){const t=await this.resolve(e),r=[];for(const[e,s]of t)for(const t of s)r.push(this.slice(e,t));return Promise.all(r)}}export{f as FloodMapsIndex,a as httpFetcher};
@@ -0,0 +1 @@
1
+ import{o as t}from"../chunks/F6d4L9u4.esm.js";import{h as e,e as s}from"../chunks/BcUKIvbV.esm.js";import{g as a,s as n}from"../chunks/B3OxysOz.esm.js";import"../chunks/pq2-5-mb.esm.js";const r=async({variable:s,group:r,onProgress:o,signal:i,concurrency:h=8}={})=>{if(!s)throw new Error("fetchMetadataArray requires a variable");const c=await t({zarrUrl:e({group:r}),variable:s}),l=c.shape[0],d=c.chunks[0];if(!l||!d)throw new Error(`${s}: expected a chunked 1-D array, got shape ${c.shape}`);const u=()=>{if(i?.aborted)throw new DOMException(`Aborted while reading ${s}`,"AbortError")};u();const f=await a(c,[n(0,Math.min(d,l))]),p=new f.data.constructor(l);p.set(f.data,0);let w=Math.min(d,l);o?.({done:w,total:l});const g=[];for(let t=d;t<l;t+=d)g.push(t);let m=0;return await Promise.all(Array.from({length:Math.min(h,g.length)},async()=>{for(;m<g.length;){u();const t=g[m++],e=Math.min(t+d,l),{data:s}=await a(c,[n(t,e)]);p.set(s,t),w+=e-t,o?.({done:w,total:l})}})),u(),p},o=async({variables:s,index:r,group:o}={})=>{if(!s?.length)throw new Error("fetchMetadataAt requires at least one variable");if(!Number.isInteger(r)||r<0)throw new Error(`fetchMetadataAt requires a non-negative integer index, got ${r}`);const i=e({group:o}),h=await Promise.all(s.map(async e=>{const s=await t({zarrUrl:i,variable:e}),o=s.shape[0];if(r>=o)throw new Error(`${e}: index ${r} is past the end of the axis (${o})`);const{data:h}=await a(s,[n(r,r+1)]);return[e,Number(h[0])]}));return Object.fromEntries(h)};class i{terminal;downMap;upAdj;areaKm2;meta;constructor(t){this.terminal=t.schema.terminal_value,this.meta=t.meta,this.downMap=new Map,this.upAdj=new Map,this.areaKm2=new Map;for(const e of t.edges){const[t,s]=e;if(this.downMap.set(t,s),e.length>2&&e[2]>0&&this.areaKm2.set(t,e[2]),s!==this.terminal){let e=this.upAdj.get(s);e||this.upAdj.set(s,e=new Set),e.add(t)}}}has(t){return this.downMap.has(t)}upstreamOf(t){const e=new Set([t]),s=[t];for(let t=0;t<s.length;t++){const a=this.upAdj.get(s[t]);if(a)for(const t of a)e.has(t)||(e.add(t),s.push(t))}return e}downstreamOf(t){const e=new Set;let s=t;for(;this.downMap.has(s)&&!e.has(s);){e.add(s);const t=this.downMap.get(s);if(t===this.terminal)break;s=t}return e}upstreamClosure(t){const e=new Set;for(const s of t)for(const t of this.upstreamOf(s))e.add(t);return e}downstreamClosure(t){const e=new Set;for(const s of t)for(const t of this.downstreamOf(s))e.add(t);return e}upCounts=null;buildUpCounts(){if(this.upCounts)return this.upCounts;const t=new Map,e=new Map,s=[];for(const a of this.downMap.keys()){const n=this.upAdj.get(a)?.size??0;t.set(a,1),e.set(a,n),0===n&&s.push(a)}for(let a=0;a<s.length;a++){const n=s[a],r=this.downMap.get(n);if(void 0===r||r===this.terminal||!this.downMap.has(r))continue;t.set(r,(t.get(r)??1)+(t.get(n)??1));const o=(e.get(r)??1)-1;e.set(r,o),0===o&&s.push(r)}return this.upCounts=t,t}parentsByStem(t){const e=this.upAdj.get(t);if(!e||0===e.size)return[];const s=[...e];if(s.every(t=>this.areaKm2.has(t)))return s.sort((t,e)=>this.areaKm2.get(e)-this.areaKm2.get(t)||t-e);const a=this.buildUpCounts();return s.sort((t,e)=>(a.get(e)??0)-(a.get(t)??0)||t-e)}walkBranch(t,e,s){let a=t;for(let t=0;t<e&&!s.has(a);t++){s.add(a);const t=this.parentsByStem(a);if(0===t.length)break;a=t[0]}}aroundClick(t,e,s,a){const n=new Set;if(!this.downMap.has(t))return n;n.add(t);const r=[];let o=t;for(let t=0;t<e;t++){const t=this.parentsByStem(o);if(0===t.length)break;for(let e=1;e<t.length;e++)r.push(t[e]);if(n.has(t[0]))break;n.add(t[0]),o=t[0]}o=t;for(let t=0;t<s;t++){const t=this.downMap.get(o);if(void 0===t||t===this.terminal||!this.downMap.has(t)||n.has(t))break;for(const e of this.upAdj.get(t)??[])e!==o&&r.push(e);n.add(t),o=t}for(const t of r)this.walkBranch(t,a,n);return n}ranks=new Map;rankToOutlet(t){if(!this.downMap.has(t))return-1;const e=[];let s=t;for(;void 0===this.ranks.get(s);){e.push(s);const t=this.downMap.get(s);if(void 0===t||t===this.terminal||!this.downMap.has(t)){this.ranks.set(s,0);break}if(e.length>this.downMap.size){this.ranks.set(s,0);break}s=t}for(let t=e.length-1;t>=0;t--){const s=e[t];void 0===this.ranks.get(s)&&this.ranks.set(s,this.ranks.get(this.downMap.get(s))+1)}return this.ranks.get(t)}between(t){const e=[...new Set(t)],s=new Set(e);let a=e.filter(t=>this.downMap.has(t)).map(t=>({at:t,clicks:[t],trail:[t]}));if(a.length<2)return{corridor:s,junctions:[],detached:e};const n=a.length*this.downMap.size+1;for(let t=0;a.length>1&&t<n;t++){let t=a[0];for(const e of a)this.rankToOutlet(e.at)>this.rankToOutlet(t.at)&&(t=e);const e=this.downMap.get(t.at);if(void 0===e||e===this.terminal||!this.downMap.has(e))break;t.at=e,t.trail.push(e);const s=a.find(s=>s!==t&&s.at===e);s&&(s.clicks.push(...t.clicks),s.trail.push(...t.trail),s.junction=e,s.settled=s.trail.length,a=a.filter(e=>e!==t))}const r=[],o=e.filter(t=>!this.downMap.has(t));for(const t of a)if(t.clicks.length<2)o.push(t.clicks[0]);else{r.push(t.junction);for(const e of t.trail.slice(0,t.settled))s.add(e)}return{corridor:s,junctions:r,detached:o}}}async function h(t=s()){const e=await fetch(t);if(!e.ok)throw new Error(`river network graph fetch failed: ${e.status} ${t}`);return new i(await e.json())}export{i as RiverNetwork,r as fetchMetadataArray,o as fetchMetadataAt,h as loadRiverNetwork};
@@ -0,0 +1 @@
1
+ export{c as configure,g as getConfig,u as urls}from"../chunks/BcUKIvbV.esm.js";
@@ -0,0 +1 @@
1
+ import{Chart as e,LineController as t,LineElement as a,PointElement as r,LinearScale as o,CategoryScale as i,TimeScale as n,Filler as l,Legend as s,Tooltip as d,Title as c,Decimation as m,ScatterController as u}from"chart.js";import"chartjs-adapter-date-fns";import p from"chartjs-plugin-zoom";import{MatrixController as h,MatrixElement as y}from"chartjs-chart-matrix";const g=Array.from({length:12},(e,t)=>String(t+1).padStart(2,"0")),b=[1,32,60,91,121,152,182,213,244,274,305,335],f=[0,13,28,72,87],x=["rgb(44, 125, 205)","rgb(142, 206, 238)","rgb(231, 226, 188)","rgb(255, 168, 133)","rgb(205, 35, 63)"],v=Array.from({length:51},(e,t)=>2*t),k=e=>[...v].reverse().map(t=>e[Math.floor(e.length*t/100)-(100===t?1:0)]);var C={"chart.cumulativeVolume":"Cumulative annual volume","chart.dailyTimeseries":"Retrospective daily discharge · river {riverId}","chart.flowDurationCurve":"Flow duration curve","chart.forecastHydrograph":"15-day ensemble forecast · river {riverId}","chart.monthlyStatus":"Monthly flow status","chart.rasterHydrograph":"Raster hydrograph","chart.yearlyPeaks":"Yearly peak discharge","chart.yearlyVolumes":"Yearly volumes","axis.cumulativeVolume":"Cumulative volume (Mm³)","axis.datetime":"Datetime (UTC+00:00)","axis.dayOfPeak":"Day of peak","axis.dayOfYear":"Day of year","axis.discharge":"Discharge (m³/s)","axis.flow":"Flow (m³/s)","axis.month":"Month","axis.percentile":"Percentile (%)","axis.volume":"Volume (m³ × 10⁶)","axis.year":"Year","tooltip.day":"day","series.allMonths":"All months","series.annualVolume":"Annual volume","series.dailyMean":"Daily mean discharge","series.fiveYearAverage":"5-year average","series.monthlyAverage":"Monthly average","series.ensembleMedian":"Ensemble median","series.iqr":"IQR (25–75%)","series.medianDay":"Median day","series.range":"Range (min–max)","series.temporalOutlier":"Temporal outlier","label.returnPeriodYears":"{n}-year","control.all":"All","control.resetZoom":"Reset zoom","control.yearsShort":"{n}y","control.zoomHint":"drag a box to zoom · shift-drag to pan",months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],status:["High","Above normal","Normal","Below normal","Low"]};const M={es:()=>import("../chunks/DvWHvDDD.esm.js"),fr:()=>import("../chunks/vJR8AuKC.esm.js")},A=new Map([["en",C]]);let w=C;async function R(e){const t=(e=>String(e??"en").trim().toLowerCase().split(/[-_]/)[0])(e),a=A.get(t);if(a)return w=a,w;const r=M[t];if(!r)return w=C,w;try{const e=await r(),a={...C,...e.default??e};A.set(t,a),w=a}catch{w=C}return w}const S=()=>["en",...Object.keys(M)],F=e=>w[e]??C[e]??e,W=(e,t={})=>String(F(e)).replace(/\{(\w+)\}/g,(e,a)=>a in t?String(t[a]):e);e.register(t,a,r,o,i,n,l,s,d,c),e.defaults.plugins.title.font={...e.defaults.plugins.title.font,size:18},e.defaults.plugins.legend.position="right",e.defaults.scale.title.font={size:14,weight:"bold"},e.defaults.plugins.legend.labels.usePointStyle=!0;const T=e.defaults.plugins.legend.labels.generateLabels;"function"==typeof T&&(e.defaults.plugins.legend.labels.generateLabels=e=>{const t=T(e);for(const a of t){const t=e.data.datasets[a.datasetIndex];t&&("scatter"!==t.type&&!1!==t.showLine&&(Boolean(t.fill)&&!1!==t.fill&&!t.borderWidth?a.pointStyle="rect":(a.pointStyle="line",a.strokeStyle=t.borderColor,a.lineWidth=t.borderWidth||2,a.lineDash=t.borderDash||[])))}return t});const D="#94a3b8",N="rgba(148,163,184,.12)",O="#e2e8f0";let Y=D,$=N,z=O;function j(e){const t=e??("undefined"==typeof document?null:document.documentElement);if(!t||"function"!=typeof getComputedStyle)return Y=D,$=N,void(z=O);const a=getComputedStyle(t),r=(e,t)=>a.getPropertyValue(e).trim()||t;Y=r("--rfs-chart-axis",D),$=r("--rfs-chart-grid",N),z=r("--rfs-chart-text",O)}const P=["#440154","#3b528b","#21918c","#5ec962","#fde725"],H=["#440154","#414487","#2a788e","#22a884","#7ad151","#bddf26","#fde725"],I=(e,t)=>e.replace("rgb(","rgba(").replace(")",`, ${t})`),U=(e,t={})=>({title:{display:!0,text:e,color:Y},ticks:{color:Y},grid:{color:$},...t}),E=(e,t=!0)=>({legend:{display:t,labels:{color:z,boxWidth:12,font:{size:11}}},title:{display:!0,text:e,color:z}}),V=()=>({type:"linear",min:.5,max:366.5,afterBuildTicks:e=>{e.ticks=b.map(e=>({value:e}))},ticks:{color:Y,callback:e=>F("months")[b.indexOf(Number(e))]??""},grid:{color:$}});function L(e){const t=document.createElement("div");t.className="chart-canvas";const a=document.createElement("canvas");return t.appendChild(a),e.appendChild(t),a}e.register(m,p);const Z=(e,t,a)=>{const r=new Date(e);return r.setFullYear(r.getFullYear()-t),Math.max(a,r.getTime())};function _(t,a){const r=(new Date).getUTCFullYear(),o=a.yearlyPeaks.filter(e=>e.year<r&&Number.isFinite(e.peak)),i=Math.min(...o.map(e=>e.year)),n=Math.max(...o.map(e=>e.year)),l=o.map(e=>e.peak),s=Math.min(...l),d=Math.max(...l),c=o.map(e=>2*Math.PI*(e.doy-1)/365),m=(e,t)=>Math.min(Math.abs(e-t),2*Math.PI-Math.abs(e-t)),u=c.reduce((e,t)=>{const a=c.reduce((e,a)=>e+m(a,t),0);return a<e.dist?{a:t,dist:a}:e},{a:0,dist:1/0}).a,p=Math.round(u/(2*Math.PI)*365)+1,h=c.map(e=>m(e,u)*(365/(2*Math.PI))),y=[...h].sort((e,t)=>e-t),g=y[Math.floor(.25*y.length)],b=y[Math.floor(.75*y.length)],f=b+1.5*(b-g),x=P.map((e,t)=>({type:"scatter",label:`bin ${t+1}`,backgroundColor:e,pointRadius:5,data:o.filter(e=>{return a=e.peak,Math.min(4,Math.max(0,Math.floor((a-s)/(d-s||1)*5)))===t;var a}).map(e=>({x:e.doy,y:e.year,peak:e.peak}))})),v={type:"scatter",label:F("series.temporalOutlier"),backgroundColor:"rgba(0,0,0,0)",borderColor:"#ef4444",borderWidth:2,pointRadius:8,data:o.filter((e,t)=>(e=>h[e]>f&&h[e]>30)(t)).map(e=>({x:e.doy,y:e.year}))},k={type:"line",label:F("series.medianDay"),borderColor:z,borderDash:[5,5],borderWidth:1,pointRadius:0,data:[{x:p,y:i-1},{x:p,y:n+1}]};return new e(L(t),{type:"scatter",data:{datasets:[...x,v,k]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,plugins:{...E(F("chart.yearlyPeaks")),tooltip:{callbacks:{label:e=>{const t=e.raw;return null!=t.peak?`${t.y}: ${t.peak.toFixed(1)} m³/s (day ${t.x})`:""}}}},scales:{x:{...V(),title:{display:!0,text:F("axis.dayOfPeak"),color:Y}},y:U(F("axis.year"),{min:i-1,max:n+1,ticks:{color:Y,stepSize:1,precision:0}})}}})}function X(t,a){let r=1/0,o=-1/0;for(const e of a.raster.z)for(const t of e)null!=t&&(t<r&&(r=t),t>o&&(o=t));const i=[];a.raster.z.forEach((e,t)=>e.forEach((e,r)=>{null!=e&&i.push({x:r+1,y:a.raster.years[t],v:e})}));const n=a.raster.years.length;return new e(L(t),{type:"matrix",data:{datasets:[{label:F("axis.discharge"),data:i,backgroundColor:e=>{return t=e.raw.v,H[Math.min(6,Math.max(0,Math.floor((t-r)/(o-r||1)*7)))];var t},borderWidth:0,width:e=>e.chart.chartArea?e.chart.chartArea.width/366:0,height:e=>e.chart.chartArea?e.chart.chartArea.height/n:0}]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,plugins:{...E(F("chart.rasterHydrograph"),!1),tooltip:{callbacks:{title:()=>"",label:e=>{const t=e.raw;return`${t.y} · ${F("tooltip.day")} ${t.x}: ${t.v.toFixed(1)} m³/s`}}}},scales:{x:{...V(),title:{display:!0,text:F("axis.dayOfYear"),color:Y}},y:U(F("axis.year"),{type:"linear",min:a.raster.years[0]-.5,max:a.raster.years[n-1]+.5,ticks:{color:Y,stepSize:5,precision:0}})}}})}e.register(u),e.register(h,y);const B=["rgb(254, 240, 1)","rgb(253, 154, 1)","rgb(255, 56, 5)","rgb(255, 0, 0)","rgb(128, 0, 106)","rgb(128, 0, 246)"],J=(e,t)=>B[Math.round(e*(B.length-1)/Math.max(1,t-1))],q=e=>null==e||""===e?NaN:Number(e);function K(e,t,a,r){if("lines"===r)return{fill:!1,borderColor:e.color,borderWidth:1.5,borderDash:[6,4],backgroundColor:void 0};const o=a[t+1],i=I(e.color,.3);return{fill:o?{target:{value:o.value},above:i,below:i}:{target:"end",above:i,below:i},borderColor:e.color,borderWidth:0,borderDash:[],backgroundColor:i}}function Q(e,{mode:t,firstX:a,lastX:r,hidden:o}){return e.map((i,n)=>({label:i.text,data:[{x:a,y:i.value},{x:r,y:i.value}],parsing:!1,hidden:o,rfsLevel:!0,order:10,pointRadius:0,pointHitRadius:0,tension:0,...K(i,n,e,t)}))}e.register(p);const G="rgb(56,189,248)",ee=(e,t)=>e.map((e,a)=>({x:e.getTime(),y:t[a]})).filter(e=>Number.isFinite(e.y));function te(t,a,{returnPeriods:r,levelsAs:o="boxes"}={}){const i=L(t),{riverId:n,time:l,stats:s}=a,d=l.length?l[0].getTime():0,c=l.length?l[l.length-1].getTime():d,m=function(e){if(!e)return[];const t=(Array.isArray(e)?e.map(e=>({label:e.label,value:q(e.value),color:e.color})):Object.entries(e).map(([e,t])=>({label:W("label.returnPeriodYears",{n:e}),value:q(t)}))).filter(e=>Number.isFinite(e.value)).sort((e,t)=>e.value-t.value);return t.map((e,a)=>{return{...e,color:e.color??J(a,t.length),text:`${e.label} · ${r=e.value,r>=100?r.toFixed(0):r>=10?r.toFixed(1):r.toFixed(2)}`};var r})}(r),u=((e,t)=>e.length>0&&Number.isFinite(t)&&t>=.9*e[0].value)(m,(s.median??[]).reduce((e,t)=>Number.isFinite(t)&&t>e?t:e,-1/0));return new e(i,{type:"line",data:{datasets:[{label:F("series.range"),data:ee(l,s.max),parsing:!1,fill:"+1",backgroundColor:I(G,.12),borderWidth:0,pointRadius:0,pointHitRadius:0,tension:.2},{label:"_min",data:ee(l,s.min),parsing:!1,fill:!1,borderWidth:0,pointRadius:0,pointHitRadius:0,tension:.2},{label:F("series.iqr"),data:ee(l,s.p75),parsing:!1,fill:"+1",backgroundColor:I(G,.25),borderWidth:0,pointRadius:0,pointHitRadius:0,tension:.2},{label:"_p25",data:ee(l,s.p25),parsing:!1,fill:!1,borderWidth:0,pointRadius:0,pointHitRadius:0,tension:.2},{label:F("series.ensembleMedian"),data:ee(l,s.median),parsing:!1,fill:!1,borderColor:G,borderWidth:2,pointRadius:0,pointHitRadius:6,tension:.2},...Q(m,{mode:o,firstX:d,lastX:c,hidden:!u})]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,interaction:{mode:"index",axis:"x",intersect:!1},plugins:{legend:{position:"right",labels:{color:z,boxWidth:12,font:{size:11},filter:e=>!e.text.startsWith("_")}},title:{display:!0,color:z,text:W("chart.forecastHydrograph",{riverId:n})},tooltip:{filter:e=>!e.dataset.rfsLevel,callbacks:{title:e=>new Date(e[0].parsed.x).toISOString().slice(0,16).replace("T"," ")+" UTC",label:e=>` ${e.dataset.label}: ${e.parsed.y.toFixed(2)} m³/s`}},zoom:{zoom:{drag:{enabled:!0,backgroundColor:I(G,.15),borderColor:I(G,.6),borderWidth:1},wheel:{enabled:!1},pinch:{enabled:!0},mode:"xy"},pan:{enabled:!0,mode:"xy",modifierKey:"shift"},limits:{x:{min:d,max:c}}}},scales:{x:{type:"time",time:{unit:"day",displayFormats:{day:"MMM d"}},min:d,max:c,title:{display:!0,text:F("axis.datetime"),color:Y},ticks:{color:Y,maxRotation:0},grid:{color:$}},y:{beginAtZero:!0,title:{display:!0,text:F("axis.discharge"),color:Y},grace:"5%",ticks:{color:Y},grid:{color:$}}}}})}let ae=[],re=[];const oe=e=>e.forEach(e=>e.destroy());function ie(){oe(ae),ae=[],oe(re),re=[]}function ne(){const e=[...ae,...re];if(0!==e.length){j(e[0].canvas);for(const t of e){for(const e of Object.values(t.options.scales??{}))e.title&&(e.title.color=Y),e.ticks&&(e.ticks.color=Y),e.grid&&(e.grid.color=$);const e=t.options.plugins??{};e.legend?.labels&&(e.legend.labels.color=z),e.title&&(e.title.color=z),t.update("none")}}}function le(e){const t=document.createElement("div");return t.className="plot-block",e.appendChild(t),t}async function se(t,a,{lang:r}={}){await R(r),oe(ae),ae=[],j(t),t.innerHTML="";const o=function(e){const{time:t,discharge:a}=e,r={};for(let e=0;e<t.length;e++){if(!Number.isFinite(a[e]))continue;const o=t[e].toISOString().slice(0,7);(r[o]??=[]).push(a[e])}const o=k([...a].filter(Number.isFinite).sort((e,t)=>e-t)),i=e=>Math.floor((e.getTime()-Date.UTC(e.getUTCFullYear(),0,0))/864e5),n={};for(let e=0;e<t.length;e++){const r=a[e];if(!Number.isFinite(r))continue;const o=t[e],l=o.getUTCFullYear();(!n[l]||r>n[l].peak)&&(n[l]={year:l,date:o,doy:i(o),peak:r})}const l=Object.values(n).sort((e,t)=>e.year-t.year),s={};for(const e of Object.keys(r))r[e].length<20?delete r[e]:s[e]=r[e].reduce((e,t)=>e+t,0)/r[e].length;const d=f.map(()=>[]),c=[],m={};for(const e of g){const t=Object.keys(r).filter(t=>t.endsWith(`-${e}`)).flatMap(e=>r[e]).sort((e,t)=>t-e);f.forEach((e,a)=>d[a].push(t[Math.floor(t.length*e/100)])),c.push({month:e,value:t.reduce((e,t)=>e+t,0)/t.length}),m[e]=k([...t].reverse())}const u=Array.from(new Set(Object.keys(r).map(e=>e.slice(0,4)))).sort(),p=[];for(const e of u){const t=Object.keys(s).filter(t=>t.startsWith(`${e}-`)).map(e=>s[e]);12===t.length&&p.push({year:+e,value:t.reduce((e,t)=>e+t,0)/12*31557600/1e6})}const h={};for(const{year:e,value:t}of p){const a=5*Math.floor(e/5);h[a]??={total:0,count:0},h[a].total+=t,h[a].count+=1}const y=Object.keys(h).map(Number).sort((e,t)=>e-t).map(e=>({period:e,average:h[e].total/h[e].count})),b=t[0].getUTCFullYear(),x=t[t.length-1].getUTCFullYear()+1-b,v=Array.from({length:x},(e,t)=>b+t),C=Array.from({length:x},()=>Array(366).fill(null));let M=b,A=0,w=-1;for(let e=0;e<t.length;e++){const r=t[e].getUTCFullYear();r!==M?(M=r,w=0,A+=1):w+=1,A<x&&w<366&&(C[A][w]=Number.isFinite(a[e])?a[e]:null)}const R={};for(let e=0;e<t.length;e++){const r=t[e],o=r.getUTCFullYear(),i=R[o]??={x:[],y:[]},n=i.y.length?i.y[i.y.length-1]:0;i.x.push(Date.UTC(2e3,r.getUTCMonth(),r.getUTCDate())),i.y.push(n+86400*(Number.isFinite(a[e])?a[e]:0))}return{fdc:o,monthlyFdc:m,monthlyAverages:c,monthlyStatus:d,monthlyAverageTimeseries:s,yearlyVolumes:p,fiveYearAverages:y,yearlyPeaks:l,raster:{years:v,z:C},cumulative:R}}(a);ae.push(function(t,a){const r=document.createElement("div");r.className="chart-tools",t.appendChild(r);const o=L(t),i=a.time.map((e,t)=>({x:e.getTime(),y:a.discharge[t]})).filter(e=>Number.isFinite(e.y)),n=i.length?i[0].x:0,l=i.length?i[i.length-1].x:n,s=new e(o,{type:"line",data:{datasets:[{label:F("series.dailyMean"),data:i,parsing:!1,borderColor:"#38bdf8",borderWidth:1,pointRadius:0,pointHitRadius:4,tension:0}]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,interaction:{mode:"index",intersect:!1},plugins:{legend:{display:!1},title:{display:!0,text:W("chart.dailyTimeseries",{riverId:a.riverId}),color:z},decimation:{enabled:!0,algorithm:"lttb",samples:600},tooltip:{callbacks:{title:e=>new Date(e[0].parsed.x).toISOString().slice(0,10),label:e=>` ${e.parsed.y.toFixed(2)} m³/s`}},zoom:{zoom:{drag:{enabled:!0,backgroundColor:"rgba(56,189,248,.15)",borderColor:"rgba(56,189,248,.6)",borderWidth:1},wheel:{enabled:!1},pinch:{enabled:!0},mode:"xy"},pan:{enabled:!0,mode:"xy",modifierKey:"shift"},limits:{x:{min:n,max:l}}}},scales:{x:{type:"time",time:{unit:"year"},min:Z(l,10,n),max:l,title:{display:!0,text:F("axis.datetime"),color:Y},ticks:{color:Y,maxRotation:0},grid:{color:$}},y:{title:{display:!0,text:F("axis.discharge"),color:Y},beginAtZero:!0,ticks:{color:Y},grid:{color:$}}}}}),d=e=>{const t=s.options.scales.x;t.min="all"===e?n:Z(l,e,n),t.max=l,s.update("none")},c=(e,t)=>{const a=document.createElement("button");return a.className="chart-btn",a.textContent=e,a.addEventListener("click",t),a};r.append(c(W("control.yearsShort",{n:1}),()=>d(1)),c(W("control.yearsShort",{n:5}),()=>d(5)),c(W("control.yearsShort",{n:10}),()=>d(10)),c(W("control.yearsShort",{n:30}),()=>d(30)),c(F("control.all"),()=>d("all")),c(F("control.resetZoom"),()=>s.resetZoom()));const m=document.createElement("span");return m.className="chart-hint",m.textContent=F("control.zoomHint"),r.appendChild(m),s}(le(t),a),function(t,a){const r=F("status").map((e,t)=>({label:e,data:a.monthlyStatus[t],borderWidth:0,pointRadius:0,backgroundColor:I(x[t],.5),fill:t<F("status").length-1?"+1":"origin"})),o=Array.from(new Set(Object.keys(a.monthlyAverageTimeseries).map(e=>e.slice(0,4)))).sort().slice(-2).reverse().map((e,t)=>({label:`Year ${e}`,borderColor:0===t?z:"#64748b",borderWidth:0===t?2:1.5,borderDash:0===t?[]:[6,4],pointRadius:0,fill:!1,data:F("months").map((t,r)=>a.monthlyAverageTimeseries[`${e}-${String(r+1).padStart(2,"0")}`]??null)}));return new e(L(t),{type:"line",data:{labels:F("months"),datasets:[...r,{label:F("series.monthlyAverage"),data:a.monthlyAverages.map(e=>e.value),borderColor:"#009dff",borderWidth:2,borderDash:[6,4],pointRadius:0,fill:!1},...o]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,interaction:{mode:"index",intersect:!1},plugins:E(F("chart.monthlyStatus")),scales:{x:U(F("axis.month")),y:U(F("axis.flow"),{beginAtZero:!0})}}})}(le(t),o),function(t,a){const r=e=>v.map((t,a)=>({x:t,y:e[a]})),o=F("months").map((e,t)=>({label:e,data:r(a.monthlyFdc[String(t+1).padStart(2,"0")]),borderColor:H[t%H.length],borderWidth:1,pointRadius:0,hidden:!0}));return new e(L(t),{type:"line",data:{datasets:[{label:F("series.allMonths"),data:r(a.fdc),borderColor:"#38bdf8",borderWidth:2,pointRadius:0},...o]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,parsing:!1,interaction:{mode:"nearest",intersect:!1},plugins:E(F("chart.flowDurationCurve")),scales:{x:U(F("axis.percentile"),{type:"linear",min:0,max:100}),y:U(F("axis.flow"),{beginAtZero:!0})}}})}(le(t),o),function(t,a){const r=a.yearlyVolumes.map(e=>e.year);return new e(L(t),{type:"line",data:{labels:r,datasets:[{label:F("series.annualVolume"),data:a.yearlyVolumes.map(e=>e.value),borderColor:"#00a6ff",borderWidth:2,pointRadius:2,tension:0},{label:F("series.fiveYearAverage"),data:r.map(e=>{const t=a.fiveYearAverages.find(t=>t.period===5*Math.floor(e/5));return t?t.average:null}),borderColor:"#ef4444",borderWidth:2,pointRadius:0,stepped:!0}]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,interaction:{mode:"index",intersect:!1},plugins:E(F("chart.yearlyVolumes")),scales:{x:U(F("axis.year")),y:U(F("axis.volume"),{beginAtZero:!0})}}})}(le(t),o),_(le(t),o),X(le(t),o),function(t,a){const r=(new Date).getUTCFullYear(),o=Object.entries(a.cumulative).map(([e,t])=>({year:+e,total:t.y[t.y.length-1]})).filter(e=>e.year<r).sort((e,t)=>e.total-t.total),i=o[0]?.year,n=o[o.length-1]?.year,l=o[Math.floor(o.length/2)]?.year,s={};null!=n&&(s[n]={color:"#3b82f6",name:`Wettest: ${n}`}),null!=i&&(s[i]={color:"#ef4444",name:`Driest: ${i}`}),null!=l&&(s[l]={color:"#22c55e",name:`Median: ${l}`});const d=Object.entries(a.cumulative).map(([e,t])=>{const a=s[+e];return{label:a?a.name:String(e),data:t.x.map((e,a)=>({x:e,y:t.y[a]/1e6})),borderColor:a?a.color:"rgba(148,163,184,.35)",borderWidth:a?2:.8,pointRadius:0,fill:!1,order:a?0:1,_hl:null!=a}});return new e(L(t),{type:"line",data:{datasets:d},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,parsing:!1,interaction:{mode:"nearest",intersect:!1},plugins:{title:{display:!0,text:F("chart.cumulativeVolume"),color:z},legend:{display:!0,labels:{color:z,boxWidth:12,font:{size:11},filter:(e,t)=>!0===t.datasets[e.datasetIndex]._hl}}},scales:{x:U(F("axis.month"),{type:"time",time:{unit:"month",displayFormats:{month:"MMM"}}}),y:U(F("axis.cumulativeVolume"),{beginAtZero:!0})}}})}(le(t),o))}async function de(e,t,{lang:a,returnPeriods:r,levelsAs:o}={}){await R(a),oe(re),re=[],j(e),e.innerHTML="",re.push(te(le(e),t,{returnPeriods:r,levelsAs:o}))}export{S as availableLocales,ie as clearPlots,de as plotAllForecast,se as plotAllRetro,ne as restyleCharts,R as useLocale};
package/package.json CHANGED
@@ -1,26 +1,66 @@
1
1
  {
2
2
  "name": "riverforecastsystem",
3
- "version": "0.0.3",
3
+ "version": "0.4.0",
4
4
  "description": "Client for reading GEOGLOWS RFS data from publicly archived Zarr data on S3.",
5
- "license": "ISC",
5
+ "license": "BSD-3-Clause-Clear",
6
6
  "author": "Riley Hales",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/river-forecast-system/js-riverforecastsystem.git"
10
+ },
11
+ "homepage": "https://github.com/river-forecast-system/js-riverforecastsystem#readme",
12
+ "bugs": "https://github.com/river-forecast-system/js-riverforecastsystem/issues",
7
13
  "type": "module",
8
14
  "sideEffects": false,
9
- "main": "dist/index.js",
15
+ "main": "dist/index.esm.js",
10
16
  "module": "dist/index.esm.js",
17
+ "exports": {
18
+ ".": "./dist/index.esm.js",
19
+ "./v2": "./dist/v2/index.esm.js",
20
+ "./v3": "./dist/v3/index.esm.js",
21
+ "./v3/discharge": "./dist/v3/discharge.esm.js",
22
+ "./v3/floodmaps": "./dist/v3/floodmaps.esm.js",
23
+ "./v3/hydrography": "./dist/v3/hydrography.esm.js",
24
+ "./v3/plots": "./dist/v3/plots.esm.js"
25
+ },
11
26
  "scripts": {
12
- "test": "node test/test.js",
27
+ "test": "vitest run",
28
+ "test:live": "node test/tests.js",
13
29
  "build": "rm -rf dist && rollup -c rollup.config.js",
14
- "deploy": "npm run build && npm publish --access public"
30
+ "prepare": "npm run build"
31
+ },
32
+ "peerDependencies": {
33
+ "chart.js": "^4.5.1",
34
+ "chartjs-adapter-date-fns": "^3.0.0",
35
+ "chartjs-chart-matrix": "^3.0.5",
36
+ "chartjs-plugin-zoom": "^2.2.0",
37
+ "date-fns": "^4.4.0",
38
+ "numcodecs": "^0.3.2"
15
39
  },
16
- "dependencies": {
17
- "zarrita": "^0.5.4"
40
+ "peerDependenciesMeta": {
41
+ "chart.js": {
42
+ "optional": true
43
+ },
44
+ "chartjs-adapter-date-fns": {
45
+ "optional": true
46
+ },
47
+ "chartjs-chart-matrix": {
48
+ "optional": true
49
+ },
50
+ "chartjs-plugin-zoom": {
51
+ "optional": true
52
+ },
53
+ "date-fns": {
54
+ "optional": true
55
+ }
18
56
  },
19
57
  "devDependencies": {
20
58
  "@rollup/plugin-commonjs": "^29.0.0",
21
59
  "@rollup/plugin-node-resolve": "^16.0.3",
22
- "@rollup/plugin-terser": "^0.4.4",
23
- "rollup": "^4.53.3"
60
+ "@rollup/plugin-terser": "^1.0.0",
61
+ "rollup": "4.63.1",
62
+ "vitest": "^4.1.10",
63
+ "zarrita": "^0.7.3"
24
64
  },
25
65
  "files": [
26
66
  "dist"