@latticexyz/utils 2.0.0-alpha.1.69 → 2.0.0-alpha.1.71

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/dist/index.js CHANGED
@@ -1,285 +1,4 @@
1
- import { reaction, computed, toJS, observable, runInAction } from 'mobx';
2
- import DeepProxy from 'proxy-deep';
3
- import { pipe, filter, concatMap, timestamp, scan, mergeMap, of, delay, ReplaySubject, first, fromEvent, map } from 'rxjs';
4
- import { BigNumber } from 'ethers';
5
- import { keccak256 as keccak256$1, toUtf8Bytes, defaultAbiCoder } from 'ethers/lib/utils.js';
6
-
7
- /**
8
- * TypeScript type guard to assert the type of a non-empty array
9
- * @param array Any array to check for non-emptiness
10
- * @returns True if the empty is non-empty, else false. TypeScript accepts the array as non-empty after the assertion.
11
- */
12
- function isNotEmpty(array) {
13
- if (array.length === 0)
14
- return false;
15
- return true;
16
- }
17
- /**
18
- * Filters undefined values from an array and lets TypeScript know the resulting array
19
- * does not have undefined values
20
- * @param array Array potentially including undefined values
21
- * @returns Array without undefined values
22
- */
23
- function filterNullishValues(array) {
24
- return array.filter((value) => value != null);
25
- }
26
-
27
- /**
28
- * A convenient way to create a promise with resolve and reject functions.
29
- * @returns Tuple with resolve function, reject function and promise.
30
- */
31
- function deferred() {
32
- let resolve = null;
33
- let reject = null;
34
- const promise = new Promise((r, rj) => {
35
- resolve = (t) => r(t);
36
- reject = (e) => rj(e);
37
- });
38
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
- return [resolve, reject, promise];
40
- }
41
-
42
- /**
43
- * @param comp Computed/Observable value that is either defined or undefined
44
- * @returns promise that resolves with the first truthy computed value
45
- */
46
- async function awaitValue(comp) {
47
- const [resolve, , promise] = deferred();
48
- const dispose = reaction(() => comp.get(), (value) => {
49
- if (value) {
50
- resolve(value);
51
- }
52
- }, { fireImmediately: true });
53
- const value = await promise;
54
- // Dispose the reaction once the promise is resolved
55
- dispose();
56
- return value;
57
- }
58
-
59
- function isObject(c) {
60
- return typeof c === "object" && !Array.isArray(c) && c !== null;
61
- }
62
- function isFunction(c) {
63
- return c instanceof Function;
64
- }
65
-
66
- /* eslint-disable @typescript-eslint/no-explicit-any */
67
- function deepAccess(target, path) {
68
- if (path.length === 0)
69
- return target;
70
- if (path.length === 1)
71
- return target[path[0]];
72
- const [next, ...rest] = path;
73
- const nextTarget = target[next];
74
- if (!isObject(nextTarget))
75
- throw new Error("Path does not exist on the target");
76
- return deepAccess(nextTarget, rest);
77
- }
78
- /**
79
- * Caches any function calls to the target until the target is ready.
80
- * @param target T extends Cachable
81
- * @returns Cached<T>
82
- */
83
- function cacheUntilReady(target) {
84
- // The call queue contains the path and arguments of calls to the
85
- // proxiedTarget while the target was not available yet.
86
- // It also contains resolve and reject methods to fulfil the promise
87
- // returned when calling the proxiedTarget once the target becomes available.
88
- const callQueue = [];
89
- // The proxiedTarget proxies all calls to the target.
90
- // If a function is called on the proxiedTarget while the target is not
91
- // available, a promise is returned and the call will be stored in the callQueue
92
- // until the target becomes available and the promise is fulfilled.
93
- const proxiedTarget = new DeepProxy({}, {
94
- get(_t, prop) {
95
- const targetReady = target.get();
96
- if (targetReady) {
97
- // If the target is ready, relay all calls directly to the target
98
- // (Except for the "proxied" key, which indicates whether the object is currently proxied)
99
- if (prop === "proxied")
100
- return false;
101
- return Reflect.get(targetReady, prop);
102
- }
103
- else {
104
- // Note: if the target is not available, accessing a property returns another proxy,
105
- // not a Promise. It is possible to check whether a value is currently proxied using the proxied key.
106
- if (prop === "proxied")
107
- return true;
108
- if (prop === "name")
109
- return "ProxiedTarget";
110
- if (prop === "toJSON")
111
- return () => ({ proxied: true });
112
- return this.nest(() => void 0);
113
- }
114
- },
115
- apply(_, thisArg, args) {
116
- const targetReady = target.get();
117
- if (targetReady) {
118
- // If the target is ready, relay all calls directly to the target
119
- const targetFunc = deepAccess(targetReady, this.path);
120
- if (!isFunction(targetFunc))
121
- throw new Error("Target is not callable");
122
- return Reflect.apply(targetFunc, thisArg, args);
123
- }
124
- else {
125
- // Otherwise store the call and relay it to the target later once it's ready.
126
- // The return value of this call is a promise, that gets resolved once the target is ready.
127
- const [resolve, reject, promise] = deferred();
128
- callQueue.push({ path: this.path, args, resolve, reject });
129
- return promise;
130
- }
131
- },
132
- });
133
- reaction(() => target.get(), (targetReady) => {
134
- if (!targetReady)
135
- return;
136
- // Move all entries from callQueue to queuedCalls
137
- const queuedCalls = callQueue.splice(0);
138
- for (const { path, args, resolve, reject } of queuedCalls) {
139
- const target = deepAccess(targetReady, path);
140
- if (args && isFunction(target)) {
141
- (async () => {
142
- try {
143
- resolve(await target(...args));
144
- }
145
- catch (e) {
146
- reject(e);
147
- }
148
- })();
149
- }
150
- else {
151
- resolve(target);
152
- }
153
- }
154
- });
155
- return proxiedTarget;
156
- }
157
-
158
- /**
159
- * @param enm Numeric enum
160
- * @returns Number array containing the enum values
161
- */
162
- function numValues(enm) {
163
- const nums = [];
164
- for (const val of Object.values(enm)) {
165
- if (!isNaN(Number(val))) {
166
- nums.push(Number(val));
167
- }
168
- }
169
- return nums;
170
- }
171
-
172
- /**
173
- * Utility function to map a source object to an object with the same keys but mapped values
174
- * @param source Source object to be mapped
175
- * @param valueMap Mapping values of the source object to values of the target object
176
- * @returns An object with the same keys as the source object but mapped values
177
- */
178
- function mapObject(source, valueMap) {
179
- const target = {};
180
- for (const key in source) {
181
- target[key] = valueMap(source[key], key);
182
- }
183
- return target;
184
- }
185
-
186
- /**
187
- *
188
- * @param to Upper bound (included)
189
- * @param from Lower bound (included). Default 0.
190
- * @returns A random integer between from and to.
191
- */
192
- function random(to, from = 0) {
193
- return Math.floor(Math.random() * (to - from + 1)) + from;
194
- }
195
- /**
196
- * @param array Array to pick a random element from.
197
- * @returns Random element from the given array.
198
- */
199
- function pickRandom(array) {
200
- return array[random(array.length - 1)];
201
- }
202
-
203
- function filterNullish() {
204
- return pipe(filter((x) => x != null));
205
- }
206
- function awaitPromise() {
207
- return pipe(concatMap((x) => x));
208
- }
209
- /**
210
- * RxJS operator to stretch out an event stream by a given delay per event
211
- * @param spacingDelayMs Delay between each event in ms
212
- * @returns stream of events with at least spacingDelayMs spaceing between event
213
- */
214
- function stretch(spacingDelayMs) {
215
- return pipe(timestamp(), scan((acc, curr) => {
216
- // calculate delay needed to offset next emission
217
- let delay = 0;
218
- if (acc !== null) {
219
- const timeDelta = curr.timestamp - acc.timestamp;
220
- delay = timeDelta > spacingDelayMs ? 0 : spacingDelayMs - timeDelta;
221
- }
222
- return {
223
- timestamp: curr.timestamp,
224
- delay: delay,
225
- value: curr.value,
226
- };
227
- }, null), filterNullish(), mergeMap((i) => of(i.value).pipe(delay(i.delay)), 1));
228
- }
229
- function observableToComputed(obs) {
230
- return computed(() => obs.get());
231
- }
232
- function computedToStream(comp) {
233
- const stream = new ReplaySubject(1);
234
- reaction(() => comp.get(), (value) => {
235
- if (value != null)
236
- stream.next(value);
237
- }, { fireImmediately: true });
238
- return stream;
239
- }
240
- function observableToStream(obs) {
241
- const stream = new ReplaySubject(1);
242
- reaction(() => toJS(obs), (value) => {
243
- if (value != null)
244
- stream.next(value);
245
- }, { fireImmediately: true });
246
- return stream;
247
- }
248
- function streamToComputed(stream$) {
249
- const value = observable.box();
250
- stream$.subscribe((val) => runInAction(() => value.set(val)));
251
- return computed(() => value.get());
252
- }
253
- async function streamToDefinedComputed(stream$) {
254
- const value = observable.box();
255
- stream$.subscribe((val) => runInAction(() => value.set(val)));
256
- const computedValue = computed(() => value.get());
257
- await awaitValue(computedValue);
258
- return computedValue;
259
- }
260
- /**
261
- *
262
- * @param stream$ RxJS observable to check for the given value
263
- * @param predicate Predicate to check
264
- * @returns A promise that resolves with the requested value once the predicate is true
265
- */
266
- async function awaitStreamValue(stream$, predicate = (value) => value != null) {
267
- const [resolve, , promise] = deferred();
268
- stream$.pipe(first(predicate)).subscribe(resolve);
269
- return promise;
270
- }
271
- /**
272
- * Turns a stream into an updating object for easy access outside of rxjs
273
- * @param stream$ Stream to turn into a wrapped value
274
- * @returns Object with `current` key corresponding to last stream value
275
- */
276
- async function streamToWrappedValue(stream$) {
277
- const value = {};
278
- stream$.subscribe((v) => (value.current = v));
279
- value.current = await awaitStreamValue(stream$);
280
- return value;
281
- }
282
-
1
+ function Vr(r){return r.length!==0}function Or(r){return r.filter(e=>e!=null)}function p(){let r=null,e=null,t=new Promise((n,o)=>{r=i=>n(i),e=i=>o(i)});return[r,e,t]}import{reaction as rr}from"mobx";async function P(r){let[e,,t]=p(),n=rr(()=>r.get(),i=>{i&&e(i)},{fireImmediately:!0}),o=await t;return n(),o}function j(r){return typeof r=="object"&&!Array.isArray(r)&&r!==null}function U(r){return r instanceof Function}import{reaction as er}from"mobx";import tr from"proxy-deep";function E(r,e){if(e.length===0)return r;if(e.length===1)return r[e[0]];let[t,...n]=e,o=r[t];if(!j(o))throw new Error("Path does not exist on the target");return E(o,n)}function Wr(r){let e=[],t=new tr({},{get(n,o){let i=r.get();return i?o==="proxied"?!1:Reflect.get(i,o):o==="proxied"?!0:o==="name"?"ProxiedTarget":o==="toJSON"?()=>({proxied:!0}):this.nest(()=>{})},apply(n,o,i){let a=r.get();if(a){let s=E(a,this.path);if(!U(s))throw new Error("Target is not callable");return Reflect.apply(s,o,i)}else{let[s,l,u]=p();return e.push({path:this.path,args:i,resolve:s,reject:l}),u}}});return er(()=>r.get(),n=>{if(!n)return;let o=e.splice(0);for(let{path:i,args:a,resolve:s,reject:l}of o){let u=E(n,i);a&&U(u)?(async()=>{try{s(await u(...a))}catch(f){l(f)}})():s(u)}}),t}function Xr(r){let e=[];for(let t of Object.values(r))isNaN(Number(t))||e.push(Number(t));return e}function Kr(r,e){let t={};for(let n in r)t[n]=e(r[n],n);return t}function nr(r,e=0){return Math.floor(Math.random()*(r-e+1))+e}function Gr(r){return r[nr(r.length-1)]}import{concatMap as or,delay as ir,filter as sr,first as ar,mergeMap as ur,of as lr,pipe as M,ReplaySubject as _,scan as mr,timestamp as cr}from"rxjs";import{computed as N,observable as D,reaction as H,runInAction as Y,toJS as fr}from"mobx";function pr(){return M(sr(r=>r!=null))}function ae(){return M(or(r=>r))}function ue(r){return M(cr(),mr((e,t)=>{let n=0;if(e!==null){let o=t.timestamp-e.timestamp;n=o>r?0:r-o}return{timestamp:t.timestamp,delay:n,value:t.value}},null),pr(),ur(e=>lr(e.value).pipe(ir(e.delay)),1))}function le(r){return N(()=>r.get())}function me(r){let e=new _(1);return H(()=>r.get(),t=>{t!=null&&e.next(t)},{fireImmediately:!0}),e}function ce(r){let e=new _(1);return H(()=>fr(r),t=>{t!=null&&e.next(t)},{fireImmediately:!0}),e}function fe(r){let e=D.box();return r.subscribe(t=>Y(()=>e.set(t))),N(()=>e.get())}async function pe(r){let e=D.box();r.subscribe(n=>Y(()=>e.set(n)));let t=N(()=>e.get());return await P(t),t}async function dr(r,e=t=>t!=null){let[t,,n]=p();return r.pipe(ar(e)).subscribe(t),n}async function de(r){let e={};return r.subscribe(t=>e.current=t),e.current=await dr(r),e}var Te=function(){let r=xr,e=Tr;return e(r(32),8)+"-"+e(r(16),4)+"-"+e(16384|r(12),4)+"-"+e(32768|r(14),4)+"-"+e(r(48),12)},xr=function(r){if(r<0||r>53)return NaN;let e=0|Math.random()*1073741824;return r>30?e+(0|Math.random()*(1<<r-30))*1073741824:e>>>30-r},Tr=function(r,e){let t=r.toString(16),n=e-t.length,o="0";for(;n>0;n>>>=1,o+=o)n&1&&(t=o+t);return t};function R(r,e){return new Promise(t=>setTimeout(()=>t(e),r))}var Ae=function*(r=0,e=1,t=0){for(let n=0;n<r;yield t+n++*e);};async function br(r,e){throw await R(r),new Error(e)}var we=async(r,e,t)=>Promise.race([r,br(e,t)]),Ce=(r,e=[],t=10,n=1e3)=>{let[o,i,a]=p();return(async()=>{let l;for(let u=0;u<t;u++)try{l=await r(...e),o(l);break}catch(f){u<t-1?(console.info("[CallWithRetry Failed] attempt number="+u,r),console.error(f),await R(Math.min(n*2**u+Math.random()*100,15e3))):i(f)}})(),a};function h(r){return{...r,[Symbol.iterator](){return this}}}function ve(r,e){return h(e?{next(){let t=r.next();return t.done?e.next():t}}:r)}function Se(r,e){return h({next(){let n=r.next(),o=e.next();return n.done&&o.done?{done:!0,value:null}:{value:[n.value,o.value]}}})}function v(r,e){return h({next(){let{done:t,value:n}=r.next();return{done:t,value:t?n:e(n)}}})}function ke(r){let e=0;return h({next(){let n=e>=r.length;return n?{done:n,value:null}:{value:r[e++]}}})}function Oe(r,e){return e.x>=r.x&&e.y>=r.y&&e.x<r.x+r.width&&e.y<r.y+r.height}function Ue(r){let e=[];for(let t=0;t<r.width;t++)for(let n=0;n<r.height;n++)e.push({x:r.x+t,y:r.y+n});return e}import{BigNumber as gr}from"ethers";import{keccak256 as W,toUtf8Bytes as yr}from"ethers/lib/utils.js";import{defaultAbiCoder as hr}from"ethers/lib/utils.js";function Be(r){return gr.from(W(yr(r))).toHexString()}function Fe(r){let e=hr.encode(["int32","int32"],[r.x,r.y]);return W(e)}import{fromEvent as J,map as X}from"rxjs";function _e(r,e){return e.subscribe(t=>r.postMessage(t)),J(r,"message").pipe(X(t=>t.data))}function De(r){let e=J(self,"message");r.work(e.pipe(X(n=>n.data))).subscribe(n=>self.postMessage(n))}function Ar(r,e){return r&2**e-1}function wr(r,e){if(e.reduce((n,o)=>n+o,0)>32)throw new Error("JS pretends integers are 32 bit when bitshifts are involved");if(r.length!==e.length)throw new Error("Arrays' lengths must match");for(let n=0;n<r.length;n++){if(r[n]<0)throw new Error("Underflow: can only pack unsigned integer");if(r[n]>2**e[n]-1){let o=`Overflow: ${r[n]} does not fit in ${e[n]} bits`;throw new Error(o)}}let t=0;for(let n=0;n<r.length;n++)t=t<<e[n]|r[n];return t}function Cr(r,e){let t=[],n=r;for(let o=e.length-1;o>=0;o--)t.unshift(Ar(n,e[o])),n=n>>>e[o];return t}function Ye(r){return wr(r,[8,24])}function We(r){return Cr(r,[8,24])}var Ir=2**16-1,A=2**15-1;function ze(r,e){let t=new w;for(let n of r.coords())e.get(n)||t.set(n,!0);return t}function S(r){return r.x<<16|r.y&Ir}function z(r){let e=r>>16,t=r<<16>>16;return{x:e,y:t}}var w=class{map;defaultValue;constructor(e){this.map=new Map,this.defaultValue=e?.defaultValue}static from(e){let t=new w;return t.map=e.map,t.defaultValue=e.defaultValue,t}set(e,t){if(e.x>A||e.x<-1*A||e.y>A||e.y<-1*A)throw new Error(`CoordMap only supports coords up to ${A}`);return this.map.set(S(e),t)}get(e){return this.map.get(S(e))??this.defaultValue}keys(){return this.map.keys()}coords(){return v(this.map.keys(),e=>z(e))}entries(){return this.map.entries()}toArray(){return Array.from(this.map.entries()).map(([t,n])=>[z(t),n])}values(){return this.map.values()}delete(e){return this.map.delete(S(e))}has(e){return this.map.has(S(e))}clear(){for(let e of this.map.keys())this.map.delete(e)}get size(){return this.map.size}};function k(r){return`${r.x}/${r.y}/${r.z}`}function K(r){let e=r.split("/");return{x:Number(e[0]),y:Number(e[1]),z:Number(e[2])}}var V=class{map;defaultValue;constructor(e){this.map=new Map,this.defaultValue=e?.defaultValue}static from(e){let t=new V;return t.map=e.map,t.defaultValue=e.defaultValue,t}set(e,t){return this.map.set(k(e),t)}get(e){return this.map.get(k(e))??this.defaultValue}keys(){return this.map.keys()}coords(){return v(this.map.keys(),e=>K(e))}entries(){return this.map.entries()}toArray(){return Array.from(this.map.entries()).map(([t,n])=>[K(t),n])}values(){return this.map.values()}delete(e){return this.map.delete(k(e))}has(e){return this.map.has(k(e))}clear(){for(let e of this.map.keys())this.map.delete(e)}get size(){return this.map.size}};function L(r,e){r.substring(0,2)=="0x"&&(r=r.substring(2));let t=e/4;return r=r.padStart(t,"0"),r=r.substring(r.length-t),`0x${r}`}function G(r){return L(r,160)}function qe(r){return L(r,256)}function Qe(r){if(r[0]!=="0"&&r[1]!=="x")throw new Error("Invalid hex string");return"0x"+r.substring(10)}function d(r,e,t){return(((e^t)*134775813^r+e)*(1103515245*e<<16^1103515245*t-134775813)>>>0)/4294967295}function c(r,e){if(r<0)for(;r<0;)r+=e;return r%e}function B(r,e,t,n,o,i,a){let s=n-t-(r-e);return(e*Math.pow(i,3)+o*(t*Math.pow(i,2)+r*i*(-i+o)+o*(-(e+s)*i+s*o)))*a}function rt(r,e,t,n=Number.MAX_SAFE_INTEGER,o=Number.MAX_SAFE_INTEGER){return{seed:Math.floor(r*Number.MAX_SAFE_INTEGER),periodX:n,periodY:o,octave:e,scale:t}}function et(r,e){let t=Math.floor(e),n=e-t;return B(d(r.seed,c(t-1,r.periodX),0),d(r.seed,c(t,r.periodX),0),d(r.seed,c(t+1,r.periodX),0),d(r.seed,c(t+2,r.periodX),0),n,1,1)*.666666+.166666}function tt({octave:r,periodX:e,periodY:t,seed:n,scale:o},i,a){let s=Math.floor(i/r),l=Math.floor(i*1e3/r)-s*1e3,u=Math.floor(a/r),f=Math.floor(a*1e3/r)-u*1e3,b=c(s-1,e),m=c(s,e),g=c(s+1,e),Z=c(s+2,e),y=new Array(4);for(let C=0;C<4;++C){let I=c(u-1+C,t);y[C]=B(d(n,b,I),d(n,m,I),d(n,g,I),d(n,Z,I),l,1e3,1)}return Math.floor(B(y[0],y[1],y[2],y[3],f,1e3,o)/Math.pow(1e3,6))}var x="mud-logger-topics";function ot(){let r=window.console,e=!!localStorage.getItem(x),t=localStorage.getItem(x),n=t?JSON.parse(t):[];function o(...m){e||r.log(...m)}function i(m,...g){(!e||n.includes(m))&&(r.log(`--- BETTER CONSOLE / TOPIC ${m} ---`),r.log(...g))}function a(){localStorage.setItem(x,JSON.stringify([])),e=!0}function s(){localStorage.removeItem(x),e=!1}function l(m){n.push(m),localStorage.setItem(x,JSON.stringify(n))}function u(m){n=n.filter(g=>g!==m),localStorage.setItem(x,JSON.stringify(n))}function f(){n=[],localStorage.setItem(x,JSON.stringify(n))}let b={...r,log:o,logWithTopic:i,enableFilters:a,disableFilters:s,addTopic:l,removeTopic:u,resetTopics:f};return window.logger=b,window.console=b,b}function st(r,e){if(r.length!==e.length)throw new Error("points must have same dimension");return Math.sqrt(r.reduce((t,n,o)=>t+Math.pow(r[o]-e[o],2),0))}function ut(r){return(r<0?-1:1)*Math.floor(Math.abs(r))}var q=r=>`0x${[...new Uint8Array(r)].map(e=>e.toString(16).padStart(2,"0")).join("")}`;var F=r=>[...r].map(e=>String.fromCharCode(e)).join("");function Q(r){return/^(0x)?([\da-f]{2})*$/i.test(r)}var O=r=>{if(!Q(r))throw console.error("Invalid hex string",r),new Error("Invalid hex string");let e=r.match(/[\da-f]{2}/gi);return e?new Uint8Array(e.map(t=>parseInt(t,16))):new Uint8Array([])};function xt(r){return r!==void 0}function bt(r){return r!==null}var $=r=>{if(r.length>16)throw new Error("string too long");return new Uint8Array(16).map((e,t)=>r.charCodeAt(t))};var T=class{namespace;name;constructor(e,t){this.namespace=e,this.name=t}toString(){return`TableId<${this.namespace||"[empty]"}:${this.name||"[empty]"}>`}toHexString(){return T.toHexString(this.namespace,this.name)}static toHexString(e,t){let n=new Uint8Array(32);return n.set($(e),0),n.set($(t),16),q(n)}static fromHexString(e){return T.fromBytes32(O(e))}static fromBytes32(e){let t=new Uint8Array(32);t.set(e);let n=F(t.slice(0,16)).replace(/\0+$/,""),o=F(t.slice(16,32)).replace(/\0+$/,"");return new T(n,o)}static parse(e){let t=e.match(/^TableId<(.+?):(.+?)>$/);if(!t)return null;let[,n,o]=t;return new T(n==="[empty]"?"":n,o==="[empty]"?"":o)}};function vr(r){return r.substring(0,2)=="0x"&&(r=r.substring(2)),(r.length%2!==0?"0x0":"0x")+r}function Sr(r){return O(r)}function Ft(r){return r.length===0?"0x00":vr(r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),""))}function $t(...r){return Uint8Array.from(r.reduce((e,t)=>[...e,...t],[]))}function Pt(r,e){let t=[],n=0;for(let o of e){let i=new Uint8Array(o);t.push(i);for(let a=0;a<o;a++)i[a]=r[n],n++}return t}function jt(r){let e=new ArrayBuffer(r.length*4),t=new Int32Array(e);for(let n=0;n<r.length;n++)t[n]=r[n];return new Uint8Array(e)}function _t(r){return[...new Int32Array(r.buffer)]}function Dt(r){return Sr(G(r))}function kr(r){if(r<2)throw new Error("Minimum size is 2");if(r>64)throw new Error("Maximum size is 64");let e=2**(r-1)-1,t=-e-1;return n=>{if(n=n<<0,n>e||n<t)throw console.log("value",n,e,t,n>e,n<t),new Error(`Int${r} overflow`);return n<0?2**r+n:n}}var Ht=kr(32);export{w as CoordMap,jt as Int32ArrayToUint8Array,T as TableId,Ft as Uint8ArrayToHexString,_t as Uint8ArrayToInt32Array,V as VoxelCoordMap,Oe as areaContains,q as arrayToHex,ke as arrayToIterator,ae as awaitPromise,dr as awaitStreamValue,P as awaitValue,F as bytesToString,Wr as cacheUntilReady,Ce as callWithRetry,me as computedToStream,ve as concatIterators,$t as concatUint8Arrays,S as coordToKey,Ue as coordsOf,kr as createToInt,rt as cubicNoiseConfig,et as cubicNoiseSample1,tt as cubicNoiseSample2,p as deferred,ot as enableLogger,Dt as ethAddressToUint8Array,st as euclidean,Qe as extractEncodedArguments,pr as filterNullish,Or as filterNullishValues,vr as formatHex,_e as fromWorker,Sr as hexStringToUint8Array,O as hexToArray,B as interpolate,xt as isDefined,U as isFunction,Q as isHex,Vr as isNotEmpty,bt as isNotNull,j as isObject,Be as keccak256,Fe as keccak256Coord,z as keyToCoord,h as makeIterable,Kr as mapObject,Se as mergeIterators,Xr as numValues,le as observableToComputed,ce as observableToStream,wr as pack,Ye as packTuple,L as padToBitLength,Gr as pickRandom,nr as random,d as randomize,Ae as range,br as rejectAfter,ut as roundTowardsZero,De as runWorker,R as sleep,Pt as splitUint8Arrays,fe as streamToComputed,pe as streamToDefinedComputed,de as streamToWrappedValue,ue as stretch,$ as stringToBytes16,ze as subtract,c as tile,we as timeoutAfter,qe as to256BitString,G as toEthAddress,Ht as toInt32,v as transformIterator,Cr as unpack,We as unpackTuple,Te as uuid};
283
2
  /**
284
3
  * UUID.core.js - UUID.js for Minimalists
285
4
  *
@@ -289,728 +8,4 @@ async function streamToWrappedValue(stream$) {
289
8
  * @license Apache License 2.0: Copyright (c) 2010-2018 LiosK
290
9
  * @url https://github.com/LiosK/UUID.js/blob/master/src/uuid.core.js
291
10
  */
292
- /**
293
- * @class
294
- * @classdesc {@link UUID} object.
295
- * @hideconstructor
296
- */
297
- // Core Component {{{
298
- /**
299
- * Generates a version 4 UUID as a hexadecimal string.
300
- * @returns {string} Hexadecimal UUID string.
301
- */
302
- const uuid = function () {
303
- const rand = _getRandomInt, hex = _hexAligner;
304
- return (hex(rand(32), 8) + // time_low
305
- "-" +
306
- hex(rand(16), 4) + // time_mid
307
- "-" +
308
- hex(0x4000 | rand(12), 4) + // time_hi_and_version
309
- "-" +
310
- hex(0x8000 | rand(14), 4) + // clock_seq_hi_and_reserved clock_seq_low
311
- "-" +
312
- hex(rand(48), 12)); // node
313
- };
314
- /**
315
- * Returns an unsigned x-bit random integer.
316
- * @private
317
- * @param {number} x Unsigned integer ranging from 0 to 53, inclusive.
318
- * @returns {number} Unsigned x-bit random integer (0 <= f(x) < 2^x).
319
- */
320
- const _getRandomInt = function (x) {
321
- if (x < 0 || x > 53) {
322
- return NaN;
323
- }
324
- const n = 0 | (Math.random() * 0x40000000); // 1 << 30
325
- return x > 30 ? n + (0 | (Math.random() * (1 << (x - 30)))) * 0x40000000 : n >>> (30 - x);
326
- };
327
- /**
328
- * Converts an integer to a zero-filled hexadecimal string.
329
- * @private
330
- * @param {number} num
331
- * @param {number} length
332
- * @returns {string}
333
- */
334
- const _hexAligner = function (num, length) {
335
- let str = num.toString(16), i = length - str.length, z = "0";
336
- for (; i > 0; i >>>= 1, z += z) {
337
- if (i & 1) {
338
- str = z + str;
339
- }
340
- }
341
- return str;
342
- };
343
-
344
- function sleep(timeout, returns) {
345
- return new Promise((resolve) => setTimeout(() => resolve(returns), timeout));
346
- }
347
-
348
- /* eslint-disable @typescript-eslint/no-explicit-any */
349
- const range = function* (total = 0, step = 1, from = 0) {
350
- // eslint-disable-next-line no-empty
351
- for (let i = 0; i < total; yield from + i++ * step) { }
352
- };
353
- async function rejectAfter(ms, msg) {
354
- await sleep(ms);
355
- throw new Error(msg);
356
- }
357
- const timeoutAfter = async (promise, ms, timeoutMsg) => {
358
- return Promise.race([promise, rejectAfter(ms, timeoutMsg)]);
359
- };
360
- const callWithRetry = (fn, args = [], maxRetries = 10, retryInterval = 1000) => {
361
- const [resolve, reject, promise] = deferred();
362
- const process = async () => {
363
- let res;
364
- for (let i = 0; i < maxRetries; i++) {
365
- try {
366
- res = await fn(...args);
367
- resolve(res);
368
- break;
369
- }
370
- catch (e) {
371
- if (i < maxRetries - 1) {
372
- console.info("[CallWithRetry Failed] attempt number=" + i, fn);
373
- console.error(e);
374
- await sleep(Math.min(retryInterval * 2 ** i + Math.random() * 100, 15000));
375
- }
376
- else {
377
- reject(e);
378
- }
379
- }
380
- }
381
- };
382
- process();
383
- return promise;
384
- };
385
-
386
- function makeIterable(iterator) {
387
- const iterable = {
388
- ...iterator,
389
- [Symbol.iterator]() {
390
- return this;
391
- },
392
- };
393
- return iterable;
394
- }
395
- function concatIterators(first, second) {
396
- if (!second)
397
- return makeIterable(first);
398
- return makeIterable({
399
- next() {
400
- const next = first.next();
401
- if (!next.done)
402
- return next;
403
- return second.next();
404
- },
405
- });
406
- }
407
- function mergeIterators(iteratorA, iteratorB) {
408
- const iterator = {
409
- next() {
410
- const nextA = iteratorA.next();
411
- const nextB = iteratorB.next();
412
- if (nextA.done && nextB.done)
413
- return { done: true, value: null };
414
- return { value: [nextA.value, nextB.value] };
415
- },
416
- };
417
- return makeIterable(iterator);
418
- }
419
- function transformIterator(iterator, transform) {
420
- return makeIterable({
421
- next() {
422
- const { done, value } = iterator.next();
423
- return { done, value: done ? value : transform(value) };
424
- },
425
- });
426
- }
427
- /**
428
- * Turns an array into an iterator. NOTE: an iterator can only be iterated once.
429
- * @param array Array to be turned into an iterator
430
- * @returns Iterator to iterate through the array
431
- */
432
- function arrayToIterator(array) {
433
- let i = 0;
434
- const iterator = {
435
- next() {
436
- const done = i >= array.length;
437
- if (done)
438
- return { done, value: null };
439
- return { value: array[i++] };
440
- },
441
- };
442
- return makeIterable(iterator);
443
- }
444
-
445
- function areaContains(area, coord) {
446
- return coord.x >= area.x && coord.y >= area.y && coord.x < area.x + area.width && coord.y < area.y + area.height;
447
- }
448
- function coordsOf(area) {
449
- const coords = [];
450
- for (let dx = 0; dx < area.width; dx++) {
451
- for (let dy = 0; dy < area.height; dy++) {
452
- coords.push({ x: area.x + dx, y: area.y + dy });
453
- }
454
- }
455
- return coords;
456
- }
457
-
458
- /**
459
- * Compute keccak256 hash from given string and remove padding from the resulting hex string
460
- * @param data String to be hashed
461
- * @returns Hash of the given string as hex string without padding
462
- */
463
- function keccak256(data) {
464
- return BigNumber.from(keccak256$1(toUtf8Bytes(data))).toHexString();
465
- }
466
- function keccak256Coord(coord) {
467
- // TODO: make faster by implementing in wasm
468
- const bytes = defaultAbiCoder.encode(["int32", "int32"], [coord.x, coord.y]);
469
- return keccak256$1(bytes);
470
- }
471
-
472
- function fromWorker(worker, input$) {
473
- input$.subscribe((event) => worker.postMessage(event));
474
- return fromEvent(worker, "message").pipe(map((e) => e.data));
475
- }
476
- function runWorker(worker) {
477
- const input$ = fromEvent(self, "message");
478
- const output$ = worker.work(input$.pipe(map((event) => event.data)));
479
- output$.subscribe((event) => self.postMessage(event));
480
- }
481
-
482
- function rightMask(input, keep) {
483
- return input & (2 ** keep - 1);
484
- }
485
- /**
486
- * Packs two unsigned integers in one 32 bit unsigned integer
487
- * @param numbers Unsigned integers to be packed in 32 bit integer
488
- * @param bitsPerNumber Bits for each number
489
- * @returns Packed 32 bit unsigned integer
490
- */
491
- function pack(numbers, bitsPerNumber) {
492
- // Total number of bits must be 32
493
- if (bitsPerNumber.reduce((acc, curr) => acc + curr, 0) > 32) {
494
- throw new Error("JS pretends integers are 32 bit when bitshifts are involved");
495
- }
496
- // Array lengths must match
497
- if (numbers.length !== bitsPerNumber.length)
498
- throw new Error("Arrays' lengths must match");
499
- // Numbers must fit in number of bits and must be unsigned
500
- for (let i = 0; i < numbers.length; i++) {
501
- if (numbers[i] < 0) {
502
- throw new Error("Underflow: can only pack unsigned integer");
503
- }
504
- if (numbers[i] > 2 ** bitsPerNumber[i] - 1) {
505
- const error = `Overflow: ${numbers[i]} does not fit in ${bitsPerNumber[i]} bits`;
506
- throw new Error(error);
507
- }
508
- }
509
- // Pack number
510
- let packed = 0;
511
- for (let i = 0; i < numbers.length; i++) {
512
- packed = (packed << bitsPerNumber[i]) | numbers[i];
513
- }
514
- return packed;
515
- }
516
- /**
517
- * Unpacks a packed 32 bit unsigned integer into the original unsigned integers
518
- * @param packed Packed 32 bit unsigned integer
519
- * @param bitsPerNumber Bits for each unsigned integer
520
- * @returns Array of unpacked unsignd integers
521
- */
522
- function unpack(packed, bitsPerNumber) {
523
- const numbers = [];
524
- let shiftedPacked = packed;
525
- for (let i = bitsPerNumber.length - 1; i >= 0; i--) {
526
- numbers.unshift(rightMask(shiftedPacked, bitsPerNumber[i]));
527
- shiftedPacked = shiftedPacked >>> bitsPerNumber[i];
528
- }
529
- return numbers;
530
- }
531
- function packTuple(numbers) {
532
- return pack(numbers, [8, 24]);
533
- }
534
- function unpackTuple(packed) {
535
- return unpack(packed, [8, 24]);
536
- }
537
-
538
- const LOWER_HALF_MASK = 2 ** 16 - 1;
539
- const MAX_SUPPORTED = 2 ** 15 - 1;
540
- function subtract(from, subtract) {
541
- const result = new CoordMap();
542
- for (const coord of from.coords()) {
543
- if (subtract.get(coord))
544
- continue;
545
- result.set(coord, true);
546
- }
547
- return result;
548
- }
549
- function coordToKey$1(coord) {
550
- const key = (coord.x << 16) | (coord.y & LOWER_HALF_MASK);
551
- return key;
552
- // Old version using strings:
553
- // return `${coord.x}/${coord.y}`;
554
- }
555
- function keyToCoord$1(key) {
556
- const x = key >> 16;
557
- const y = (key << 16) >> 16;
558
- return { x, y };
559
- // Old version using strings:
560
- // const fragments = key.split("/");
561
- // return { x: Number(fragments[0]), y: Number(fragments[1]) };
562
- }
563
- class CoordMap {
564
- constructor(props) {
565
- this.map = new Map();
566
- this.defaultValue = props === null || props === void 0 ? void 0 : props.defaultValue;
567
- }
568
- static from(coordMapLike) {
569
- const coordMap = new CoordMap();
570
- coordMap.map = coordMapLike.map;
571
- coordMap.defaultValue = coordMapLike.defaultValue;
572
- return coordMap;
573
- }
574
- set(coord, value) {
575
- if (coord.x > MAX_SUPPORTED ||
576
- coord.x < -1 * MAX_SUPPORTED ||
577
- coord.y > MAX_SUPPORTED ||
578
- coord.y < -1 * MAX_SUPPORTED) {
579
- throw new Error(`CoordMap only supports coords up to ${MAX_SUPPORTED}`);
580
- }
581
- return this.map.set(coordToKey$1(coord), value);
582
- }
583
- get(coord) {
584
- var _a;
585
- return (_a = this.map.get(coordToKey$1(coord))) !== null && _a !== void 0 ? _a : this.defaultValue;
586
- }
587
- keys() {
588
- return this.map.keys();
589
- }
590
- coords() {
591
- return transformIterator(this.map.keys(), (key) => keyToCoord$1(key));
592
- }
593
- entries() {
594
- return this.map.entries();
595
- }
596
- toArray() {
597
- const entries = Array.from(this.map.entries());
598
- return entries.map(([key, value]) => [keyToCoord$1(key), value]);
599
- }
600
- values() {
601
- return this.map.values();
602
- }
603
- delete(coord) {
604
- return this.map.delete(coordToKey$1(coord));
605
- }
606
- has(coord) {
607
- return this.map.has(coordToKey$1(coord));
608
- }
609
- clear() {
610
- for (const key of this.map.keys()) {
611
- this.map.delete(key);
612
- }
613
- }
614
- get size() {
615
- return this.map.size;
616
- }
617
- }
618
-
619
- function coordToKey(coord) {
620
- // TODO: find a more memory efficient way to store these keys
621
- return `${coord.x}/${coord.y}/${coord.z}`;
622
- }
623
- function keyToCoord(key) {
624
- const fragments = key.split("/");
625
- return { x: Number(fragments[0]), y: Number(fragments[1]), z: Number(fragments[2]) };
626
- }
627
- class VoxelCoordMap {
628
- constructor(props) {
629
- this.map = new Map();
630
- this.defaultValue = props === null || props === void 0 ? void 0 : props.defaultValue;
631
- }
632
- static from(coordMapLike) {
633
- const coordMap = new VoxelCoordMap();
634
- coordMap.map = coordMapLike.map;
635
- coordMap.defaultValue = coordMapLike.defaultValue;
636
- return coordMap;
637
- }
638
- set(coord, value) {
639
- return this.map.set(coordToKey(coord), value);
640
- }
641
- get(coord) {
642
- var _a;
643
- return (_a = this.map.get(coordToKey(coord))) !== null && _a !== void 0 ? _a : this.defaultValue;
644
- }
645
- keys() {
646
- return this.map.keys();
647
- }
648
- coords() {
649
- return transformIterator(this.map.keys(), (key) => keyToCoord(key));
650
- }
651
- entries() {
652
- return this.map.entries();
653
- }
654
- toArray() {
655
- const entries = Array.from(this.map.entries());
656
- return entries.map(([key, value]) => [keyToCoord(key), value]);
657
- }
658
- values() {
659
- return this.map.values();
660
- }
661
- delete(coord) {
662
- return this.map.delete(coordToKey(coord));
663
- }
664
- has(coord) {
665
- return this.map.has(coordToKey(coord));
666
- }
667
- clear() {
668
- for (const key of this.map.keys()) {
669
- this.map.delete(key);
670
- }
671
- }
672
- get size() {
673
- return this.map.size;
674
- }
675
- }
676
-
677
- /**
678
- * Pads start of a hex string with 0 to create a bit string of the given length
679
- * @param input Hex string
680
- * @param bits Number of bits in the output hex string
681
- * @returns Hex string of specified length
682
- */
683
- function padToBitLength(input, bits) {
684
- // Cut off 0x prefix
685
- if (input.substring(0, 2) == "0x")
686
- input = input.substring(2);
687
- // Pad start with 0 to get desired bit length
688
- const length = bits / 4;
689
- input = input.padStart(length, "0");
690
- input = input.substring(input.length - length);
691
- // Prefix with 0x
692
- return `0x${input}`;
693
- }
694
- /**
695
- * Pads start of a hex string with 0 to create a 160 bit hex string
696
- * which can be used as an Ethereum address
697
- * @param input Hex string
698
- * @returns 160 bit hex string
699
- */
700
- function toEthAddress(input) {
701
- return padToBitLength(input, 160);
702
- }
703
- /**
704
- * Pads start of a hex string with 0 to create a 256bit hex string
705
- * which can be used as an Ethereum address
706
- * @param input Hex string
707
- * @returns 256 bit hex string
708
- */
709
- function to256BitString(input) {
710
- return padToBitLength(input, 256);
711
- }
712
- function extractEncodedArguments(input) {
713
- // Cutting off the first 4 bytes, which represent the function selector
714
- if (input[0] !== "0" && input[1] !== "x")
715
- throw new Error("Invalid hex string");
716
- return "0x" + input.substring(10);
717
- }
718
-
719
- const RND_A = 134775813;
720
- const RND_B = 1103515245;
721
- const ACCURACY = 1000;
722
- function randomize(seed, x, y) {
723
- return (((((x ^ y) * RND_A) ^ (seed + x)) * (((RND_B * x) << 16) ^ (RND_B * y - RND_A))) >>> 0) / 4294967295;
724
- }
725
- function tile(coordinate, period) {
726
- if (coordinate < 0)
727
- while (coordinate < 0)
728
- coordinate += period;
729
- return coordinate % period;
730
- }
731
- function interpolate(a, b, c, d, x, s, scale) {
732
- const p = d - c - (a - b);
733
- return (b * Math.pow(s, 3) + x * (c * Math.pow(s, 2) + a * s * (-s + x) + x * (-(b + p) * s + p * x))) * scale;
734
- // return (x) * ((x ) * ((x ) * p + (a - b - p)) + (c - a)) + b;
735
- }
736
- /**
737
- * Config a cubic noise.
738
- * @param {Number} seed A seed in the range [0, 1].
739
- * @param {Number} [periodX] The number of units after which the x coordinate repeats.
740
- * @param {Number} [periodY] The number of units after which the y coordinate repeats.
741
- * @returns {Object} A configuration object used by noise functions.
742
- */
743
- function cubicNoiseConfig(seed, octave, scale, periodX = Number.MAX_SAFE_INTEGER, periodY = Number.MAX_SAFE_INTEGER) {
744
- return {
745
- seed: Math.floor(seed * Number.MAX_SAFE_INTEGER),
746
- periodX: periodX,
747
- periodY: periodY,
748
- octave,
749
- scale,
750
- };
751
- }
752
- /**
753
- * Sample 1D cubic noise.
754
- * @param {Object} config A valid noise configuration.
755
- * @param {Number} x The X position to sample at.
756
- * @returns {Number} A noise value in the range [0, 1].
757
- */
758
- function cubicNoiseSample1(config, x) {
759
- const xi = Math.floor(x);
760
- const lerp = x - xi;
761
- return (interpolate(randomize(config.seed, tile(xi - 1, config.periodX), 0), randomize(config.seed, tile(xi, config.periodX), 0), randomize(config.seed, tile(xi + 1, config.periodX), 0), randomize(config.seed, tile(xi + 2, config.periodX), 0), lerp, 1, 1) *
762
- 0.666666 +
763
- 0.166666);
764
- }
765
- /**
766
- * Sample 2D cubic noise.
767
- * @param {Object} config A valid noise configuration.
768
- * @param {Number} x The X position to sample at.
769
- * @param {Number} y The Y position to sample at.
770
- * @returns {Number} A noise value in the range [0, 1].
771
- */
772
- function cubicNoiseSample2({ octave, periodX, periodY, seed, scale }, x, y) {
773
- const xi = Math.floor(x / octave);
774
- const lerpX = Math.floor((x * ACCURACY) / octave) - xi * ACCURACY;
775
- const yi = Math.floor(y / octave);
776
- const lerpY = Math.floor((y * ACCURACY) / octave) - yi * ACCURACY;
777
- const x0 = tile(xi - 1, periodX);
778
- const x1 = tile(xi, periodX);
779
- const x2 = tile(xi + 1, periodX);
780
- const x3 = tile(xi + 2, periodX);
781
- const xSamples = new Array(4);
782
- for (let i = 0; i < 4; ++i) {
783
- const y = tile(yi - 1 + i, periodY);
784
- xSamples[i] = interpolate(randomize(seed, x0, y), randomize(seed, x1, y), randomize(seed, x2, y), randomize(seed, x3, y), lerpX, ACCURACY, 1);
785
- }
786
- return Math.floor(interpolate(xSamples[0], xSamples[1], xSamples[2], xSamples[3], lerpY, ACCURACY, scale) / Math.pow(ACCURACY, 6));
787
- }
788
-
789
- const TOPICS_KEY = "mud-logger-topics";
790
- function enableLogger() {
791
- const windowConsole = window.console;
792
- let filtersActive = Boolean(localStorage.getItem(TOPICS_KEY));
793
- const topicsString = localStorage.getItem(TOPICS_KEY);
794
- let topics = topicsString ? JSON.parse(topicsString) : [];
795
- function log(...logs) {
796
- if (filtersActive)
797
- return;
798
- windowConsole.log(...logs);
799
- }
800
- function logWithTopic(topic, ...logs) {
801
- if (!filtersActive || topics.includes(topic)) {
802
- windowConsole.log(`--- BETTER CONSOLE / TOPIC ${topic} ---`);
803
- windowConsole.log(...logs);
804
- }
805
- }
806
- function enableFilters() {
807
- localStorage.setItem(TOPICS_KEY, JSON.stringify([]));
808
- filtersActive = true;
809
- }
810
- function disableFilters() {
811
- localStorage.removeItem(TOPICS_KEY);
812
- filtersActive = false;
813
- }
814
- function addTopic(topic) {
815
- topics.push(topic);
816
- localStorage.setItem(TOPICS_KEY, JSON.stringify(topics));
817
- }
818
- function removeTopic(topic) {
819
- topics = topics.filter((t) => t !== topic);
820
- localStorage.setItem(TOPICS_KEY, JSON.stringify(topics));
821
- }
822
- function resetTopics() {
823
- topics = [];
824
- localStorage.setItem(TOPICS_KEY, JSON.stringify(topics));
825
- }
826
- const logger = {
827
- ...windowConsole,
828
- log,
829
- logWithTopic,
830
- enableFilters,
831
- disableFilters,
832
- addTopic,
833
- removeTopic,
834
- resetTopics,
835
- };
836
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
837
- window.logger = logger;
838
- window.console = logger;
839
- return logger;
840
- }
841
-
842
- /**
843
- * Compute the Euclidean distance between two points
844
- * https://en.wikipedia.org/wiki/Euclidean_distance
845
- * @param a
846
- * @param b
847
- * @returns Euclidian distance between a and b
848
- */
849
- function euclidean(a, b) {
850
- if (a.length !== b.length)
851
- throw new Error("points must have same dimension");
852
- return Math.sqrt(a.reduce((acc, _, i) => acc + Math.pow(a[i] - b[i], 2), 0));
853
- }
854
-
855
- /**
856
- * For positive inputs: returns the greatest integer less than or equal to its numeric argument.
857
- * For negative inputs: returns the smallest integer greater than or equal to its numeric argument.
858
- *
859
- * @param x A numeric expression.
860
- * @returns Input rounded towards zero.
861
- */
862
- function roundTowardsZero(x) {
863
- const sign = x < 0 ? -1 : 1;
864
- return sign * Math.floor(Math.abs(x));
865
- }
866
-
867
- // TODO: migrate to viem's toHex()
868
- const arrayToHex = (array) => `0x${[...new Uint8Array(array)].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
869
-
870
- const bytesToString = (bytes) => [...bytes].map((x) => String.fromCharCode(x)).join("");
871
-
872
- // TODO: migrate to viem's isHex()
873
- // Note that this assumes hex pairs, but viem does not. We'll need to be careful migrating.
874
- // Padding an odd-length hex sounds scary (based on how Solidity left/right aligns numbers vs bytes/strings).
875
- function isHex(hex) {
876
- return /^(0x)?([\da-f]{2})*$/i.test(hex);
877
- }
878
-
879
- // TODO: migrate to viem's toBytes(hex)
880
- const hexToArray = (hex) => {
881
- if (!isHex(hex)) {
882
- console.error("Invalid hex string", hex);
883
- throw new Error("Invalid hex string");
884
- }
885
- const bytes = hex.match(/[\da-f]{2}/gi);
886
- if (!bytes)
887
- return new Uint8Array([]);
888
- return new Uint8Array(bytes.map((byte) => parseInt(byte, 16)));
889
- };
890
-
891
- function isDefined(argument) {
892
- return argument !== undefined;
893
- }
894
-
895
- function isNotNull(argument) {
896
- return argument !== null;
897
- }
898
-
899
- const stringToBytes16 = (str) => {
900
- if (str.length > 16)
901
- throw new Error("string too long");
902
- return new Uint8Array(16).map((v, i) => str.charCodeAt(i));
903
- };
904
-
905
- class TableId {
906
- constructor(namespace, name) {
907
- this.namespace = namespace;
908
- this.name = name;
909
- }
910
- toString() {
911
- return `TableId<${this.namespace || "[empty]"}:${this.name || "[empty]"}>`;
912
- }
913
- toHexString() {
914
- return TableId.toHexString(this.namespace, this.name);
915
- }
916
- static toHexString(namespace, name) {
917
- const tableId = new Uint8Array(32);
918
- tableId.set(stringToBytes16(namespace), 0);
919
- tableId.set(stringToBytes16(name), 16);
920
- return arrayToHex(tableId);
921
- }
922
- static fromHexString(tableId) {
923
- return TableId.fromBytes32(hexToArray(tableId));
924
- }
925
- static fromBytes32(tableId) {
926
- const tableIdBytes = new Uint8Array(32);
927
- tableIdBytes.set(tableId);
928
- const namespace = bytesToString(tableIdBytes.slice(0, 16)).replace(/\0+$/, "");
929
- const name = bytesToString(tableIdBytes.slice(16, 32)).replace(/\0+$/, "");
930
- return new TableId(namespace, name);
931
- }
932
- /** @deprecated Don't use this! This is a temporary hack for v2<>v1 compatibility until we can write v2 client libraries. This is here so it stays close to the formatting of `toString()` above. */
933
- static parse(tableIdString) {
934
- const match = tableIdString.match(/^TableId<(.+?):(.+?)>$/);
935
- if (!match)
936
- return null;
937
- const [, namespace, name] = match;
938
- return new TableId(namespace === "[empty]" ? "" : namespace, name === "[empty]" ? "" : name);
939
- }
940
- }
941
-
942
- function formatHex(hex) {
943
- if (hex.substring(0, 2) == "0x")
944
- hex = hex.substring(2);
945
- const prefix = hex.length % 2 !== 0 ? "0x0" : "0x";
946
- return prefix + hex;
947
- }
948
- function hexStringToUint8Array(hexString) {
949
- return hexToArray(hexString);
950
- }
951
- function Uint8ArrayToHexString(data) {
952
- if (data.length === 0)
953
- return "0x00";
954
- return formatHex(data.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), ""));
955
- }
956
- function concatUint8Arrays(...arrays) {
957
- return Uint8Array.from(arrays.reduce((acc, curr) => {
958
- return [...acc, ...curr];
959
- }, []));
960
- }
961
- function splitUint8Arrays(data, byteLengths) {
962
- const arrays = [];
963
- let i = 0;
964
- for (const length of byteLengths) {
965
- const array = new Uint8Array(length);
966
- arrays.push(array);
967
- for (let j = 0; j < length; j++) {
968
- array[j] = data[i];
969
- i++;
970
- }
971
- }
972
- return arrays;
973
- }
974
- function Int32ArrayToUint8Array(input) {
975
- const buffer = new ArrayBuffer(input.length * 4);
976
- const int32arr = new Int32Array(buffer);
977
- for (let i = 0; i < input.length; i++) {
978
- int32arr[i] = input[i];
979
- }
980
- return new Uint8Array(buffer);
981
- }
982
- function Uint8ArrayToInt32Array(input) {
983
- return [...new Int32Array(input.buffer)];
984
- }
985
- function ethAddressToUint8Array(address) {
986
- return hexStringToUint8Array(toEthAddress(address));
987
- }
988
- // https://stackoverflow.com/a/55330424
989
- function createToInt(size) {
990
- if (size < 2) {
991
- throw new Error("Minimum size is 2");
992
- }
993
- else if (size > 64) {
994
- throw new Error("Maximum size is 64");
995
- }
996
- // Determine value range
997
- const maxValue = 2 ** (size - 1) - 1;
998
- const minValue = -maxValue - 1;
999
- return (value) => {
1000
- value = value << 0;
1001
- if (value > maxValue || value < minValue) {
1002
- console.log("value", value, maxValue, minValue, value > maxValue, value < minValue);
1003
- throw new Error(`Int${size} overflow`);
1004
- }
1005
- if (value < 0) {
1006
- return 2 ** size + value;
1007
- }
1008
- else {
1009
- return value;
1010
- }
1011
- };
1012
- }
1013
- const toInt32 = createToInt(32);
1014
-
1015
- export { CoordMap, Int32ArrayToUint8Array, TableId, Uint8ArrayToHexString, Uint8ArrayToInt32Array, VoxelCoordMap, areaContains, arrayToHex, arrayToIterator, awaitPromise, awaitStreamValue, awaitValue, bytesToString, cacheUntilReady, callWithRetry, computedToStream, concatIterators, concatUint8Arrays, coordToKey$1 as coordToKey, coordsOf, createToInt, cubicNoiseConfig, cubicNoiseSample1, cubicNoiseSample2, deferred, enableLogger, ethAddressToUint8Array, euclidean, extractEncodedArguments, filterNullish, filterNullishValues, formatHex, fromWorker, hexStringToUint8Array, hexToArray, interpolate, isDefined, isFunction, isHex, isNotEmpty, isNotNull, isObject, keccak256, keccak256Coord, keyToCoord$1 as keyToCoord, makeIterable, mapObject, mergeIterators, numValues, observableToComputed, observableToStream, pack, packTuple, padToBitLength, pickRandom, random, randomize, range, rejectAfter, roundTowardsZero, runWorker, sleep, splitUint8Arrays, streamToComputed, streamToDefinedComputed, streamToWrappedValue, stretch, stringToBytes16, subtract, tile, timeoutAfter, to256BitString, toEthAddress, toInt32, transformIterator, unpack, unpackTuple, uuid };
1016
- //# sourceMappingURL=index.js.map
11
+ //# sourceMappingURL=index.js.map