@flapsdk/vault-runtime 0.1.40-next.0 → 0.1.40-next.2

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.
@@ -253,7 +253,11 @@ function createIpfsTextReader({ fetchImpl = fetch, timeoutMs = 8e3 } = {}) {
253
253
 
254
254
  // src/sdk/fsiPolicy.mjs
255
255
  var FSI_QUERY_PREFIX = "https://bsc-debug.butterfly.army/fsi/v1";
256
- var FSI_ORIGIN = "https://bsc-debug.butterfly.army";
256
+ var FSI_QUERY_PREFIXES = Object.freeze([
257
+ "https://fsi.taxed.fun/fsi/v1",
258
+ FSI_QUERY_PREFIX
259
+ ]);
260
+ var FSI_ORIGINS = new Set(FSI_QUERY_PREFIXES.map((prefix) => new URL(prefix).origin));
257
261
  var FSI_PATH = "/fsi/v1";
258
262
  var encodedPathSyntax = /%(?:2e|2f|5c|25)/i;
259
263
  var hasDotSegment = (path) => path.split("/").some((part) => part === "." || part === "..");
@@ -263,27 +267,35 @@ function isFsiQueryUrl(value) {
263
267
  const rawPath = value.match(/^[a-z][a-z\d+.-]*:\/\/[^/?#]*([^?#]*)/i)?.[1];
264
268
  if (rawPath === void 0 || encodedPathSyntax.test(rawPath) || hasDotSegment(rawPath)) return false;
265
269
  const url = new URL(value);
266
- return url.origin === FSI_ORIGIN && !url.username && !url.password && !url.hash && (url.pathname === FSI_PATH || url.pathname.startsWith(`${FSI_PATH}/`)) && !encodedPathSyntax.test(url.pathname);
270
+ return FSI_ORIGINS.has(url.origin) && !url.username && !url.password && !url.hash && (url.pathname === FSI_PATH || url.pathname.startsWith(`${FSI_PATH}/`)) && !encodedPathSyntax.test(url.pathname);
267
271
  } catch {
268
272
  return false;
269
273
  }
270
274
  }
271
- function hasFsiQueryDeclaration(endpoints) {
275
+ function resolveFsiQueryPrefix(endpoints) {
272
276
  const urls = typeof endpoints === "string" ? [endpoints] : endpoints;
273
- return Array.isArray(urls) && urls.some((value) => {
274
- if (!isFsiQueryUrl(value)) return false;
277
+ if (!Array.isArray(urls)) return null;
278
+ const declared = /* @__PURE__ */ new Set();
279
+ for (const value of urls) {
280
+ if (!isFsiQueryUrl(value)) continue;
275
281
  const url = new URL(value);
276
- return !url.search && (url.pathname === FSI_PATH || url.pathname === `${FSI_PATH}/`);
277
- });
282
+ if (!url.search && (url.pathname === FSI_PATH || url.pathname === `${FSI_PATH}/`)) {
283
+ declared.add(`${url.origin}${FSI_PATH}`);
284
+ }
285
+ }
286
+ return FSI_QUERY_PREFIXES.find((prefix) => declared.has(prefix)) ?? null;
278
287
  }
279
- function buildFsiQueryUrl(path, params = {}) {
288
+ function buildFsiQueryUrl(path, params = {}, prefix = FSI_QUERY_PREFIX) {
289
+ if (!FSI_QUERY_PREFIXES.includes(prefix)) {
290
+ throw new Error("FSI URL is outside the platform query allowlist.");
291
+ }
280
292
  if (typeof path !== "string" || path.startsWith("/") || /[\\?#\s\u0000-\u001f\u007f]/.test(path)) {
281
293
  throw new Error("FSI path must be relative to /fsi/v1 without query or fragment; pass query parameters separately.");
282
294
  }
283
295
  if (encodedPathSyntax.test(path) || hasDotSegment(path)) {
284
296
  throw new Error("FSI path traversal and encoded path separators/dots are not allowed.");
285
297
  }
286
- const url = new URL(`${FSI_QUERY_PREFIX}/${path}`);
298
+ const url = new URL(`${prefix}/${path}`);
287
299
  if (!isFsiQueryUrl(url.href)) throw new Error("FSI URL is outside the platform query allowlist.");
288
300
  for (const [key, value] of Object.entries(params)) {
289
301
  if (typeof value !== "string") throw new Error("FSI query parameter values must be strings.");
@@ -294,10 +306,11 @@ function buildFsiQueryUrl(path, params = {}) {
294
306
 
295
307
  // src/sdk/fsi.ts
296
308
  async function readFsiJson(endpoints, path, params, fetchImpl = fetch) {
297
- if (!hasFsiQueryDeclaration(endpoints)) {
298
- throw new Error("FSI requires https://bsc-debug.butterfly.army/fsi/v1 in manifest.endpoints for review.");
309
+ const prefix = resolveFsiQueryPrefix(endpoints);
310
+ if (!prefix) {
311
+ throw new Error(`FSI requires ${FSI_QUERY_PREFIXES.join(" or ")} in manifest.endpoints for review.`);
299
312
  }
300
- const url = buildFsiQueryUrl(path, params);
313
+ const url = buildFsiQueryUrl(path, params, prefix);
301
314
  const response = await fetchImpl(url, {
302
315
  method: "GET",
303
316
  credentials: "omit",
@@ -522,6 +535,339 @@ function createFlapChainSdk(runtime, input) {
522
535
  };
523
536
  }
524
537
 
538
+ // src/sdk/deviceSensors.ts
539
+ var DEVICE_SENSORS_VERSION = 1;
540
+ var ALL = ["location", "motion", "orientation"];
541
+ var DEFAULT_TIMEOUT_MS = 1e4;
542
+ var finite = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
543
+ var nonnegative = (value) => {
544
+ const number = finite(value);
545
+ return number !== null && number >= 0 ? number : null;
546
+ };
547
+ var boundedTimeout = (value) => Math.min(12e4, Math.max(1, nonnegative(value) ?? DEFAULT_TIMEOUT_MS));
548
+ function browserEnvironment() {
549
+ if (typeof window === "undefined" || typeof document === "undefined" || typeof navigator === "undefined") return void 0;
550
+ return {
551
+ secure: window.isSecureContext === true,
552
+ window,
553
+ document,
554
+ geolocation: navigator.geolocation,
555
+ setTimeout: (callback, milliseconds) => window.setTimeout(callback, milliseconds),
556
+ clearTimeout: (id) => window.clearTimeout(id),
557
+ now: Date.now
558
+ };
559
+ }
560
+ function locationData(value, now) {
561
+ const coords = value?.coords;
562
+ const latitude = finite(coords?.latitude), longitude = finite(coords?.longitude), accuracy = nonnegative(coords?.accuracy);
563
+ if (latitude === null || Math.abs(latitude) > 90 || longitude === null || Math.abs(longitude) > 180 || accuracy === null) return null;
564
+ return { latitude, longitude, accuracy, altitude: finite(coords.altitude), altitudeAccuracy: nonnegative(coords.altitudeAccuracy), heading: finite(coords.heading), speed: nonnegative(coords.speed), timestamp: finite(value.timestamp) ?? now };
565
+ }
566
+ function vector(value) {
567
+ const result = { x: finite(value?.x), y: finite(value?.y), z: finite(value?.z) };
568
+ return Object.values(result).some((item) => item !== null) ? result : null;
569
+ }
570
+ function motionData(value, now) {
571
+ const acceleration = vector(value?.acceleration), accelerationIncludingGravity = vector(value?.accelerationIncludingGravity);
572
+ const rotation = { alpha: finite(value?.rotationRate?.alpha), beta: finite(value?.rotationRate?.beta), gamma: finite(value?.rotationRate?.gamma) };
573
+ const rotationRate = Object.values(rotation).some((item) => item !== null) ? rotation : null;
574
+ if (!acceleration && !accelerationIncludingGravity && !rotationRate) return null;
575
+ return { acceleration, accelerationIncludingGravity, rotationRate, interval: nonnegative(value?.interval), timestamp: now };
576
+ }
577
+ function orientationData(value, now) {
578
+ const alpha = finite(value?.alpha), beta = finite(value?.beta), gamma = finite(value?.gamma);
579
+ return alpha === null && beta === null && gamma === null ? null : { alpha, beta, gamma, absolute: value?.absolute === true, timestamp: now };
580
+ }
581
+ function inactiveSensor(status, mode) {
582
+ const snapshot = Object.freeze({ status, permission: "unknown", data: null, mode });
583
+ return { getSnapshot: () => snapshot, subscribe: () => () => {
584
+ }, request: () => Promise.resolve(snapshot), stop() {
585
+ } };
586
+ }
587
+ function createBrowserChannel(kind, declared, resolveEnvironment) {
588
+ if (!declared) return inactiveSensor("not-declared", "real");
589
+ let state = { status: "idle", permission: "unknown", data: null, mode: "real" };
590
+ const listeners = /* @__PURE__ */ new Set();
591
+ let generation = 0;
592
+ let pending;
593
+ let environment;
594
+ let options = {};
595
+ let watchId;
596
+ let timer;
597
+ let eventListener;
598
+ let visibilityListener;
599
+ let abortListener;
600
+ let shouldResume = false;
601
+ let sawInvalidData = false;
602
+ let sessionActive = false;
603
+ const eventName = kind === "motion" ? "devicemotion" : "deviceorientation";
604
+ function update(next) {
605
+ state = { ...state, ...next };
606
+ for (const listener of listeners) listener();
607
+ }
608
+ function settle() {
609
+ const task = pending;
610
+ pending = void 0;
611
+ task?.resolve(state);
612
+ }
613
+ function clearTimer() {
614
+ if (timer !== void 0) environment?.clearTimeout(timer);
615
+ timer = void 0;
616
+ }
617
+ function detachHardware() {
618
+ clearTimer();
619
+ if (watchId !== void 0) environment?.geolocation?.clearWatch(watchId);
620
+ watchId = void 0;
621
+ if (eventListener) environment?.window.removeEventListener(eventName, eventListener);
622
+ eventListener = void 0;
623
+ }
624
+ function cleanup() {
625
+ generation += 1;
626
+ detachHardware();
627
+ if (visibilityListener) environment?.document.removeEventListener("visibilitychange", visibilityListener);
628
+ visibilityListener = void 0;
629
+ if (abortListener) options.signal?.removeEventListener("abort", abortListener);
630
+ abortListener = void 0;
631
+ sessionActive = false;
632
+ shouldResume = false;
633
+ }
634
+ function finish(status, permission = state.permission) {
635
+ cleanup();
636
+ update({ status, permission, data: null });
637
+ settle();
638
+ }
639
+ function stop() {
640
+ const hadWork = sessionActive || Boolean(pending);
641
+ cleanup();
642
+ update({ status: hadWork ? "cancelled" : "idle", data: null });
643
+ settle();
644
+ }
645
+ function guard(env) {
646
+ if (!env) return "unsupported";
647
+ if (!env.secure) return "insecure";
648
+ const features = kind === "location" ? ["geolocation"] : ["accelerometer", "gyroscope"];
649
+ const policy = env.document.permissionsPolicy ?? env.document.featurePolicy;
650
+ try {
651
+ if (policy && features.some((feature) => !policy.allowsFeature(feature))) return "policy-blocked";
652
+ } catch (error) {
653
+ if (error?.name === "SecurityError") return "policy-blocked";
654
+ }
655
+ if (kind === "location" ? !env.geolocation : !(kind === "motion" ? env.window.DeviceMotionEvent : env.window.DeviceOrientationEvent)) return "unsupported";
656
+ return null;
657
+ }
658
+ function accept(raw, token) {
659
+ if (token !== generation || !sessionActive) return;
660
+ const data = kind === "location" ? locationData(raw, environment.now()) : kind === "motion" ? motionData(raw, environment.now()) : orientationData(raw, environment.now());
661
+ if (!data) {
662
+ sawInvalidData = true;
663
+ return;
664
+ }
665
+ clearTimer();
666
+ update({ status: "active", permission: "granted", data });
667
+ settle();
668
+ if (kind === "location" && !options.watch) {
669
+ cleanup();
670
+ }
671
+ }
672
+ function startHardware() {
673
+ const env = environment;
674
+ if (env.document.visibilityState === "hidden") {
675
+ shouldResume = true;
676
+ update({ status: "paused", data: null });
677
+ settle();
678
+ return;
679
+ }
680
+ const token = generation;
681
+ sawInvalidData = false;
682
+ update({ status: "requesting", data: null });
683
+ timer = env.setTimeout(() => {
684
+ if (token === generation) finish(sawInvalidData ? "unavailable" : "timeout");
685
+ }, boundedTimeout(options.timeoutMs));
686
+ try {
687
+ if (kind === "location") {
688
+ const failed = (error) => {
689
+ if (token !== generation || !sessionActive) return;
690
+ const status = error?.code === 1 ? "denied" : error?.code === 3 ? "timeout" : "unavailable";
691
+ finish(status, status === "denied" ? "denied" : state.permission);
692
+ };
693
+ const geoOptions = { enableHighAccuracy: options.enableHighAccuracy === true, maximumAge: nonnegative(options.maximumAge) ?? 0, timeout: boundedTimeout(options.timeoutMs) };
694
+ if (options.watch) {
695
+ const id = env.geolocation.watchPosition((value) => accept(value, token), failed, geoOptions);
696
+ if (token === generation && sessionActive) watchId = id;
697
+ else env.geolocation.clearWatch(id);
698
+ } else env.geolocation.getCurrentPosition((value) => accept(value, token), failed, geoOptions);
699
+ } else {
700
+ eventListener = (value) => accept(value, token);
701
+ env.window.addEventListener(eventName, eventListener);
702
+ }
703
+ } catch (error) {
704
+ if (token === generation) finish(error?.name === "SecurityError" ? "policy-blocked" : "unavailable");
705
+ }
706
+ }
707
+ function observeSession() {
708
+ const env = environment;
709
+ visibilityListener = () => {
710
+ if (!sessionActive) return;
711
+ if (env.document.visibilityState === "hidden") {
712
+ generation += 1;
713
+ detachHardware();
714
+ shouldResume = true;
715
+ update({ status: "paused", data: null });
716
+ settle();
717
+ } else if (shouldResume) {
718
+ shouldResume = false;
719
+ if (state.permission === "granted") startHardware();
720
+ else finish("paused");
721
+ }
722
+ };
723
+ env.document.addEventListener("visibilitychange", visibilityListener);
724
+ if (options.signal) {
725
+ abortListener = () => finish("cancelled");
726
+ options.signal.addEventListener("abort", abortListener, { once: true });
727
+ }
728
+ }
729
+ function request(requestOptions = {}) {
730
+ if (pending) return pending.promise;
731
+ if (state.status === "active" && (kind !== "location" || options.watch && requestOptions.watch)) return Promise.resolve(state);
732
+ cleanup();
733
+ options = { ...requestOptions };
734
+ let blocked;
735
+ try {
736
+ environment = resolveEnvironment();
737
+ blocked = guard(environment);
738
+ } catch (error) {
739
+ blocked = error?.name === "SecurityError" ? "policy-blocked" : "unavailable";
740
+ }
741
+ if (blocked) {
742
+ update({ status: blocked, data: null });
743
+ return Promise.resolve(state);
744
+ }
745
+ if (options.signal?.aborted) {
746
+ update({ status: "cancelled", data: null });
747
+ return Promise.resolve(state);
748
+ }
749
+ if (environment.document.visibilityState === "hidden") {
750
+ update({ status: "paused", data: null });
751
+ return Promise.resolve(state);
752
+ }
753
+ sessionActive = true;
754
+ let resolve;
755
+ const promise = new Promise((done) => {
756
+ resolve = done;
757
+ });
758
+ pending = { promise, resolve };
759
+ update({ status: "requesting", data: null });
760
+ observeSession();
761
+ const token = generation;
762
+ if (kind === "location") startHardware();
763
+ else {
764
+ const constructor = kind === "motion" ? environment.window.DeviceMotionEvent : environment.window.DeviceOrientationEvent;
765
+ try {
766
+ const permission = constructor?.requestPermission?.();
767
+ if (permission) {
768
+ Promise.resolve(permission).then((result) => {
769
+ if (token !== generation || !sessionActive) return;
770
+ if (result !== "granted") {
771
+ finish("denied", "denied");
772
+ return;
773
+ }
774
+ update({ permission: "granted" });
775
+ startHardware();
776
+ }, (error) => {
777
+ if (token === generation && sessionActive) finish(error?.name === "NotAllowedError" ? "denied" : "unavailable");
778
+ });
779
+ } else startHardware();
780
+ } catch (error) {
781
+ if (token === generation) finish(error?.name === "NotAllowedError" ? "denied" : "unavailable");
782
+ }
783
+ }
784
+ return promise;
785
+ }
786
+ return {
787
+ getSnapshot: () => state,
788
+ subscribe(listener) {
789
+ listeners.add(listener);
790
+ let subscribed = true;
791
+ return () => {
792
+ if (!subscribed) return;
793
+ subscribed = false;
794
+ listeners.delete(listener);
795
+ if (listeners.size === 0 && sessionActive) stop();
796
+ };
797
+ },
798
+ request,
799
+ stop
800
+ };
801
+ }
802
+ function createBrowserDeviceSensors(options = {}) {
803
+ const allowed = new Set(options.capabilities ?? ALL);
804
+ const environment = () => typeof options.environment === "function" ? options.environment() : options.environment ?? browserEnvironment();
805
+ const location = createBrowserChannel("location", allowed.has("location"), environment);
806
+ const motion = createBrowserChannel("motion", allowed.has("motion"), environment);
807
+ const orientation = createBrowserChannel("orientation", allowed.has("orientation"), environment);
808
+ return { version: DEVICE_SENSORS_VERSION, mode: "real", location, motion, orientation, dispose() {
809
+ location.stop();
810
+ motion.stop();
811
+ orientation.stop();
812
+ } };
813
+ }
814
+ function createMockDeviceSensors(options = {}) {
815
+ const allowed = new Set(options.capabilities ?? ALL);
816
+ function channel(capability, data) {
817
+ if (!allowed.has(capability)) return inactiveSensor("not-declared", "mock");
818
+ let state = { status: "idle", permission: "unknown", data: null, mode: "mock" };
819
+ const listeners = /* @__PURE__ */ new Set();
820
+ const update = (next) => {
821
+ state = next;
822
+ for (const listener of listeners) listener();
823
+ };
824
+ return {
825
+ getSnapshot: () => state,
826
+ subscribe(listener) {
827
+ listeners.add(listener);
828
+ return () => {
829
+ listeners.delete(listener);
830
+ };
831
+ },
832
+ request(requestOptions) {
833
+ const outcome = options.outcome ?? "granted";
834
+ const status = requestOptions?.signal?.aborted ? "cancelled" : outcome === "granted" ? "active" : outcome;
835
+ update({ status, permission: status === "active" ? "granted" : status === "denied" ? "denied" : "unknown", data: status === "active" ? data : null, mode: "mock" });
836
+ return Promise.resolve(state);
837
+ },
838
+ stop() {
839
+ update({ ...state, status: "idle", data: null });
840
+ }
841
+ };
842
+ }
843
+ const location = channel("location", { latitude: 0, longitude: 0, accuracy: 100, altitude: null, altitudeAccuracy: null, heading: null, speed: null, timestamp: 0, ...options.location });
844
+ const motion = channel("motion", { acceleration: { x: 0, y: 0, z: 0 }, accelerationIncludingGravity: { x: 0, y: 0, z: 9.8 }, rotationRate: { alpha: 0, beta: 0, gamma: 0 }, interval: 16, timestamp: 0, ...options.motion });
845
+ const orientation = channel("orientation", { alpha: 0, beta: 0, gamma: 0, absolute: false, timestamp: 0, ...options.orientation });
846
+ return { version: DEVICE_SENSORS_VERSION, mode: "mock", location, motion, orientation, dispose() {
847
+ location.stop();
848
+ motion.stop();
849
+ orientation.stop();
850
+ } };
851
+ }
852
+ function scopeDeviceSensors(sensors, capabilities = []) {
853
+ const declared = new Set(capabilities);
854
+ const location = declared.has("location") ? sensors.location : inactiveSensor("not-declared", sensors.mode);
855
+ const motion = declared.has("motion") ? sensors.motion : inactiveSensor("not-declared", sensors.mode);
856
+ const orientation = declared.has("orientation") ? sensors.orientation : inactiveSensor("not-declared", sensors.mode);
857
+ return { version: DEVICE_SENSORS_VERSION, mode: sensors.mode, location, motion, orientation, dispose() {
858
+ location.stop();
859
+ motion.stop();
860
+ orientation.stop();
861
+ } };
862
+ }
863
+ function unavailableDeviceSensors() {
864
+ const location = inactiveSensor("unsupported", "real");
865
+ const motion = inactiveSensor("unsupported", "real");
866
+ const orientation = inactiveSensor("unsupported", "real");
867
+ return { version: DEVICE_SENSORS_VERSION, mode: "real", location, motion, orientation, dispose() {
868
+ } };
869
+ }
870
+
525
871
  // src/sdk/runtimeContext.ts
526
872
  var zeroAddress = "0x0000000000000000000000000000000000000000";
527
873
  function explorerForChain(chainId) {
@@ -578,6 +924,6 @@ function createVaultRuntimeContext(input) {
578
924
  };
579
925
  }
580
926
 
581
- export { FLAP_WALLET_RUNTIME_VERSION, chainLabelForChain, createFlapChainSdk, createIpfsTextReader, createVaultRuntimeContext, explorerForChain, parseAppWalletContracts, readContractEventsInBlockRanges, readFsiJson, resolveSafeContractWriteFeeOverrides };
582
- //# sourceMappingURL=chunk-QS475ZC7.js.map
583
- //# sourceMappingURL=chunk-QS475ZC7.js.map
927
+ export { DEVICE_SENSORS_VERSION, FLAP_WALLET_RUNTIME_VERSION, chainLabelForChain, createBrowserDeviceSensors, createFlapChainSdk, createIpfsTextReader, createMockDeviceSensors, createVaultRuntimeContext, explorerForChain, parseAppWalletContracts, readContractEventsInBlockRanges, readFsiJson, resolveSafeContractWriteFeeOverrides, scopeDeviceSensors, unavailableDeviceSensors };
928
+ //# sourceMappingURL=chunk-T4Y5RVCD.js.map
929
+ //# sourceMappingURL=chunk-T4Y5RVCD.js.map