@bty/feed_app-runtime-sdk 0.1.2 → 0.1.4

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/README.md CHANGED
@@ -180,6 +180,13 @@ denial / cancel / unavailability — none of them throw. `pickFiles` resolves to
180
180
  `{ files: { file, path? }[] }` (path present only on the native bridge),
181
181
  `saveFile` to a `FileSaveResult`.
182
182
 
183
+ For native/App saves, `saveFile` sends the Blob bytes through the bridge as
184
+ base64 with `{ filename, mime, size, base64 }`. The host App must return an
185
+ `ok: true` envelope with `result.saved === true`; older metadata-only success
186
+ responses are ignored. `USER_CANCELLED` maps to `"cancelled"`; other native
187
+ failure responses map to `"failed"` instead of trusting browser download
188
+ fallbacks, because WebView downloads can report success without writing a file.
189
+
183
190
  Capability detection (synchronous, cheap — gate UI ahead of a call):
184
191
 
185
192
  | Capability | Probe |
package/dist/ai/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {d as d$1,c}from'../chunk-AKZVV563.js';import {a as a$1}from'../chunk-ALNJCFV4.js';import {createParser}from'eventsource-parser';var D={version:"0.1.2"};var m="/v1/feed-app/runtime/ai",T=`${m}/chat/completions`,_=`${m}/messages`,B=`${m}/images/generations`,M=`${m}/audio/speech`,N=`${m}/video/generations`,H="Authorization",j="x-bty-extend",G="x-bty-app",h=D.version;var q=()=>{};async function*U(e){let t=e.getReader(),r=new TextDecoder,n=[],o=createParser({onEvent(c){n.push({event:c.event||"message",data:c.data});},onRetry:q,onComment:q}),s=false;try{for(;;){let{done:c,value:p}=await t.read();for(p&&o.feed(r.decode(p,{stream:!0}));n.length>0;)yield n.shift();if(c){for(o.reset({consume:!0});n.length>0;)yield n.shift();s=!0;return}}}finally{if(!s)try{await t.cancel();}catch{}t.releaseLock();}}async function*J(e){for await(let t of U(e)){if(t.data==="[DONE]")return;t.data&&(yield JSON.parse(t.data));}}async function*V(e){for await(let t of U(e))t.data&&(yield JSON.parse(t.data));}var Z="https://reactus-api.happyseeds.ai",$=e=>{try{let t=e();if(typeof t=="string"&&t.length>0)return t}catch{}},ee=()=>$(()=>typeof __BTY_RUNTIME_API_BASE_URL__=="string"?__BTY_RUNTIME_API_BASE_URL__:void 0),te=()=>$(()=>typeof __BTY_RUNTIME_PROJECT_ID__=="string"?__BTY_RUNTIME_PROJECT_ID__:void 0),x={apiBaseUrl:(ee()??Z).replace(/\/+$/,""),projectId:te()??""},re=e=>{x={...x,...e,...e.apiBaseUrl?{apiBaseUrl:e.apiBaseUrl.replace(/\/+$/,"")}:{}};},g=()=>x;var a=class extends Error{status;code;body;constructor(t,r,n,o=null){super(t),this.name="AiError",this.code=r,this.status=n,this.body=o;}},i=class extends a{constructor(t="Auth required",r=null){super(t,"auth_required",401,r),this.name="AuthRequiredError";}},y=class extends a{constructor(t="Rate limit exceeded",r=null){super(t,"rate_limit",429,r),this.name="RateLimitError";}},E=class extends a{constructor(t="Quota exceeded",r=null){super(t,"quota_exceeded",402,r),this.name="QuotaExceededError";}},A=class extends a{constructor(t,r=400,n=null){super(t,"bad_input",r,n),this.name="BadInputError";}},R=class extends a{constructor(t,r=500,n=null){super(t,"server",r,n),this.name="ServerError";}},d=class extends a{constructor(t="Network error",r){super(t,"network",-1,r),this.name="NetworkError";}},l=class extends a{constructor(t="Request aborted"){super(t,"aborted",-1,null),this.name="AbortedError";}},L=e=>typeof e=="object"&&e!==null,ne=(e,t)=>{if(typeof e=="string")return e||t;if(!L(e))return t;let r=e.message;if(typeof r=="string"&&r.length>0)return r;let n=e.error;if(typeof n=="string"&&n.length>0)return n;if(L(n)&&typeof n.message=="string"&&n.message.length>0)return n.message;let o=e.detail;return typeof o=="string"&&o.length>0?o:t},P=(e,t)=>{let r=ne(t,`HTTP ${e}`);return e===401||e===403?new i(r,t):e===402?new E(r,t):e===429?new y(r,t):e>=400&&e<500?new A(r,e,t):e>=500?new R(r,e,t):new a(r,"unknown",e,t)};var oe=e=>JSON.stringify({"sdk-version":h,...e}),F=async(e={})=>{let t=await c(),r=new Headers;t&&r.set(H,`Bearer ${t}`),r.set(j,oe(e.extend));let{projectId:n}=g();if(n&&r.set(G,n),e.contentType&&r.set("Content-Type",e.contentType),e.accept&&r.set("Accept",e.accept),e.extra)for(let[o,s]of Object.entries(e.extra))r.set(o,s);return r};var S="feed-app-runtime-sdk:ai-error",se=e=>typeof e=="object"&&e!==null,ae=(e,t)=>{if(se(e))for(let r of t){let n=e[r];if(typeof n=="string"&&n.length>0)return n}},Y=e=>{let t=ae(e.body,["request_id","requestId"]);return {source:"feed-app-runtime-sdk/ai",status:e.error.status,code:e.error.code,message:e.error.message,path:e.path,method:e.method,sdkVersion:h,timestamp:Date.now(),...t?{requestId:t}:{},...e.traceId?{traceId:e.traceId}:{},...e.willRetryAuth!==void 0?{willRetryAuth:e.willRetryAuth}:{}}},K=e=>{if(a$1()&&(window.dispatchEvent(new CustomEvent(S,{detail:e})),window.parent!==window))try{window.parent.postMessage({type:S,detail:e},"*");}catch{}};var ie="feed-app-runtime-sdk:auth-required",k=e=>{a$1()&&window.dispatchEvent(new CustomEvent(ie,{detail:e}));};var ce=e=>e instanceof DOMException&&e.name==="AbortError",pe=async e=>{let t=e.headers.get("content-type")??"";try{return t.includes("application/json")?await e.json():await e.text()}catch{return null}},de=e=>typeof e=="object"&&e!==null,ue=(e,t)=>{if(!de(e)||typeof e.success!="boolean")return e;if(e.success)return e.data;let r=typeof e.code=="number"?e.code:t;throw P(r,e)},Q=async(e,t)=>{let{apiBaseUrl:r}=g(),n=`${r}${e}`,o=await F(t),s;try{s=await fetch(n,{method:t.method??"POST",headers:o,body:t.body,signal:t.signal});}catch(b){throw ce(b)?new l:new d("Failed to reach AI backend",b)}if(s.ok)return s;let c=await pe(s),p=P(s.status,c);throw K(Y({error:p,path:e,method:t.method??"POST",body:c,traceId:s.headers.get("x-trace-id")??void 0,willRetryAuth:p instanceof i&&!t.skipAuthRetry&&!t.signal?.aborted})),p},v=async(e,t={})=>{try{return await Q(e,t)}catch(r){if(r instanceof i&&!t.skipAuthRetry&&!t.signal?.aborted){if(!await d$1())throw k({reason:"refresh_failed",error:r}),r;try{return await Q(e,{...t,skipAuthRetry:!0})}catch(o){throw o instanceof i&&k({reason:"retry_rejected",error:o}),o}}throw r}},u=async(e,t,r={})=>{let n=await v(e,{...r,method:"POST",contentType:"application/json",body:JSON.stringify(t)});return ue(await n.json(),n.status)};var w=async(e,t,r={})=>{let n=await v(e,{...r,method:"POST",contentType:"application/json",accept:"text/event-stream",body:JSON.stringify(t)});if(!n.body)throw new d("Streaming response has no body");return n.body},X=async(e,t,r={})=>await(await v(e,{...r,method:"POST",contentType:"application/json",body:JSON.stringify(t)})).blob();var C=e=>{let{signal:t,headers:r,...n}=e;return {transport:{signal:t,extra:r},payload:n}},me=(async e=>{let{transport:t,payload:r}=C(e);if(e.stream){let n=await w(T,r,t);return J(n)}return await u(T,r,t)}),le={create:me},fe={async generate(e){let{transport:t,payload:r}=C(e);return u(B,r,t)}},he={speech:{async create(e){let{transport:t,payload:r}=C(e);return X(M,r,t)}}},ge={generations:{async create(e){let{transport:t,payload:r}=C(e);return u(N,r,t)}}},ye={chat:{completions:le},images:fe,audio:he,video:ge};var Ee=e=>{let{signal:t,headers:r,...n}=e;return {transport:{signal:t,extra:r},payload:n}},Ae=(async e=>{let{transport:t,payload:r}=Ee(e);if(e.stream){let n=await w(_,r,t);return V(n)}return await u(_,r,t)}),Re={messages:{create:Ae}};
1
+ import {d as d$1,c}from'../chunk-V73IHZAF.js';import {a as a$1}from'../chunk-H42VJJAC.js';import {createParser}from'eventsource-parser';var D={version:"0.1.4"};var m="/v1/feed-app/runtime/ai",T=`${m}/chat/completions`,_=`${m}/messages`,B=`${m}/images/generations`,M=`${m}/audio/speech`,N=`${m}/video/generations`,H="Authorization",j="x-bty-extend",G="x-bty-app",h=D.version;var q=()=>{};async function*U(e){let t=e.getReader(),r=new TextDecoder,n=[],o=createParser({onEvent(c){n.push({event:c.event||"message",data:c.data});},onRetry:q,onComment:q}),s=false;try{for(;;){let{done:c,value:p}=await t.read();for(p&&o.feed(r.decode(p,{stream:!0}));n.length>0;)yield n.shift();if(c){for(o.reset({consume:!0});n.length>0;)yield n.shift();s=!0;return}}}finally{if(!s)try{await t.cancel();}catch{}t.releaseLock();}}async function*J(e){for await(let t of U(e)){if(t.data==="[DONE]")return;t.data&&(yield JSON.parse(t.data));}}async function*V(e){for await(let t of U(e))t.data&&(yield JSON.parse(t.data));}var Z="https://reactus-api.happyseeds.ai",$=e=>{try{let t=e();if(typeof t=="string"&&t.length>0)return t}catch{}},ee=()=>$(()=>typeof __BTY_RUNTIME_API_BASE_URL__=="string"?__BTY_RUNTIME_API_BASE_URL__:void 0),te=()=>$(()=>typeof __BTY_RUNTIME_PROJECT_ID__=="string"?__BTY_RUNTIME_PROJECT_ID__:void 0),x={apiBaseUrl:(ee()??Z).replace(/\/+$/,""),projectId:te()??""},re=e=>{x={...x,...e,...e.apiBaseUrl?{apiBaseUrl:e.apiBaseUrl.replace(/\/+$/,"")}:{}};},g=()=>x;var a=class extends Error{status;code;body;constructor(t,r,n,o=null){super(t),this.name="AiError",this.code=r,this.status=n,this.body=o;}},i=class extends a{constructor(t="Auth required",r=null){super(t,"auth_required",401,r),this.name="AuthRequiredError";}},y=class extends a{constructor(t="Rate limit exceeded",r=null){super(t,"rate_limit",429,r),this.name="RateLimitError";}},E=class extends a{constructor(t="Quota exceeded",r=null){super(t,"quota_exceeded",402,r),this.name="QuotaExceededError";}},A=class extends a{constructor(t,r=400,n=null){super(t,"bad_input",r,n),this.name="BadInputError";}},R=class extends a{constructor(t,r=500,n=null){super(t,"server",r,n),this.name="ServerError";}},d=class extends a{constructor(t="Network error",r){super(t,"network",-1,r),this.name="NetworkError";}},l=class extends a{constructor(t="Request aborted"){super(t,"aborted",-1,null),this.name="AbortedError";}},L=e=>typeof e=="object"&&e!==null,ne=(e,t)=>{if(typeof e=="string")return e||t;if(!L(e))return t;let r=e.message;if(typeof r=="string"&&r.length>0)return r;let n=e.error;if(typeof n=="string"&&n.length>0)return n;if(L(n)&&typeof n.message=="string"&&n.message.length>0)return n.message;let o=e.detail;return typeof o=="string"&&o.length>0?o:t},P=(e,t)=>{let r=ne(t,`HTTP ${e}`);return e===401||e===403?new i(r,t):e===402?new E(r,t):e===429?new y(r,t):e>=400&&e<500?new A(r,e,t):e>=500?new R(r,e,t):new a(r,"unknown",e,t)};var oe=e=>JSON.stringify({"sdk-version":h,...e}),F=async(e={})=>{let t=await c(),r=new Headers;t&&r.set(H,`Bearer ${t}`),r.set(j,oe(e.extend));let{projectId:n}=g();if(n&&r.set(G,n),e.contentType&&r.set("Content-Type",e.contentType),e.accept&&r.set("Accept",e.accept),e.extra)for(let[o,s]of Object.entries(e.extra))r.set(o,s);return r};var S="feed-app-runtime-sdk:ai-error",se=e=>typeof e=="object"&&e!==null,ae=(e,t)=>{if(se(e))for(let r of t){let n=e[r];if(typeof n=="string"&&n.length>0)return n}},Y=e=>{let t=ae(e.body,["request_id","requestId"]);return {source:"feed-app-runtime-sdk/ai",status:e.error.status,code:e.error.code,message:e.error.message,path:e.path,method:e.method,sdkVersion:h,timestamp:Date.now(),...t?{requestId:t}:{},...e.traceId?{traceId:e.traceId}:{},...e.willRetryAuth!==void 0?{willRetryAuth:e.willRetryAuth}:{}}},K=e=>{if(a$1()&&(window.dispatchEvent(new CustomEvent(S,{detail:e})),window.parent!==window))try{window.parent.postMessage({type:S,detail:e},"*");}catch{}};var ie="feed-app-runtime-sdk:auth-required",k=e=>{a$1()&&window.dispatchEvent(new CustomEvent(ie,{detail:e}));};var ce=e=>e instanceof DOMException&&e.name==="AbortError",pe=async e=>{let t=e.headers.get("content-type")??"";try{return t.includes("application/json")?await e.json():await e.text()}catch{return null}},de=e=>typeof e=="object"&&e!==null,ue=(e,t)=>{if(!de(e)||typeof e.success!="boolean")return e;if(e.success)return e.data;let r=typeof e.code=="number"?e.code:t;throw P(r,e)},Q=async(e,t)=>{let{apiBaseUrl:r}=g(),n=`${r}${e}`,o=await F(t),s;try{s=await fetch(n,{method:t.method??"POST",headers:o,body:t.body,signal:t.signal});}catch(b){throw ce(b)?new l:new d("Failed to reach AI backend",b)}if(s.ok)return s;let c=await pe(s),p=P(s.status,c);throw K(Y({error:p,path:e,method:t.method??"POST",body:c,traceId:s.headers.get("x-trace-id")??void 0,willRetryAuth:p instanceof i&&!t.skipAuthRetry&&!t.signal?.aborted})),p},v=async(e,t={})=>{try{return await Q(e,t)}catch(r){if(r instanceof i&&!t.skipAuthRetry&&!t.signal?.aborted){if(!await d$1())throw k({reason:"refresh_failed",error:r}),r;try{return await Q(e,{...t,skipAuthRetry:!0})}catch(o){throw o instanceof i&&k({reason:"retry_rejected",error:o}),o}}throw r}},u=async(e,t,r={})=>{let n=await v(e,{...r,method:"POST",contentType:"application/json",body:JSON.stringify(t)});return ue(await n.json(),n.status)};var w=async(e,t,r={})=>{let n=await v(e,{...r,method:"POST",contentType:"application/json",accept:"text/event-stream",body:JSON.stringify(t)});if(!n.body)throw new d("Streaming response has no body");return n.body},X=async(e,t,r={})=>await(await v(e,{...r,method:"POST",contentType:"application/json",body:JSON.stringify(t)})).blob();var C=e=>{let{signal:t,headers:r,...n}=e;return {transport:{signal:t,extra:r},payload:n}},me=(async e=>{let{transport:t,payload:r}=C(e);if(e.stream){let n=await w(T,r,t);return J(n)}return await u(T,r,t)}),le={create:me},fe={async generate(e){let{transport:t,payload:r}=C(e);return u(B,r,t)}},he={speech:{async create(e){let{transport:t,payload:r}=C(e);return X(M,r,t)}}},ge={generations:{async create(e){let{transport:t,payload:r}=C(e);return u(N,r,t)}}},ye={chat:{completions:le},images:fe,audio:he,video:ge};var Ee=e=>{let{signal:t,headers:r,...n}=e;return {transport:{signal:t,extra:r},payload:n}},Ae=(async e=>{let{transport:t,payload:r}=Ee(e);if(e.stream){let n=await w(_,r,t);return V(n)}return await u(_,r,t)}),Re={messages:{create:Ae}};
2
2
  export{S as AI_ERROR_EVENT,l as AbortedError,a as AiError,i as AuthRequiredError,A as BadInputError,d as NetworkError,E as QuotaExceededError,y as RateLimitError,R as ServerError,Re as anthropic,re as configureRuntime,ye as openai};
@@ -0,0 +1 @@
1
+ var o=()=>typeof window<"u"&&typeof document<"u";var f="hostRuntime",i=class{listeners=new Map;on(e,r){let s=this.listeners.get(e),n=s??new Set;return s||this.listeners.set(e,n),n.add(r),()=>{n.delete(r),n.size===0&&this.listeners.delete(e);}}emit(e,r){let s=this.listeners.get(e);if(s)for(let n of s)n(r);}},_=new i,u=0,N=t=>(u+=1,`${t}.${u}`),a=false,T=()=>{if(!o()||a)return;a=true,Reflect.set(window,f,{receiveMessage(e){if(!e)return;let r=e.endpoint;r&&_.emit(r,e.data??e);}});};var E="HostApp",M="hostListener";var x="processUserCredentials",I="processUserInfo",O="user.getCredentials",L="user.getUserInfo",v="user.credentials",H="user.info",U="user-credentials-request",k="user-credentials-response",y="user-info-request",P="user-info-response";var S=new RegExp(`${E}\\/(\\d+\\.\\d+\\.\\d+)\\/(\\d+)\\/(iOS|Android)`),R=t=>{let e=t.match(S);if(!e)return null;let[,r,s,n]=e;return !r||!s||n!=="iOS"&&n!=="Android"?null:{type:"native_app",platform:n,appVersion:r,buildNumber:s}},C=()=>{if(!o())return {type:"web"};let t=R(navigator.userAgent??"");return t||(window.parent!==window?{type:"iframe"}:{type:"web"})};var l=t=>typeof t!="object"||t===null?false:typeof Reflect.get(t,"postMessage")=="function",w=t=>{let e=Reflect.get(window,"webkit");if(typeof e=="object"&&e!==null){let s=Reflect.get(e,"messageHandlers");if(typeof s=="object"&&s!==null){let n=Reflect.get(s,t);if(l(n))return n}}let r=Reflect.get(window,t);return l(r)?r:null},B=(t,e={})=>{let{pollIntervalMs:r=50,timeoutMs:s=1500}=e;return new Promise(n=>{let d=Date.now(),c=()=>{let p=w(t);if(p){n(p);return}if(Date.now()-d>=s){n(null);return}setTimeout(c,r);};c();})};export{o as a,_ as b,N as c,T as d,M as e,x as f,I as g,O as h,L as i,v as j,H as k,U as l,k as m,y as n,P as o,C as p,w as q,B as r};
@@ -0,0 +1 @@
1
+ import {a as a$1,b as b$1,j as j$1,d,f,g,k,o,m,p,r,e,q as q$1,c as c$1,l,n,h,i}from'./chunk-H42VJJAC.js';var E=e=>typeof e=="object"&&e!==null,a=(e,n)=>{if(e)for(let t of n){let r=e[t];if(typeof r=="string"&&r.length>0)return r}},W=(e,n)=>{if(e)for(let t of n){let r=e[t];if(typeof r=="string"&&r.length>0||typeof r=="number"&&Number.isFinite(r))return r}},u=e=>{if(!E(e))return null;let n=E(e.credentials)?e.credentials:void 0,t=E(e.user)?e.user:void 0,r=a(e,["uid","userId","id"])??a(n,["uid","userId","id"])??a(t,["uid","userId","id"]),o=a(e,["token","authToken"])??a(n,["token","authToken"]);return !r||!o?null:{uid:r,token:o}},c=e=>{if(!E(e))return null;let n=E(e.data)?e.data:e,t=W(n,["userId","id","uid"]);if(t===void 0)return null;let r=a(n,["username","nickname","nickName","name"]),o=a(n,["nickname","nickName","username"]);return {...n,userId:t,...r?{username:r}:{},...o?{nickname:o}:{}}};var X=e=>typeof e!="object"||e===null?false:typeof Reflect.get(e,"type")=="string",b=false,D=()=>{!a$1()||b||(b=true,d(),Reflect.set(window,f,e=>{u(e)&&b$1.emit(j$1,e);}),Reflect.set(window,g,e=>{c(e)&&b$1.emit(k,e);}),window.addEventListener("message",e=>{let n=e.data;if(X(n))switch(n.type){case m:b$1.emit("iframe.credentials",n);break;case o:b$1.emit("iframe.userinfo",n);break}}));};var q=(e,n,t)=>new Promise(r=>{let o=false,f=i=>{o||(o=true,y(),clearTimeout(T),r(i));},y=b$1.on(n,i=>{let g=t(i);g&&f(g);}),T=setTimeout(()=>f(null),500);try{window.parent.postMessage({type:e,timestamp:Date.now()},"*");}catch{f(null);}}),B=()=>q(l,"iframe.credentials",u),H=()=>q(n,"iframe.userinfo",c);var j=async(e$1,n,t,r$1)=>{let o=e$1.platform==="Android"?await r(e,{pollIntervalMs:50,timeoutMs:1500}):q$1(e);if(!o)return null;let f=c$1(t);return new Promise(y=>{let T=false,i=d=>{T||(T=true,g(),z(),clearTimeout(K),y(d));},g=b$1.on(f,d=>{let p=r$1(d);p&&i(p);}),z=b$1.on(t,d=>{let p=r$1(d);p&&i(p);}),K=setTimeout(()=>i(null),3e3);try{o.postMessage({command:n,parameters:JSON.stringify({timestamp:Date.now(),endpoint:f})});}catch{i(null);}})},G=e=>j(e,h,j$1,u),Q=e=>j(e,i,k,c);D();var C=null,I=null,R=new Set,ne=e=>{switch(e.type){case "native_app":return G(e);case "iframe":return B();case "web":return Promise.resolve(null)}},re=e=>{switch(e.type){case "native_app":return Q(e);case "iframe":return H();case "web":return Promise.resolve(null)}},V=e=>{let n=C?.token??"",t=e?.token??"";if(C=e,n!==t)for(let r of R)try{r();}catch{}},Ne=()=>C?.token??"",ve=e=>(R.add(e),()=>{R.delete(e);}),J=()=>I||(I=ne(p()).then(e=>(e&&V(e),e)).finally(()=>{I=null;}),I);a$1()&&b$1.on(j$1,e=>{let n=u(e);n&&V(n);});var te=async()=>a$1()?C?C.token:(await J())?.token??"":"",we=async()=>a$1()?(await J())?.token??"":"",se=async()=>a$1()?re(p()):null;export{Ne as a,ve as b,te as c,we as d,se as e};
@@ -1,5 +1,3 @@
1
- import { A as AppEnvironment } from '../types-DryABknE.js';
2
-
3
1
  type HapticImpactStrength = "light" | "medium" | "heavy" | "soft" | "rigid";
4
2
  type HapticNotificationKind = "success" | "warning" | "error";
5
3
  interface PositionRequestOptions {
@@ -288,8 +286,6 @@ declare const sensors: {
288
286
 
289
287
  type DeviceFeature = "haptics" | "geolocation" | "sensors" | "camera" | "files" | "microphone";
290
288
 
291
- declare const meetsFeatureMinVersion: (feature: DeviceFeature, env: AppEnvironment) => boolean;
292
-
293
289
  declare const device: {
294
290
  readonly haptics: {
295
291
  isSupported(): boolean;
@@ -331,4 +327,4 @@ declare const device: {
331
327
  };
332
328
  };
333
329
 
334
- export { type AudioRecorder, type AudioRecording, type AudioRecordingOptions, type CameraFacing, type CapturedPhoto, type DeviceFeature, type HapticImpactStrength, type HapticNotificationKind, type MotionSample, type MotionWatchOptions, type OrientationSample, type PhotoCaptureOptions, type PhotoFormat, type PhotoQuality, type PickFilesOptions, type PickedFiles, type PositionRequestOptions, type PositionSample, type StreamOptions, type Vector3, camera, device, files, geolocation, haptics, meetsFeatureMinVersion, microphone, sensors };
330
+ export { type AudioRecorder, type AudioRecording, type AudioRecordingOptions, type CameraFacing, type CapturedPhoto, type DeviceFeature, type HapticImpactStrength, type HapticNotificationKind, type MotionSample, type MotionWatchOptions, type OrientationSample, type PhotoCaptureOptions, type PhotoFormat, type PhotoQuality, type PickFilesOptions, type PickedFiles, type PositionRequestOptions, type PositionSample, type StreamOptions, type Vector3, camera, device, files, geolocation, haptics, microphone, sensors };
@@ -1 +1 @@
1
- import {a,d as d$1,b as b$1,u,t,v,c,x as x$1,e,s,r,w}from'../chunk-ALNJCFV4.js';import {fileSave,directoryOpen,fileOpen}from'browser-fs-access';var G="device.haptics",C="device.geolocation",j="device.sensors.motion",z="device.sensors.orientation",Q="device.sensors.permission",K="device.camera",A="device.files",J="device.microphone",Y="device.microphone.permission",$="device.haptics.impact",X="device.haptics.selection",Z="device.haptics.notification",ee="device.haptics.vibrate",te="device.geolocation.get",ne="device.geolocation.watch.start",oe="device.geolocation.watch.stop",ie="device.sensors.motion.start",re="device.sensors.motion.stop",ae="device.sensors.orientation.start",se="device.sensors.orientation.stop",le="device.sensors.requestPermission",ce="device.camera.capture",ue="device.files.pick",de="device.files.save",me="device.microphone.record",pe="device.microphone.requestPermission",fe="device-request",ge="device-response";var ye={haptics:{iOS:null,Android:null},geolocation:{iOS:null,Android:null},sensors:{iOS:null,Android:null},camera:{iOS:null,Android:null},files:{iOS:null,Android:null},microphone:{iOS:null,Android:null}};var Ee=false,Ve=e=>typeof e!="object"||e===null?false:Reflect.get(e,"type")===ge&&typeof Reflect.get(e,"endpoint")=="string",T=()=>{!a()||Ee||(Ee=true,d$1(),window.addEventListener("message",e=>{let t=e.data;Ve(t)&&b$1.emit(t.endpoint,t.data??t);}));};var D=(e,t$1)=>{if(t$1.type!=="native_app"||!t$1.platform||!t$1.appVersion)return false;let n=ye[e][t$1.platform];return n?u(t(t$1.appVersion),n):false},b=e=>JSON.stringify(e),qe=()=>a()&&window.parent!==window,N=(e,t)=>{if(typeof e!="object"||e===null||Reflect.get(e,"ok")!==true)return null;let o=Reflect.get(e,"result");return t(o)},he=async e$1=>e$1.platform==="Android"?x$1(e,{pollIntervalMs:r,timeoutMs:s}):w(e),We=async e=>{let t=v();if(!D(e.feature,t))return null;let n=await he(t);if(!n)return null;let o=c(e.endpointPrefix),i=e.timeoutMs??3e3;return new Promise(r=>{let a=false,s=f=>{a||(a=true,l(),clearTimeout(u),r(f));},l=b$1.on(o,f=>{let h=N(f,e.parseResult);s(h);}),u=setTimeout(()=>s(null),i);try{n.postMessage({command:e.command,parameters:b({endpoint:o,timestamp:Date.now(),payload:e.payload})});}catch{s(null);}})},Ge=async e=>{if(!qe())return null;let t=c(e.endpointPrefix),n=e.timeoutMs??3e3;return new Promise(o=>{let i=false,r=l=>{i||(i=true,a(),clearTimeout(s),o(l));},a=b$1.on(t,l=>{let u=N(l,e.parseResult);r(u);}),s=setTimeout(()=>r(null),n);try{window.parent.postMessage({type:fe,command:e.command,parameters:b({endpoint:t,timestamp:Date.now(),payload:e.payload})},"*");}catch{r(null);}})},d=async e=>{if(!a())return null;T();let t=await We(e);return t!==null?t:Ge(e)},O=async e=>{if(!a())return null;T();let t=v();if(!D(e.feature,t))return null;let n=await he(t);if(!n)return null;let o=c(e.endpointPrefix),i=b$1.on(o,r=>{let a=N(r,e.parseEvent);a&&e.onEvent(a);});try{n.postMessage({command:e.startCommand,parameters:b({endpoint:o,timestamp:Date.now(),payload:e.payload})});}catch{return i(),null}return ()=>{i();try{n.postMessage({command:e.stopCommand,parameters:b({endpoint:o,timestamp:Date.now(),payload:null})});}catch{}}};var g=async e=>{if(!a())return e.safeDefault;let t=await e.native();if(t!==null)return t;try{let n=await e.web();if(n!==null)return n}catch{}return e.safeDefault};var Se=e=>e==="front"?"user":"environment",je={low:.5,medium:.8,high:.95},ze=e=>{let t=e.indexOf(",");if(t<0)return null;let n=e.slice(5,t),o=e.slice(t+1),r=/^([^;]+)/.exec(n)?.[1]??"application/octet-stream";try{if(/;base64/.test(n)){let s=atob(o),l=new Uint8Array(s.length);for(let u=0;u<s.length;u++)l[u]=s.charCodeAt(u);return new Blob([l],{type:r})}return new Blob([decodeURIComponent(o)],{type:r})}catch{return null}},Qe=e=>new Promise(t=>{let n=new FileReader;n.onload=()=>t(typeof n.result=="string"?n.result:null),n.onerror=()=>t(null),n.readAsDataURL(e);}),Ke=e=>new Promise(t=>{let n=new Image;n.onload=()=>{t({width:n.naturalWidth,height:n.naturalHeight}),n.remove();},n.onerror=()=>{t(null),n.remove();},n.src=e;}),Je=e=>{if(typeof e!="object"||e===null)return null;let t=Reflect.get(e,"dataUrl"),n=Reflect.get(e,"width"),o=Reflect.get(e,"height");if(typeof t!="string"||t.length===0||typeof n!="number"||typeof o!="number")return null;let i=ze(t);return i?{blob:i,dataUrl:t,width:n,height:o}:null},Ye=async(e,t)=>{if(t?.format!==void 0||t?.quality!==void 0||t?.width!==void 0||t?.height!==void 0)return null;let n=Reflect.get(window,"ImageCapture");if(typeof n!="function")return null;let o=e.getVideoTracks()[0];if(!o)return null;try{let r=await new n(o).takePhoto(),a=await Qe(r);if(!a)return null;let s=await Ke(a);return s?{blob:r,dataUrl:a,width:s.width,height:s.height}:null}catch{return null}},Pe=()=>new Promise(e=>requestAnimationFrame(()=>e())),x=(e,t,n)=>new Promise(o=>{let i=false,r=()=>{i||(i=true,window.clearTimeout(a),e.removeEventListener(t,r),o());},a=window.setTimeout(r,n);e.addEventListener(t,r,{once:true});}),Re=(e,t)=>new Promise(n=>{let o=e.requestVideoFrameCallback;if(!o){requestAnimationFrame(()=>requestAnimationFrame(()=>n()));return}let i=false,r=()=>{i||(i=true,window.clearTimeout(a),n());},a=window.setTimeout(r,t);o.call(e,r);}),$e=async e=>{let t=()=>e.videoWidth>0&&e.videoHeight>0;return t()||await x(e,"loadedmetadata",2e3),e.readyState<HTMLMediaElement.HAVE_CURRENT_DATA&&await x(e,"loadeddata",2e3),e.readyState<HTMLMediaElement.HAVE_CURRENT_DATA&&await x(e,"canplay",2e3),await Re(e,1e3),await Pe(),t()},Xe=e=>{if(e.videoWidth<=0||e.videoHeight<=0)return true;let t=document.createElement("canvas");t.width=24,t.height=24;let n=t.getContext("2d");if(!n)return false;try{n.drawImage(e,0,0,t.width,t.height);let o=n.getImageData(0,0,t.width,t.height).data,i=0,r=0;for(let s=0;s<o.length;s+=4){let l=o[s]*.2126+o[s+1]*.7152+o[s+2]*.0722;i=Math.max(i,l),r+=l;}let a=r/(o.length/4);return i<18&&a<6}catch{return false}},Ze=async(e,t)=>{let n=performance.now();for(;performance.now()-n<t;)if(await Re(e,700),await Pe(),!Xe(e))return},et=async e=>{if(!a()||!navigator.mediaDevices?.getUserMedia)return null;let t=null,n=null;try{t=await navigator.mediaDevices.getUserMedia({video:{facingMode:Se(e?.camera),width:e?.width,height:e?.height}});let o=await Ye(t,e);if(o)return o;if(n=document.createElement("video"),n.srcObject=t,n.autoplay=!0,n.muted=!0,n.playsInline=!0,n.style.position="fixed",n.style.left="0",n.style.top="0",n.style.width="2px",n.style.height="2px",n.style.opacity="0.01",n.style.pointerEvents="none",n.style.zIndex="-1",(document.body??document.documentElement).appendChild(n),await n.play(),!await $e(n))return null;await Ze(n,3e3);let a=e?.width??n.videoWidth??640,s=e?.height??n.videoHeight??480,l=document.createElement("canvas");l.width=a,l.height=s;let u=l.getContext("2d");if(!u)return null;u.drawImage(n,0,0,a,s);let h=`image/${e?.format??"jpeg"}`,E=je[e?.quality??"medium"],R=l.toDataURL(h,E),p=await new Promise(S=>{l.toBlob(Be=>S(Be),h,E);});return p?{blob:p,dataUrl:R,width:a,height:s}:null}catch{return null}finally{if(n&&(n.pause(),n.srcObject=null,n.remove()),t)for(let o of t.getTracks())o.stop();}},Te={isSupported(){return a()?!!navigator.mediaDevices?.getUserMedia:false},capturePhoto(e){return g({native:()=>d({feature:"camera",command:ce,endpointPrefix:K,payload:e??{},parseResult:Je,timeoutMs:6e4}),web:()=>et(e),safeDefault:null})},async openStream(e){if(!a()||!navigator.mediaDevices?.getUserMedia)return null;try{return await navigator.mediaDevices.getUserMedia({video:{facingMode:Se(e?.camera),width:e?.width,height:e?.height}})}catch{return null}},stopStream(e){try{for(let t of e.getTracks())t.stop();}catch{}}};var Me=(e,t)=>{let n=atob(e),o=new Uint8Array(n.length);for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);return new Blob([o],{type:t})},ot=e=>{let t=null;if(e.dataUrl){let n=e.dataUrl.indexOf(",");if(n>0){let o=e.dataUrl.slice(5,n),i=e.dataUrl.slice(n+1),r=/^([^;]+)/.exec(o)?.[1]??"application/octet-stream";try{t=/;base64/.test(o)?Me(i,r):new Blob([decodeURIComponent(i)],{type:r});}catch{t=null;}}}else e.base64&&(t=Me(e.base64,e.mime??"application/octet-stream"));return t?new File([t],e.name,{type:e.mime??t.type,lastModified:Date.now()}):null},it=e=>{if(typeof e!="object"||e===null)return null;let t=Reflect.get(e,"files");if(!Array.isArray(t))return null;let n=Reflect.get(e,"paths"),o=r=>{if(!Array.isArray(n))return;let a=n[r];return typeof a=="string"?a:void 0},i=[];for(let r=0;r<t.length;r++){let a=t[r];if(typeof a!="object"||a===null)continue;let s=a,l=ot(s);if(!l)continue;let u=typeof s.path=="string"?s.path:o(r);i.push(u!==void 0?{file:l,path:u}:{file:l});}return i.length===0?null:{files:i}},rt=e=>{let t=[],n=[];if(!e)return {mimeTypes:t,extensions:n};for(let o of e)for(let i of o.split(",")){let r=i.trim();r&&(r.startsWith(".")?n.push(r):t.push(r));}return {mimeTypes:t,extensions:n}},_e=e=>e instanceof DOMException&&e.name==="AbortError",be=e=>e.length>0?{files:e.map(t=>({file:t}))}:null,at=async e=>{if(!a())return null;try{if(e?.directory){let i=await directoryOpen({recursive:!0});return be(i)}let{mimeTypes:t,extensions:n}=rt(e?.accept);if(e?.multiple){let i=await fileOpen({mimeTypes:t,extensions:n,multiple:!0});return be(i)}return {files:[{file:await fileOpen({mimeTypes:t,extensions:n})}]}}catch(t){return _e(t),null}},st=async(e,t)=>{if(!a())return "failed";try{return await fileSave(e,{fileName:t}),"saved"}catch(n){return _e(n)?"cancelled":"failed"}},we={isPickerSupported(){return a()?typeof window.showOpenFilePicker=="function":false},pickFiles(e){return g({native:()=>d({feature:"files",command:ue,endpointPrefix:A,payload:e??{},parseResult:it,timeoutMs:6e4}),web:()=>at(e),safeDefault:null})},async saveFile(e,t){return a()?await d({feature:"files",command:de,endpointPrefix:A,payload:{filename:t,mime:e.type,size:e.size},parseResult:()=>true,timeoutMs:6e4})?"saved":st(e,t):"failed"},readAsText(e){return typeof e.text=="function"?e.text():new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{t(typeof o.result=="string"?o.result:"");},o.onerror=()=>n(o.error),o.readAsText(e);})},readAsDataUrl(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{t(typeof o.result=="string"?o.result:"");},o.onerror=()=>n(o.error),o.readAsDataURL(e);})}};var y=(e,...t)=>{for(let n of t){let o=Reflect.get(e,n);if(typeof o=="number"&&!Number.isNaN(o))return o}},Ie=e=>{if(typeof e!="object"||e===null)return null;let t=y(e,"latitude"),n=y(e,"longitude"),o=y(e,"accuracyMeters","accuracy");if(t===void 0||n===void 0||o===void 0)return null;let i={latitude:t,longitude:n,accuracyMeters:o,timestamp:y(e,"timestamp")??Date.now()},r=y(e,"altitudeMeters","altitude");r!==void 0&&(i.altitudeMeters=r);let a=y(e,"altitudeAccuracyMeters","altitudeAccuracy");a!==void 0&&(i.altitudeAccuracyMeters=a);let s=y(e,"headingDegrees","heading");s!==void 0&&(i.headingDegrees=s);let l=y(e,"speedMetersPerSecond","speed");return l!==void 0&&(i.speedMetersPerSecond=l),i},Ce=e=>({latitude:e.coords.latitude,longitude:e.coords.longitude,accuracyMeters:e.coords.accuracy,altitudeMeters:e.coords.altitude??void 0,altitudeAccuracyMeters:e.coords.altitudeAccuracy??void 0,headingDegrees:e.coords.heading??void 0,speedMetersPerSecond:e.coords.speed??void 0,timestamp:e.timestamp}),Ae=e=>e?{enableHighAccuracy:e.enableHighAccuracy,timeout:e.timeoutMs,maximumAge:e.maximumAgeMs}:void 0,lt=e=>!a()||!navigator.geolocation?Promise.resolve(null):new Promise(t=>{navigator.geolocation.getCurrentPosition(n=>t(Ce(n)),()=>t(null),Ae(e));}),De={isSupported(){return a()?!!navigator.geolocation:false},getCurrentPosition(e){return g({native:()=>d({feature:"geolocation",command:te,endpointPrefix:C,payload:e??{},parseResult:Ie,timeoutMs:e?.timeoutMs}),web:()=>lt(e),safeDefault:null})},watchPosition(e,t){let n=false,o=null,i=null;return O({feature:"geolocation",startCommand:ne,stopCommand:oe,endpointPrefix:C,payload:t??{},parseEvent:Ie,onEvent:r=>{n||e(r);}}).then(r=>{if(n){r?.();return}if(r){o=r;return}if(!(!a()||!navigator.geolocation))try{i=navigator.geolocation.watchPosition(a=>{n||e(Ce(a));},()=>{},Ae(t));}catch{}}),()=>{if(n=true,o&&o(),i!==null&&a()&&navigator.geolocation)try{navigator.geolocation.clearWatch(i);}catch{}}}};var ct={light:10,medium:20,heavy:40,soft:15,rigid:30},ut={success:[20,60,20],warning:[40,40,40],error:[50,30,100]},dt=e=>{if(typeof navigator>"u"||typeof navigator.vibrate!="function")return false;try{return navigator.vibrate(e)}catch{return false}},_=(e,t,n)=>g({native:()=>d({feature:"haptics",command:e,endpointPrefix:G,payload:t,parseResult:()=>true}),web:async()=>dt(n),safeDefault:false}),Ne={isSupported(){return a()?typeof navigator<"u"&&"vibrate"in navigator:false},async impact(e="medium"){await _($,{strength:e},ct[e]);},async selection(){await _(X,{},8);},async notification(e){await _(Z,{kind:e},ut[e]);},async vibrate(e){await _(ee,{pattern:e},e);}};var F=()=>{if(!a())return null;let e=window.MediaRecorder;return typeof e=="function"?e:null},Fe=()=>a()&&!!navigator.mediaDevices?.getUserMedia&&F()!==null,mt=e=>{let t=e.indexOf(",");if(t<0)return null;let n=e.slice(5,t),o=e.slice(t+1),r=/^([^;]+)/.exec(n)?.[1]??"application/octet-stream";try{if(/;base64/.test(n)){let a=atob(o),s=new Uint8Array(a.length);for(let l=0;l<a.length;l++)s[l]=a.charCodeAt(l);return new Blob([s],{type:r})}return new Blob([decodeURIComponent(o)],{type:r})}catch{return null}},pt=e=>{if(typeof e!="object"||e===null)return null;let t=Reflect.get(e,"dataUrl");if(typeof t!="string"||t.length===0)return null;let n=mt(t);if(!n)return null;let o=Reflect.get(e,"mimeType"),i=Reflect.get(e,"durationMs"),r=typeof o=="string"&&o.length>0?o:n.type||"audio/octet-stream",a=typeof i=="number"&&i>=0?i:0;return {blob:n,mimeType:r,durationMs:a,size:n.size}},ft=e=>{let t=F();if(!(!e||!t?.isTypeSupported))return t.isTypeSupported(e)?e:void 0},xe=async e=>{if(!Fe())return null;let t=F();if(!t)return null;let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0});}catch{return null}let o=()=>{for(let p of n.getTracks())p.stop();},i;try{i=new t(n,{mimeType:ft(e?.mimeType),audioBitsPerSecond:e?.audioBitsPerSecond});}catch{return o(),null}let r=[],a=Date.now(),s=false,l=false,u=null,f,h=new Promise(p=>{f=p;}),E=()=>{u!==null&&(clearTimeout(u),u=null);};i.ondataavailable=p=>{p.data&&p.data.size>0&&r.push(p.data);},i.onstop=()=>{if(E(),o(),s){f(null);return}let p=i.mimeType||e?.mimeType||"audio/webm",S=new Blob(r,{type:p});f(S.size===0?null:{blob:S,mimeType:S.type||p,durationMs:Date.now()-a,size:S.size});},i.onerror=()=>{E(),o(),f(null);};let R=()=>{if(!l){if(l=true,i.state==="inactive"){E(),o(),f(null);return}try{i.stop();}catch{E(),o(),f(null);}}};try{i.start();}catch{return o(),null}return e?.maxDurationMs&&e.maxDurationMs>0&&(u=setTimeout(R,e.maxDurationMs)),{get active(){return !l&&!s&&i.state==="recording"},stop(){return R(),h},cancel(){l||s||(s=true,R());}}},ke={isSupported(){return Fe()},async requestPermission(){if(!a())return false;let e=await d({feature:"microphone",command:pe,endpointPrefix:Y,payload:{},parseResult:t=>{if(typeof t=="boolean")return t;if(typeof t=="object"&&t!==null){let n=Reflect.get(t,"granted");if(typeof n=="boolean")return n}return null}});if(e!==null)return e;if(!a()||!navigator.mediaDevices?.getUserMedia)return false;try{let t=await navigator.mediaDevices.getUserMedia({audio:!0});for(let n of t.getTracks())n.stop();return !0}catch{return false}},async recordAudio(e){return g({native:()=>d({feature:"microphone",command:me,endpointPrefix:J,payload:e??{},parseResult:pt,timeoutMs:6e4}),web:async()=>{let n=await xe(e);if(!n)return null;let o=e?.maxDurationMs??6e4;return new Promise(i=>{setTimeout(()=>{n.stop().then(i);},o);})},safeDefault:null})},startRecording(e){return a()?xe(e):Promise.resolve(null)}};var Le=()=>typeof DeviceMotionEvent>"u"?false:typeof DeviceMotionEvent.requestPermission=="function",Ue=async()=>{if(!Le())return true;try{let e=DeviceMotionEvent.requestPermission;return e?await e()==="granted":!0}catch{return false}},m=(e,...t)=>{for(let n of t){let o=Reflect.get(e,n);if(typeof o=="number"&&!Number.isNaN(o))return o}},k=(e,t)=>{let n=Reflect.get(e,t);if(typeof n!="object"||n===null)return;let o=m(n,"x"),i=m(n,"y"),r=m(n,"z");if(!(o===void 0||i===void 0||r===void 0))return {x:o,y:i,z:r}},gt=e=>{if(typeof e!="object"||e===null)return null;let t=k(e,"accelerationWithGravity")??k(e,"accelerationIncludingGravity");if(!t)return null;let n=Reflect.get(e,"rotationRate"),o={alpha:0,beta:0,gamma:0};typeof n=="object"&&n!==null&&(o={alpha:m(n,"alpha")??0,beta:m(n,"beta")??0,gamma:m(n,"gamma")??0});let i={accelerationWithGravity:t,rotationRate:o,timestamp:m(e,"timestamp")??Date.now()},r=k(e,"acceleration");r&&(i.acceleration=r);let a=Reflect.get(e,"attitude");if(typeof a=="object"&&a!==null){let s=m(a,"yaw"),l=m(a,"pitch"),u=m(a,"roll");s!==void 0&&l!==void 0&&u!==void 0&&(i.attitude={yaw:s,pitch:l,roll:u});}return i},yt=e=>{if(typeof e!="object"||e===null)return null;let t=m(e,"alpha"),n=m(e,"beta"),o=m(e,"gamma");return t===void 0||n===void 0||o===void 0?null:{alpha:t,beta:n,gamma:o,timestamp:m(e,"timestamp")??Date.now()}},Et=e=>{let t=e.accelerationIncludingGravity,n=e.acceleration,o=e.rotationRate,i={accelerationWithGravity:{x:t?.x??0,y:t?.y??0,z:t?.z??0},rotationRate:{alpha:o?.alpha??0,beta:o?.beta??0,gamma:o?.gamma??0},timestamp:e.timeStamp||Date.now()};return n&&(n.x!==null||n.y!==null||n.z!==null)&&(i.acceleration={x:n.x??0,y:n.y??0,z:n.z??0}),i},vt=e=>({alpha:e.alpha??0,beta:e.beta??0,gamma:e.gamma??0,timestamp:e.timeStamp||Date.now()}),He={isMotionSupported(){return a()?typeof DeviceMotionEvent<"u":false},isOrientationSupported(){return a()?typeof DeviceOrientationEvent<"u":false},async requestMotionPermission(){if(!a())return false;let e=await d({feature:"sensors",command:le,endpointPrefix:Q,payload:{},parseResult:t=>{if(typeof t=="boolean")return t;if(typeof t=="object"&&t!==null){let n=Reflect.get(t,"granted");if(typeof n=="boolean")return n}return null}});return e!==null?e:Ue()},watchMotion(e,t){let n=false,o=null,i=null,r=()=>{if(n||!a())return;let s=l=>{n||e(Et(l));};window.addEventListener("devicemotion",s),i=s;};return (async()=>{let s=await O({feature:"sensors",startCommand:ie,stopCommand:re,endpointPrefix:j,payload:t??{},parseEvent:gt,onEvent:l=>{n||e(l);}});if(n){s?.();return}if(s){o=s;return}t?.autoRequestPermission&&Le()&&(!await Ue()||n)||r();})(),()=>{n=true,o&&o(),i&&a()&&(window.removeEventListener("devicemotion",i),i=null);}},watchOrientation(e){let t=false,n=null,o=null,i=()=>{if(t||!a())return;let a$1=s=>{t||e(vt(s));};window.addEventListener("deviceorientation",a$1),o=a$1;};return (async()=>{let a=await O({feature:"sensors",startCommand:ae,stopCommand:se,endpointPrefix:z,payload:{},parseEvent:yt,onEvent:s=>{t||e(s);}});if(t){a?.();return}if(a){n=a;return}i();})(),()=>{t=true,n&&n(),o&&a()&&(window.removeEventListener("deviceorientation",o),o=null);}}};T();var mn={haptics:Ne,geolocation:De,sensors:He,camera:Te,files:we,microphone:ke};export{Te as camera,mn as device,we as files,De as geolocation,Ne as haptics,D as meetsFeatureMinVersion,ke as microphone,He as sensors};
1
+ import {a,d as d$1,b,p as p$1,c,r,e,q as q$1}from'../chunk-H42VJJAC.js';import {fileSave,directoryOpen,fileOpen}from'browser-fs-access';var B="device.haptics",I="device.geolocation",H="device.sensors.motion",V="device.sensors.orientation",q="device.sensors.permission",W="device.camera",A="device.files",j="device.microphone",G="device.microphone.permission",z="device.haptics.impact",Q="device.haptics.selection",K="device.haptics.notification",Y="device.haptics.vibrate",J="device.geolocation.get",X="device.geolocation.watch.start",$="device.geolocation.watch.stop",Z="device.sensors.motion.start",ee="device.sensors.motion.stop",te="device.sensors.orientation.start",ne="device.sensors.orientation.stop",oe="device.sensors.requestPermission",ie="device.camera.capture",re="device.files.pick",ae="device.files.save",se="device.microphone.record",le="device.microphone.requestPermission",ce="device-request",ue="device-response";var de="NOT_SUPPORTED",me="USER_CANCELLED";var pe=false,He=e=>typeof e!="object"||e===null?false:Reflect.get(e,"type")===ue&&typeof Reflect.get(e,"endpoint")=="string",T=()=>{!a()||pe||(pe=true,d$1(),window.addEventListener("message",e=>{let n=e.data;He(n)&&b.emit(n.endpoint,n.data??n);}));};var w=e=>JSON.stringify(e),We=()=>a()&&window.parent!==window,je=(e,n)=>{let t=N(e,n);return t?.ok===true?t.result:null},N=(e,n)=>{if(typeof e!="object"||e===null)return null;let t=Reflect.get(e,"ok");if(t===true){let o=n(Reflect.get(e,"result"));return o===null?{ok:false}:{ok:true,result:o}}if(t===false){let o=Reflect.get(e,"errorCode"),i=Reflect.get(e,"errorMessage");return {ok:false,errorCode:typeof o=="string"?o:void 0,errorMessage:typeof i=="string"?i:void 0}}return null},ge=async e$1=>e$1.platform==="Android"?r(e,{pollIntervalMs:50,timeoutMs:1500}):q$1(e),Ge=async e=>{let n=await ve(e);return n?.ok===true?n.result:null},ve=async e=>{let n=p$1();if(n.type!=="native_app")return null;let t=await ge(n);if(!t)return null;let o=c(e.endpointPrefix),i=e.timeoutMs??3e3;return new Promise(r=>{let a=false,s=f=>{a||(a=true,l(),clearTimeout(u),r(f));},l=b.on(o,f=>{let h=N(f,e.parseResult);s(h);}),u=setTimeout(()=>s(null),i);try{t.postMessage({command:e.command,parameters:w({endpoint:o,timestamp:Date.now(),payload:e.payload})});}catch{s(null);}})},ze=async e=>{let n=await ye(e);return n?.ok===true?n.result:null},ye=async e=>{if(!We())return null;let n=c(e.endpointPrefix),t=e.timeoutMs??3e3;return new Promise(o=>{let i=false,r=l=>{i||(i=true,a(),clearTimeout(s),o(l));},a=b.on(n,l=>{let u=N(l,e.parseResult);r(u);}),s=setTimeout(()=>r(null),t);try{window.parent.postMessage({type:ce,command:e.command,parameters:w({endpoint:n,timestamp:Date.now(),payload:e.payload})},"*");}catch{r(null);}})},p=async e=>{if(!a())return null;T();let n=await Ge(e);return n!==null?n:ze(e)},Ee=async e=>{if(!a())return null;T();let n=await ve(e);return n!==null?n:ye(e)},O=async e=>{if(!a())return null;T();let n=p$1();if(n.type!=="native_app")return null;let t=await ge(n);if(!t)return null;let o=c(e.endpointPrefix),i=b.on(o,r=>{let a=je(r,e.parseEvent);a&&e.onEvent(a);});try{t.postMessage({command:e.startCommand,parameters:w({endpoint:o,timestamp:Date.now(),payload:e.payload})});}catch{return i(),null}return ()=>{i();try{t.postMessage({command:e.stopCommand,parameters:w({endpoint:o,timestamp:Date.now(),payload:null})});}catch{}}};var g=async e=>{if(!a())return e.safeDefault;let n=await e.native();if(n!==null)return n;try{let t=await e.web();if(t!==null)return t}catch{}return e.safeDefault};var he=e=>e==="front"?"user":"environment",Qe={low:.5,medium:.8,high:.95},Ke=e=>{let n=e.indexOf(",");if(n<0)return null;let t=e.slice(5,n),o=e.slice(n+1),r=/^([^;]+)/.exec(t)?.[1]??"application/octet-stream";try{if(/;base64/.test(t)){let s=atob(o),l=new Uint8Array(s.length);for(let u=0;u<s.length;u++)l[u]=s.charCodeAt(u);return new Blob([l],{type:r})}return new Blob([decodeURIComponent(o)],{type:r})}catch{return null}},Ye=e=>new Promise(n=>{let t=new FileReader;t.onload=()=>n(typeof t.result=="string"?t.result:null),t.onerror=()=>n(null),t.readAsDataURL(e);}),Je=e=>new Promise(n=>{let t=new Image;t.onload=()=>{n({width:t.naturalWidth,height:t.naturalHeight}),t.remove();},t.onerror=()=>{n(null),t.remove();},t.src=e;}),Xe=e=>{if(typeof e!="object"||e===null)return null;let n=Reflect.get(e,"dataUrl"),t=Reflect.get(e,"width"),o=Reflect.get(e,"height");if(typeof n!="string"||n.length===0||typeof t!="number"||typeof o!="number")return null;let i=Ke(n);return i?{blob:i,dataUrl:n,width:t,height:o}:null},$e=async(e,n)=>{if(n?.format!==void 0||n?.quality!==void 0||n?.width!==void 0||n?.height!==void 0)return null;let t=Reflect.get(window,"ImageCapture");if(typeof t!="function")return null;let o=e.getVideoTracks()[0];if(!o)return null;try{let r=await new t(o).takePhoto(),a=await Ye(r);if(!a)return null;let s=await Je(a);return s?{blob:r,dataUrl:a,width:s.width,height:s.height}:null}catch{return null}},Pe=()=>new Promise(e=>requestAnimationFrame(()=>e())),D=(e,n,t)=>new Promise(o=>{let i=false,r=()=>{i||(i=true,window.clearTimeout(a),e.removeEventListener(n,r),o());},a=window.setTimeout(r,t);e.addEventListener(n,r,{once:true});}),Se=(e,n)=>new Promise(t=>{let o=e.requestVideoFrameCallback;if(!o){requestAnimationFrame(()=>requestAnimationFrame(()=>t()));return}let i=false,r=()=>{i||(i=true,window.clearTimeout(a),t());},a=window.setTimeout(r,n);o.call(e,r);}),Ze=async e=>{let n=()=>e.videoWidth>0&&e.videoHeight>0;return n()||await D(e,"loadedmetadata",2e3),e.readyState<HTMLMediaElement.HAVE_CURRENT_DATA&&await D(e,"loadeddata",2e3),e.readyState<HTMLMediaElement.HAVE_CURRENT_DATA&&await D(e,"canplay",2e3),await Se(e,1e3),await Pe(),n()},et=e=>{if(e.videoWidth<=0||e.videoHeight<=0)return true;let n=document.createElement("canvas");n.width=24,n.height=24;let t=n.getContext("2d");if(!t)return false;try{t.drawImage(e,0,0,n.width,n.height);let o=t.getImageData(0,0,n.width,n.height).data,i=0,r=0;for(let s=0;s<o.length;s+=4){let l=o[s]*.2126+o[s+1]*.7152+o[s+2]*.0722;i=Math.max(i,l),r+=l;}let a=r/(o.length/4);return i<18&&a<6}catch{return false}},tt=async(e,n)=>{let t=performance.now();for(;performance.now()-t<n;)if(await Se(e,700),await Pe(),!et(e))return},nt=async e=>{if(!a()||!navigator.mediaDevices?.getUserMedia)return null;let n=null,t=null;try{n=await navigator.mediaDevices.getUserMedia({video:{facingMode:he(e?.camera),width:e?.width,height:e?.height}});let o=await $e(n,e);if(o)return o;if(t=document.createElement("video"),t.srcObject=n,t.autoplay=!0,t.muted=!0,t.playsInline=!0,t.style.position="fixed",t.style.left="0",t.style.top="0",t.style.width="2px",t.style.height="2px",t.style.opacity="0.01",t.style.pointerEvents="none",t.style.zIndex="-1",(document.body??document.documentElement).appendChild(t),await t.play(),!await Ze(t))return null;await tt(t,3e3);let a=e?.width??t.videoWidth??640,s=e?.height??t.videoHeight??480,l=document.createElement("canvas");l.width=a,l.height=s;let u=l.getContext("2d");if(!u)return null;u.drawImage(t,0,0,a,s);let h=`image/${e?.format??"jpeg"}`,y=Qe[e?.quality??"medium"],M=l.toDataURL(h,y),m=await new Promise(P=>{l.toBlob(Be=>P(Be),h,y);});return m?{blob:m,dataUrl:M,width:a,height:s}:null}catch{return null}finally{if(t&&(t.pause(),t.srcObject=null,t.remove()),n)for(let o of n.getTracks())o.stop();}},Re={isSupported(){return a()?!!navigator.mediaDevices?.getUserMedia:false},capturePhoto(e){return g({native:()=>p({feature:"camera",command:ie,endpointPrefix:W,payload:e??{},parseResult:Xe,timeoutMs:6e4}),web:()=>nt(e),safeDefault:null})},async openStream(e){if(!a()||!navigator.mediaDevices?.getUserMedia)return null;try{return await navigator.mediaDevices.getUserMedia({video:{facingMode:he(e?.camera),width:e?.width,height:e?.height}})}catch{return null}},stopStream(e){try{for(let n of e.getTracks())n.stop();}catch{}}};var rt=8*1024*1024,Me=(e,n)=>{let t=atob(e),o=new Uint8Array(t.length);for(let i=0;i<t.length;i++)o[i]=t.charCodeAt(i);return new Blob([o],{type:n})},at=e=>{let n=null;if(e.dataUrl){let t=e.dataUrl.indexOf(",");if(t>0){let o=e.dataUrl.slice(5,t),i=e.dataUrl.slice(t+1),r=/^([^;]+)/.exec(o)?.[1]??"application/octet-stream";try{n=/;base64/.test(o)?Me(i,r):new Blob([decodeURIComponent(i)],{type:r});}catch{n=null;}}}else e.base64&&(n=Me(e.base64,e.mime??"application/octet-stream"));return n?new File([n],e.name,{type:e.mime??n.type,lastModified:Date.now()}):null},st=e=>{if(typeof e!="object"||e===null)return null;let n=Reflect.get(e,"files");if(!Array.isArray(n))return null;let t=Reflect.get(e,"paths"),o=r=>{if(!Array.isArray(t))return;let a=t[r];return typeof a=="string"?a:void 0},i=[];for(let r=0;r<n.length;r++){let a=n[r];if(typeof a!="object"||a===null)continue;let s=a,l=at(s);if(!l)continue;let u=typeof s.path=="string"?s.path:o(r);i.push(u!==void 0?{file:l,path:u}:{file:l});}return i.length===0?null:{files:i}},lt=e=>{let n=[],t=[];if(!e)return {mimeTypes:n,extensions:t};for(let o of e)for(let i of o.split(",")){let r=i.trim();r&&(r.startsWith(".")?t.push(r):n.push(r));}return {mimeTypes:n,extensions:t}},be=e=>e instanceof DOMException&&e.name==="AbortError",Oe=e=>e.length>0?{files:e.map(n=>({file:n}))}:null,ct=async e=>{if(!a())return null;try{if(e?.directory){let i=await directoryOpen({recursive:!0});return Oe(i)}let{mimeTypes:n,extensions:t}=lt(e?.accept);if(e?.multiple){let i=await fileOpen({mimeTypes:n,extensions:t,multiple:!0});return Oe(i)}return {files:[{file:await fileOpen({mimeTypes:n,extensions:t})}]}}catch(n){return be(n),null}},ut=async(e,n)=>{if(!a())return "failed";try{return await fileSave(e,{fileName:n}),"saved"}catch(t){return be(t)?"cancelled":"failed"}},dt=e=>new Promise(n=>{let t=new FileReader;t.onload=()=>{let o=typeof t.result=="string"?t.result:"",i=o.indexOf(",");n(i>=0?o.slice(i+1):null);},t.onerror=()=>n(null),t.readAsDataURL(e);}),mt=e=>e===true?true:typeof e!="object"||e===null?null:Reflect.get(e,"saved")===true?true:null,we={isPickerSupported(){return a()?typeof window.showOpenFilePicker=="function":false},pickFiles(e){return g({native:()=>p({feature:"files",command:re,endpointPrefix:A,payload:e??{},parseResult:st,timeoutMs:6e4}),web:()=>ct(e),safeDefault:null})},async saveFile(e,n){if(!a())return "failed";if(e.size<=rt){let t=await dt(e);if(t!==null){let o=await Ee({feature:"files",command:ae,endpointPrefix:A,payload:{filename:n,mime:e.type||"application/octet-stream",size:e.size,base64:t},parseResult:mt,timeoutMs:6e4});if(o?.ok===true)return "saved";if(o?.ok===false){if(o.errorCode===me)return "cancelled";if(o.errorCode!==de||p$1().type==="native_app")return "failed"}}}return p$1().type==="native_app"?"failed":ut(e,n)},readAsText(e){return typeof e.text=="function"?e.text():new Promise((n,t)=>{let o=new FileReader;o.onload=()=>{n(typeof o.result=="string"?o.result:"");},o.onerror=()=>t(o.error),o.readAsText(e);})},readAsDataUrl(e){return new Promise((n,t)=>{let o=new FileReader;o.onload=()=>{n(typeof o.result=="string"?o.result:"");},o.onerror=()=>t(o.error),o.readAsDataURL(e);})}};var v=(e,...n)=>{for(let t of n){let o=Reflect.get(e,t);if(typeof o=="number"&&!Number.isNaN(o))return o}},_e=e=>{if(typeof e!="object"||e===null)return null;let n=v(e,"latitude"),t=v(e,"longitude"),o=v(e,"accuracyMeters","accuracy");if(n===void 0||t===void 0||o===void 0)return null;let i={latitude:n,longitude:t,accuracyMeters:o,timestamp:v(e,"timestamp")??Date.now()},r=v(e,"altitudeMeters","altitude");r!==void 0&&(i.altitudeMeters=r);let a=v(e,"altitudeAccuracyMeters","altitudeAccuracy");a!==void 0&&(i.altitudeAccuracyMeters=a);let s=v(e,"headingDegrees","heading");s!==void 0&&(i.headingDegrees=s);let l=v(e,"speedMetersPerSecond","speed");return l!==void 0&&(i.speedMetersPerSecond=l),i},Ce=e=>({latitude:e.coords.latitude,longitude:e.coords.longitude,accuracyMeters:e.coords.accuracy,altitudeMeters:e.coords.altitude??void 0,altitudeAccuracyMeters:e.coords.altitudeAccuracy??void 0,headingDegrees:e.coords.heading??void 0,speedMetersPerSecond:e.coords.speed??void 0,timestamp:e.timestamp}),Ie=e=>e?{enableHighAccuracy:e.enableHighAccuracy,timeout:e.timeoutMs,maximumAge:e.maximumAgeMs}:void 0,pt=e=>!a()||!navigator.geolocation?Promise.resolve(null):new Promise(n=>{navigator.geolocation.getCurrentPosition(t=>n(Ce(t)),()=>n(null),Ie(e));}),Ae={isSupported(){return a()?!!navigator.geolocation:false},getCurrentPosition(e){return g({native:()=>p({feature:"geolocation",command:J,endpointPrefix:I,payload:e??{},parseResult:_e,timeoutMs:e?.timeoutMs}),web:()=>pt(e),safeDefault:null})},watchPosition(e,n){let t=false,o=null,i=null;return O({feature:"geolocation",startCommand:X,stopCommand:$,endpointPrefix:I,payload:n??{},parseEvent:_e,onEvent:r=>{t||e(r);}}).then(r=>{if(t){r?.();return}if(r){o=r;return}if(!(!a()||!navigator.geolocation))try{i=navigator.geolocation.watchPosition(a=>{t||e(Ce(a));},()=>{},Ie(n));}catch{}}),()=>{if(t=true,o&&o(),i!==null&&a()&&navigator.geolocation)try{navigator.geolocation.clearWatch(i);}catch{}}}};var ft={light:10,medium:20,heavy:40,soft:15,rigid:30},gt={success:[20,60,20],warning:[40,40,40],error:[50,30,100]},vt=e=>{if(typeof navigator>"u"||typeof navigator.vibrate!="function")return false;try{return navigator.vibrate(e)}catch{return false}},_=(e,n,t)=>g({native:()=>p({feature:"haptics",command:e,endpointPrefix:B,payload:n,parseResult:()=>true}),web:async()=>vt(t),safeDefault:false}),Ne={isSupported(){return a()?typeof navigator<"u"&&"vibrate"in navigator:false},async impact(e="medium"){await _(z,{strength:e},ft[e]);},async selection(){await _(Q,{},8);},async notification(e){await _(K,{kind:e},gt[e]);},async vibrate(e){await _(Y,{pattern:e},e);}};var x=()=>{if(!a())return null;let e=window.MediaRecorder;return typeof e=="function"?e:null},xe=()=>a()&&!!navigator.mediaDevices?.getUserMedia&&x()!==null,yt=e=>{let n=e.indexOf(",");if(n<0)return null;let t=e.slice(5,n),o=e.slice(n+1),r=/^([^;]+)/.exec(t)?.[1]??"application/octet-stream";try{if(/;base64/.test(t)){let a=atob(o),s=new Uint8Array(a.length);for(let l=0;l<a.length;l++)s[l]=a.charCodeAt(l);return new Blob([s],{type:r})}return new Blob([decodeURIComponent(o)],{type:r})}catch{return null}},Et=e=>{if(typeof e!="object"||e===null)return null;let n=Reflect.get(e,"dataUrl");if(typeof n!="string"||n.length===0)return null;let t=yt(n);if(!t)return null;let o=Reflect.get(e,"mimeType"),i=Reflect.get(e,"durationMs"),r=typeof o=="string"&&o.length>0?o:t.type||"audio/octet-stream",a=typeof i=="number"&&i>=0?i:0;return {blob:t,mimeType:r,durationMs:a,size:t.size}},ht=e=>{let n=x();if(!(!e||!n?.isTypeSupported))return n.isTypeSupported(e)?e:void 0},De=async e=>{if(!xe())return null;let n=x();if(!n)return null;let t;try{t=await navigator.mediaDevices.getUserMedia({audio:!0});}catch{return null}let o=()=>{for(let m of t.getTracks())m.stop();},i;try{i=new n(t,{mimeType:ht(e?.mimeType),audioBitsPerSecond:e?.audioBitsPerSecond});}catch{return o(),null}let r=[],a=Date.now(),s=false,l=false,u=null,f,h=new Promise(m=>{f=m;}),y=()=>{u!==null&&(clearTimeout(u),u=null);};i.ondataavailable=m=>{m.data&&m.data.size>0&&r.push(m.data);},i.onstop=()=>{if(y(),o(),s){f(null);return}let m=i.mimeType||e?.mimeType||"audio/webm",P=new Blob(r,{type:m});f(P.size===0?null:{blob:P,mimeType:P.type||m,durationMs:Date.now()-a,size:P.size});},i.onerror=()=>{y(),o(),f(null);};let M=()=>{if(!l){if(l=true,i.state==="inactive"){y(),o(),f(null);return}try{i.stop();}catch{y(),o(),f(null);}}};try{i.start();}catch{return o(),null}return e?.maxDurationMs&&e.maxDurationMs>0&&(u=setTimeout(M,e.maxDurationMs)),{get active(){return !l&&!s&&i.state==="recording"},stop(){return M(),h},cancel(){l||s||(s=true,M());}}},ke={isSupported(){return xe()},async requestPermission(){if(!a())return false;let e=await p({feature:"microphone",command:le,endpointPrefix:G,payload:{},parseResult:n=>{if(typeof n=="boolean")return n;if(typeof n=="object"&&n!==null){let t=Reflect.get(n,"granted");if(typeof t=="boolean")return t}return null}});if(e!==null)return e;if(!a()||!navigator.mediaDevices?.getUserMedia)return false;try{let n=await navigator.mediaDevices.getUserMedia({audio:!0});for(let t of n.getTracks())t.stop();return !0}catch{return false}},async recordAudio(e){return g({native:()=>p({feature:"microphone",command:se,endpointPrefix:j,payload:e??{},parseResult:Et,timeoutMs:6e4}),web:async()=>{let t=await De(e);if(!t)return null;let o=e?.maxDurationMs??6e4;return new Promise(i=>{setTimeout(()=>{t.stop().then(i);},o);})},safeDefault:null})},startRecording(e){return a()?De(e):Promise.resolve(null)}};var Ue=()=>typeof DeviceMotionEvent>"u"?false:typeof DeviceMotionEvent.requestPermission=="function",Fe=async()=>{if(!Ue())return true;try{let e=DeviceMotionEvent.requestPermission;return e?await e()==="granted":!0}catch{return false}},d=(e,...n)=>{for(let t of n){let o=Reflect.get(e,t);if(typeof o=="number"&&!Number.isNaN(o))return o}},k=(e,n)=>{let t=Reflect.get(e,n);if(typeof t!="object"||t===null)return;let o=d(t,"x"),i=d(t,"y"),r=d(t,"z");if(!(o===void 0||i===void 0||r===void 0))return {x:o,y:i,z:r}},Pt=e=>{if(typeof e!="object"||e===null)return null;let n=k(e,"accelerationWithGravity")??k(e,"accelerationIncludingGravity");if(!n)return null;let t=Reflect.get(e,"rotationRate"),o={alpha:0,beta:0,gamma:0};typeof t=="object"&&t!==null&&(o={alpha:d(t,"alpha")??0,beta:d(t,"beta")??0,gamma:d(t,"gamma")??0});let i={accelerationWithGravity:n,rotationRate:o,timestamp:d(e,"timestamp")??Date.now()},r=k(e,"acceleration");r&&(i.acceleration=r);let a=Reflect.get(e,"attitude");if(typeof a=="object"&&a!==null){let s=d(a,"yaw"),l=d(a,"pitch"),u=d(a,"roll");s!==void 0&&l!==void 0&&u!==void 0&&(i.attitude={yaw:s,pitch:l,roll:u});}return i},St=e=>{if(typeof e!="object"||e===null)return null;let n=d(e,"alpha"),t=d(e,"beta"),o=d(e,"gamma");return n===void 0||t===void 0||o===void 0?null:{alpha:n,beta:t,gamma:o,timestamp:d(e,"timestamp")??Date.now()}},Rt=e=>{let n=e.accelerationIncludingGravity,t=e.acceleration,o=e.rotationRate,i={accelerationWithGravity:{x:n?.x??0,y:n?.y??0,z:n?.z??0},rotationRate:{alpha:o?.alpha??0,beta:o?.beta??0,gamma:o?.gamma??0},timestamp:e.timeStamp||Date.now()};return t&&(t.x!==null||t.y!==null||t.z!==null)&&(i.acceleration={x:t.x??0,y:t.y??0,z:t.z??0}),i},Tt=e=>({alpha:e.alpha??0,beta:e.beta??0,gamma:e.gamma??0,timestamp:e.timeStamp||Date.now()}),Le={isMotionSupported(){return a()?typeof DeviceMotionEvent<"u":false},isOrientationSupported(){return a()?typeof DeviceOrientationEvent<"u":false},async requestMotionPermission(){if(!a())return false;let e=await p({feature:"sensors",command:oe,endpointPrefix:q,payload:{},parseResult:n=>{if(typeof n=="boolean")return n;if(typeof n=="object"&&n!==null){let t=Reflect.get(n,"granted");if(typeof t=="boolean")return t}return null}});return e!==null?e:Fe()},watchMotion(e,n){let t=false,o=null,i=null,r=()=>{if(t||!a())return;let s=l=>{t||e(Rt(l));};window.addEventListener("devicemotion",s),i=s;};return (async()=>{let s=await O({feature:"sensors",startCommand:Z,stopCommand:ee,endpointPrefix:H,payload:n??{},parseEvent:Pt,onEvent:l=>{t||e(l);}});if(t){s?.();return}if(s){o=s;return}n?.autoRequestPermission&&Ue()&&(!await Fe()||t)||r();})(),()=>{t=true,o&&o(),i&&a()&&(window.removeEventListener("devicemotion",i),i=null);}},watchOrientation(e){let n=false,t=null,o=null,i=()=>{if(n||!a())return;let a$1=s=>{n||e(Tt(s));};window.addEventListener("deviceorientation",a$1),o=a$1;};return (async()=>{let a=await O({feature:"sensors",startCommand:te,stopCommand:ne,endpointPrefix:V,payload:{},parseEvent:St,onEvent:s=>{n||e(s);}});if(n){a?.();return}if(a){t=a;return}i();})(),()=>{n=true,t&&t(),o&&a()&&(window.removeEventListener("deviceorientation",o),o=null);}}};T();var yn={haptics:Ne,geolocation:Ae,sensors:Le,camera:Re,files:we,microphone:ke};export{Re as camera,yn as device,we as files,Ae as geolocation,Ne as haptics,ke as microphone,Le as sensors};
@@ -1,4 +1,4 @@
1
- import { U as UserInfo } from '../types-DryABknE.js';
1
+ import { U as UserInfo } from '../types-CLujY9ck.js';
2
2
 
3
3
  interface UseAuthTokenResult {
4
4
  token: string;
@@ -1 +1 @@
1
- import {b,a,c,e}from'../chunk-AKZVV563.js';import'../chunk-ALNJCFV4.js';import {useSyncExternalStore,useState,useCallback,useEffect}from'react';var k="",d=()=>{let u=useSyncExternalStore(b,a,()=>k),[s,e]=useState(()=>a()===""),t=useCallback(async()=>{e(true),await c(),e(false);},[]);return useEffect(()=>{if(a()!==""){e(false);return}let o=true;return c().then(()=>{o&&e(false);}),()=>{o=false;}},[]),{token:u,loading:s,refetch:t}};var I=()=>{let[u,s]=useState(null),[e$1,t]=useState(true),o=useCallback(async()=>{t(true);let r=await e();s(r),t(false);},[]);return useEffect(()=>{let r=true;return e().then(c=>{r&&(s(c),t(false));}),()=>{r=false;}},[]),{user:u,loading:e$1,refetch:o}};export{d as useAuthToken,I as useUserInfo};
1
+ import {b,a,c,e}from'../chunk-V73IHZAF.js';import'../chunk-H42VJJAC.js';import {useSyncExternalStore,useState,useCallback,useEffect}from'react';var k="",d=()=>{let u=useSyncExternalStore(b,a,()=>k),[s,e]=useState(()=>a()===""),t=useCallback(async()=>{e(true),await c(),e(false);},[]);return useEffect(()=>{if(a()!==""){e(false);return}let o=true;return c().then(()=>{o&&e(false);}),()=>{o=false;}},[]),{token:u,loading:s,refetch:t}};var I=()=>{let[u,s]=useState(null),[e$1,t]=useState(true),o=useCallback(async()=>{t(true);let r=await e();s(r),t(false);},[]);return useEffect(()=>{let r=true;return e().then(c=>{r&&(s(c),t(false));}),()=>{r=false;}},[]),{user:u,loading:e$1,refetch:o}};export{d as useAuthToken,I as useUserInfo};
@@ -0,0 +1,15 @@
1
+ interface Credentials {
2
+ uid: string;
3
+ token: string;
4
+ }
5
+ interface UserInfo {
6
+ userId: string | number;
7
+ username?: string;
8
+ nickname?: string;
9
+ avatar?: string | null;
10
+ phone?: string | null;
11
+ email?: string;
12
+ [key: string]: unknown;
13
+ }
14
+
15
+ export type { Credentials as C, UserInfo as U };
@@ -1,5 +1,5 @@
1
- import { U as UserInfo } from '../types-DryABknE.js';
2
- export { C as Credentials } from '../types-DryABknE.js';
1
+ import { U as UserInfo } from '../types-CLujY9ck.js';
2
+ export { C as Credentials } from '../types-CLujY9ck.js';
3
3
 
4
4
  declare const getAuthTokenAsync: () => Promise<string>;
5
5
  declare const getUserInfoAsync: () => Promise<UserInfo | null>;
@@ -1 +1 @@
1
- export{c as getAuthTokenAsync,e as getUserInfoAsync}from'../chunk-AKZVV563.js';import'../chunk-ALNJCFV4.js';
1
+ export{c as getAuthTokenAsync,e as getUserInfoAsync}from'../chunk-V73IHZAF.js';import'../chunk-H42VJJAC.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bty/feed_app-runtime-sdk",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "browser": true,
6
6
  "description": "Runtime SDK for feed-app template: auth / AI capabilities, multi-environment bridge (native App / iframe / web).",
@@ -1 +0,0 @@
1
- import {a as a$1,b,j as j$1,d,f,g,k,o,m,v,q,x,e,s,r,w,c as c$1,p,l,n,h,i}from'./chunk-ALNJCFV4.js';var E=e=>typeof e=="object"&&e!==null,a=(e,n)=>{if(e)for(let t of n){let r=e[t];if(typeof r=="string"&&r.length>0)return r}},$=(e,n)=>{if(e)for(let t of n){let r=e[t];if(typeof r=="string"&&r.length>0||typeof r=="number"&&Number.isFinite(r))return r}},u=e=>{if(!E(e))return null;let n=E(e.credentials)?e.credentials:void 0,t=E(e.user)?e.user:void 0,r=a(e,["uid","userId","id"])??a(n,["uid","userId","id"])??a(t,["uid","userId","id"]),o=a(e,["token","authToken"])??a(n,["token","authToken"]);return !r||!o?null:{uid:r,token:o}},c=e=>{if(!E(e))return null;let n=E(e.data)?e.data:e,t=$(n,["userId","id","uid"]);if(t===void 0)return null;let r=a(n,["username","nickname","nickName","name"]),o=a(n,["nickname","nickName","username"]);return {...n,userId:t,...r?{username:r}:{},...o?{nickname:o}:{}}};var ee=e=>typeof e!="object"||e===null?false:typeof Reflect.get(e,"type")=="string",H=false,V=()=>{!a$1()||H||(H=true,d(),Reflect.set(window,f,e=>{u(e)&&b.emit(j$1,e);}),Reflect.set(window,g,e=>{c(e)&&b.emit(k,e);}),window.addEventListener("message",e=>{let n=e.data;if(ee(n))switch(n.type){case m:b.emit("iframe.credentials",n);break;case o:b.emit("iframe.userinfo",n);break}}));};var j=(e,n,t)=>new Promise(r=>{let o=false,f=i=>{o||(o=true,y(),clearTimeout(T),r(i));},y=b.on(n,i=>{let g=t(i);g&&f(g);}),T=setTimeout(()=>f(null),q);try{window.parent.postMessage({type:e,timestamp:Date.now()},"*");}catch{f(null);}}),G=()=>j(l,"iframe.credentials",u),Q=()=>j(n,"iframe.userinfo",c);var J=async(e$1,n,t,r$1)=>{let o=e$1.platform==="Android"?await x(e,{pollIntervalMs:r,timeoutMs:s}):w(e);if(!o)return null;let f=c$1(t);return new Promise(y=>{let T=false,i=d=>{T||(T=true,g(),Y(),clearTimeout(Z),y(d));},g=b.on(f,d=>{let p=r$1(d);p&&i(p);}),Y=b.on(t,d=>{let p=r$1(d);p&&i(p);}),Z=setTimeout(()=>i(null),p);try{o.postMessage({command:n,parameters:JSON.stringify({timestamp:Date.now(),endpoint:f})});}catch{i(null);}})},z=e=>J(e,h,j$1,u),K=e=>J(e,i,k,c);V();var C=null,I=null,R=new Set,ne=e=>{switch(e.type){case "native_app":return e.meetsMinVersion?z(e):Promise.resolve(null);case "iframe":return G();case "web":return Promise.resolve(null)}},re=e=>{switch(e.type){case "native_app":return e.meetsMinVersion?K(e):Promise.resolve(null);case "iframe":return Q();case "web":return Promise.resolve(null)}},W=e=>{let n=C?.token??"",t=e?.token??"";if(C=e,n!==t)for(let r of R)try{r();}catch{}},Ne=()=>C?.token??"",ve=e=>(R.add(e),()=>{R.delete(e);}),X=()=>I||(I=ne(v()).then(e=>(e&&W(e),e)).finally(()=>{I=null;}),I);a$1()&&b.on(j$1,e=>{let n=u(e);n&&W(n);});var te=async()=>a$1()?C?C.token:(await X())?.token??"":"",Pe=async()=>a$1()?(await X())?.token??"":"",se=async()=>a$1()?re(v()):null;export{Ne as a,ve as b,te as c,Pe as d,se as e};
@@ -1 +0,0 @@
1
- var o=()=>typeof window<"u"&&typeof document<"u";var _="hostRuntime",p=class{listeners=new Map;on(e,t){let s=this.listeners.get(e),r=s??new Set;return s||this.listeners.set(e,r),r.add(t),()=>{r.delete(t),r.size===0&&this.listeners.delete(e);}}emit(e,t){let s=this.listeners.get(e);if(s)for(let r of s)r(t);}},R=new p,a=0,A=n=>(a+=1,`${n}.${a}`),l=false,I=()=>{if(!o()||l)return;l=true,Reflect.set(window,_,{receiveMessage(e){if(!e)return;let t=e.endpoint;t&&R.emit(t,e.data??e);}});};var E="HostApp",v="hostListener";var O="processUserCredentials",L="processUserInfo",H="user.getCredentials",b="user.getUserInfo",P="user.credentials",U="user.info",k="user-credentials-request",y="user-credentials-response",F="user-info-request",h="user-info-response",f={iOS:[1,6,7],Android:[1,1,8]},C=3e3,D=500,V=50,B=1500;var d=n=>{let e=n.split(".").map(t=>Number.parseInt(t,10));return [e[0]??0,e[1]??0,e[2]??0]},m=(n,e)=>{for(let t=0;t<3;t++){if(n[t]>e[t])return true;if(n[t]<e[t])return false}return true};var N=new RegExp(`${E}\\/(\\d+\\.\\d+\\.\\d+)\\/(\\d+)\\/(iOS|Android)`),g=n=>{let e=n.match(N);if(!e)return null;let[,t,s,r]=e;if(!t||!s||r!=="iOS"&&r!=="Android")return null;let i=m(d(t),f[r]);return {type:"native_app",platform:r,appVersion:t,buildNumber:s,meetsMinVersion:i}},Q=()=>{if(!o())return {type:"web",meetsMinVersion:false};let n=g(navigator.userAgent??"");return n||(window.parent!==window?{type:"iframe",meetsMinVersion:false}:{type:"web",meetsMinVersion:false})};var S=n=>typeof n!="object"||n===null?false:typeof Reflect.get(n,"postMessage")=="function",T=n=>{let e=Reflect.get(window,"webkit");if(typeof e=="object"&&e!==null){let s=Reflect.get(e,"messageHandlers");if(typeof s=="object"&&s!==null){let r=Reflect.get(s,n);if(S(r))return r}}let t=Reflect.get(window,n);return S(t)?t:null},X=(n,e={})=>{let{pollIntervalMs:t=50,timeoutMs:s=1500}=e;return new Promise(r=>{let i=Date.now(),u=()=>{let c=T(n);if(c){r(c);return}if(Date.now()-i>=s){r(null);return}setTimeout(u,t);};u();})};export{o as a,R as b,A as c,I as d,v as e,O as f,L as g,H as h,b as i,P as j,U as k,k as l,y as m,F as n,h as o,C as p,D as q,V as r,B as s,d as t,m as u,Q as v,T as w,X as x};
@@ -1,23 +0,0 @@
1
- interface Credentials {
2
- uid: string;
3
- token: string;
4
- }
5
- interface UserInfo {
6
- userId: string | number;
7
- username?: string;
8
- nickname?: string;
9
- avatar?: string | null;
10
- phone?: string | null;
11
- email?: string;
12
- [key: string]: unknown;
13
- }
14
- type AppEnvironmentType = "native_app" | "iframe" | "web";
15
- interface AppEnvironment {
16
- type: AppEnvironmentType;
17
- platform?: "iOS" | "Android";
18
- appVersion?: string;
19
- buildNumber?: string;
20
- meetsMinVersion: boolean;
21
- }
22
-
23
- export type { AppEnvironment as A, Credentials as C, UserInfo as U };