@idolchat/miniapp-sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ "use strict";(()=>{var Tt=Object.defineProperty;var At=(e,t,n)=>t in e?Tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var M=(e,t,n)=>At(e,typeof t!="symbol"?t+"":t,n);var re=["app.init","app.ready","app.setLoadingProgress","app.close","ui.showToast","ui.showAlert","ui.showConfirm","ui.showPopup","ui.setBackButtonVisible","ui.setHeaderColor","ui.setBackgroundColor","ui.setOrientation","ui.getTheme","haptic.impact","haptic.notification","haptic.selection","storage.get","storage.getMany","storage.set","storage.remove","storage.keys","storage.clear","link.open","clipboard.writeText","clipboard.readText","share.system","share.toChat","share.toPost","share.toStory","analytics.track","device.getInfo","permissions.query","permissions.request","qr.scan","location.get","media.saveImage","auth.getLaunchToken","auth.requestProfile","payment.open","notifications.requestPermission","notifications.getPermission","ads.loadRewarded","ads.showRewarded","ads.loadInterstitial","ads.showInterstitial","ads.showBanner","ads.hideBanner"],oe=["lifecycle.pause","lifecycle.resume","lifecycle.closing","ui.backButtonPressed","ui.themeChanged","ui.viewportChanged","permissions.changed","ads.loaded","ads.failed","ads.shown","ads.closed","ads.rewarded"],St=["app.beforeClose","ads.beforeBreak"];function Ee(e){return e.startsWith("payment.")||e.startsWith("ads.")||e.startsWith("share.")||e==="ui.showAlert"||e==="ui.showConfirm"||e==="ui.showPopup"||e==="permissions.request"||z(e)!==void 0}var se=1024*1024,ie=128,L=/^[A-Za-z0-9_-]{1,64}$/,ae=500,be=/^[A-Za-z0-9_-]{1,64}$/,Re=new Set(["link.open","clipboard.writeText","clipboard.readText","share.system","share.toChat","share.toPost","share.toStory","permissions.request","qr.scan","media.saveImage","payment.open","notifications.requestPermission","ads.showRewarded"]),xe=["profile","camera","microphone","location","notifications","photos"],Et={"auth.requestProfile":"profile","qr.scan":"camera","location.get":"location","media.saveImage":"photos","notifications.requestPermission":"notifications"},bt=new Map(Object.entries(Et)),z=e=>bt.get(e);var en=1,tn=["METHOD_NOT_SUPPORTED","INVALID_PARAMS","TIMEOUT","QUOTA_EXCEEDED","PERMISSION_DENIED","CANCELLED","INTERNAL_ERROR"],p=class extends Error{constructor(n,o){super(o);M(this,"code");this.name="MiniAppError",this.code=n}toWire(){return{code:this.code,message:this.message}}},w=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),A=e=>typeof e=="string"?e:void 0;function Ce(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}return w(t)&&t.v===1?t:null}function Ne(e){let t=Ce(e);if(!t)return null;let n=A(t.id),o=A(t.name);switch(t.type){case"result":return n===void 0?null:t.ok===!0?{v:1,type:"result",id:n,ok:!0,data:t.data}:t.ok!==!1||!w(t.error)?null:{v:1,type:"result",id:n,ok:!1,error:Rt(t.error)};case"event":return o===void 0?null:{v:1,type:"event",name:o,data:t.data};case"request":return n===void 0||o===void 0?null:{v:1,type:"request",id:n,name:o,data:t.data,timeoutMs:typeof t.timeoutMs=="number"?t.timeoutMs:3e3};default:return null}}function Rt(e){return{code:A(e.code)??"INTERNAL_ERROR",message:A(e.message)??""}}function nn(e){let t=Ce(e);return!t||typeof t.id!="string"||typeof t.method!="string"?null:{v:1,id:t.id,method:t.method,params:t.params,gesture:t.gesture===!0}}function le(e){return!w(e)||typeof e.id!="string"?null:{id:e.id,displayName:A(e.displayName),avatarUrl:A(e.avatarUrl),locale:A(e.locale)}}function _e(e){if(!w(e))throw new p("INTERNAL_ERROR","app.init returned no result");return{protocol:typeof e.protocol=="number"?e.protocol:1,methods:Array.isArray(e.methods)?e.methods.filter(t=>typeof t=="string"):[],limits:w(e.limits)?e.limits:{},user:le(e.user),startParam:A(e.startParam)??null,launchToken:A(e.launchToken)??null}}var Ie=1e4,F=1e4,D=class{constructor(t,n={}){M(this,"transport");M(this,"timeoutMs");M(this,"now");M(this,"pending",new Map);M(this,"events",new Map);M(this,"requests",new Map);M(this,"seq",0);M(this,"lastGestureAt",Number.NEGATIVE_INFINITY);M(this,"initPromise");M(this,"methods");this.transport=t,this.timeoutMs=n.timeoutMs??Ie,this.now=n.now??Date.now;let o=()=>{this.lastGestureAt=this.now()};n.gestureTarget?.addEventListener("pointerdown",o,{capture:!0}),n.gestureTarget?.addEventListener("keydown",o,{capture:!0}),t.listen(s=>this.receive(s))}init(){return this.initPromise??(this.initPromise=this.send("app.init",{protocol:1},{}).then(t=>{let n=_e(t);return this.methods=new Set(n.methods),n},t=>{throw this.initPromise=void 0,t})),this.initPromise}supports(t){return this.methods?.has(t)??!1}async call(t,n,o={}){let a=await this.init();if(t!=="app.init"){if(!this.supports(t))throw new p("METHOD_NOT_SUPPORTED",`host does not support ${t}`);a=await this.send(t,n,o)}return a}on(t,n){let o=a=>n(a),s=this.events.get(t);return s||this.events.set(t,s=new Set),s.add(o),()=>s.delete(o)}onRequest(t,n){return this.requests.set(t,n),()=>{this.requests.get(t)===n&&this.requests.delete(t)}}nextId(){return`c_${++this.seq}`}hasGesture(){return this.now()-this.lastGestureAt<=F}post(t,n,o){let s={v:1,id:o,method:t,gesture:this.hasGesture()};n!==void 0&&(s.params=n),this.transport.send(s)}send(t,n,o){let s=this.nextId(),a=o.timeoutMs??(Ee(t)?0:this.timeoutMs);return new Promise((c,f)=>{let g=a>0?setTimeout(()=>{this.pending.delete(s),f(new p("TIMEOUT",`${t} timed out after ${a} ms`))},a):void 0;this.pending.set(s,{resolve:c,reject:f,timer:g});try{this.post(t,n,s)}catch(m){clearTimeout(g),this.pending.delete(s),f(new p("INTERNAL_ERROR",`transport failed: ${String(m)}`))}})}receive(t){let n=Ne(t);if(n)if(n.type==="result"){let o=this.pending.get(n.id);if(!o)return;this.pending.delete(n.id),clearTimeout(o.timer),n.ok?o.resolve(n.data):o.reject(new p(n.error.code,n.error.message))}else if(n.type==="event")for(let o of this.events.get(n.name)??[])try{o(n.data)}catch(s){setTimeout(()=>{throw s})}else this.answer(n)}async answer(t){let n=this.requests.get(t.name),o;if(!n)o={id:t.id,ok:!1,error:{code:"METHOD_NOT_SUPPORTED",message:t.name}};else try{o={id:t.id,ok:!0,data:await n(t.data)}}catch(s){let a=s instanceof p?s:new p("INTERNAL_ERROR",String(s));o={id:t.id,ok:!1,error:a.toWire()}}this.post("_reply",o,this.nextId())}};function Oe(e){return{init:()=>e.init(),ready:()=>e.call("app.ready"),setLoadingProgress:t=>e.call("app.setLoadingProgress",{progress:Math.max(0,Math.min(100,Math.round(t)))}),close:()=>e.call("app.close")}}function Ue(e){return{onPause:t=>e.on("lifecycle.pause",t),onResume:t=>e.on("lifecycle.resume",t),onClosing:t=>e.on("lifecycle.closing",t),onBeforeClose:t=>e.onRequest("app.beforeClose",t)}}function Le(e){return{getInfo:()=>e.call("device.getInfo")}}function De(e){return{query:t=>e.call("permissions.query",{name:t}),request:t=>e.call("permissions.request",{name:t}),onChanged:t=>e.on("permissions.changed",t)}}function Be(e){return{scan:()=>e.call("qr.scan")}}function qe(e){return{get:()=>e.call("location.get")}}function $e(e){return{saveImage:t=>e.call("media.saveImage",{dataUrl:t})}}var x={maxBytes:2097152,maxSide:2048,types:["image/png","image/jpeg","image/webp"]},xt=/^data:([^;,]+);base64,/,Ct=/^[A-Za-z0-9+/]*={0,2}$/,Nt=Math.ceil(x.maxBytes/3)*4;function B(e){if(typeof e!="string")return{ok:!1,reason:"image must be a data: URL string"};let t=xt.exec(e.slice(0,40));if(!t)return{ok:!1,reason:"image must be a base64 data: URL"};let n=x.types.find(a=>a===t[1]);if(!n)return{ok:!1,reason:`image type must be ${x.types.join(", ")}`};let o=e.slice(t[0].length);if(o.length>Nt)return{ok:!1,reason:`image is over ${x.maxBytes} bytes`};if(o.length===0||o.length%4!==0||!Ct.test(o))return{ok:!1,reason:"image is not valid base64"};let s=o.length/4*3-(o.endsWith("==")?2:o.endsWith("=")?1:0);return s>x.maxBytes?{ok:!1,reason:`image is over ${x.maxBytes} bytes`}:{ok:!0,type:n,bytes:s}}function d(e){throw new p("INVALID_PARAMS",e)}function P(e,t){let n=e[t];return typeof n=="string"?n:d(`${t} must be a string`)}var S=(e,t)=>e[t]===void 0?void 0:P(e,t),ue=e=>typeof e=="string"&&e.trim()!=="";function ce(e,t){let n=t?P(e,"text"):S(e,"text");n!==void 0&&!ue(n)&&d("text must not be empty")}function q(e,t,n){let o=e[t];return n.find(s=>s===o)??d(`${t} must be one of ${n.join(", ")}`)}function pe(e){let t=e.color;return typeof t=="string"&&/^#[0-9a-f]{6}$/i.test(t)?t:d("color must be #rrggbb")}function We(e){let t=e.progress;return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.min(100,t)):d("progress must be a number from 0 to 100")}function de(e,t="url"){let n=e[t];if(typeof n=="string")try{let o=new URL(n);if(o.protocol==="https:"||o.protocol==="http:")return o.href}catch{}return d(`${t} must be an http(s) URL`)}function He(e){let t=e.startParam;if(t!==void 0)return typeof t=="string"&&L.test(t)?t:d("startParam must be 1-64 chars of [A-Za-z0-9_-]")}function Ve(e){let t=S(e,"text");if(t===void 0){e.image===void 0&&d("a story needs an image or text");return}let n=t.trim().length;(n<1||n>ae)&&d(`text must be 1-${ae} chars`)}var Ge=e=>q(e,"name",xe);function je(e){let t=e.buttons;return(!Array.isArray(t)||t.length===0||t.length>3)&&d("buttons must hold 1-3 buttons"),t.map(n=>{let o=w(n)?n:{},s=o.type==="cancel"||o.type==="destructive"?o.type:"default";return{id:P(o,"id"),text:P(o,"text"),type:s}})}function Ke(e){let t=P(e,"name");t.length===0&&d("name must not be empty");let n=e.props??{};if(!w(n)||Array.isArray(n))return d("props must be an object");for(let[o,s]of Object.entries(n))typeof s!="string"&&typeof s!="boolean"&&!(typeof s=="number"&&Number.isFinite(s))&&d(`props.${o} must be a string, number or boolean`);return{name:t,props:n}}function ze(e){return{open:t=>e.call("link.open",{url:t})}}function Fe(e){return{writeText:t=>e.call("clipboard.writeText",{text:t}),readText:async()=>(await e.call("clipboard.readText")).text}}function X(e,t,n,o){if(o&&(n.text!==void 0||o==="required")&&!ue(n.text))return Promise.reject(new p("INVALID_PARAMS","text must not be empty"));if(n.image!==void 0){let s=B(n.image);if(!s.ok)return Promise.reject(new p("INVALID_PARAMS",s.reason))}return e.call(t,n)}function Xe(e){return{system:t=>X(e,"share.system",t),toChat:t=>X(e,"share.toChat",t,"required"),toPost:t=>X(e,"share.toPost",t,"nonBlank"),toStory:t=>X(e,"share.toStory",t,"nonBlank")}}function Ye(e){return{track:(t,n)=>e.call("analytics.track",{name:t,props:n})}}var _t=e=>e&&(e.displayName??e.avatarUrl??e.locale)!==void 0?e:null;function Qe(e){let t,n=async()=>{let o=await e.init();if(!e.supports("auth.requestProfile"))return{user:_t(o.user)};let s=await e.call("auth.requestProfile");return{user:le(s?.user)}};return{getLaunchToken:async(o={})=>(await e.call("auth.getLaunchToken",o)).token,requestProfile:()=>t??(t=n().finally(()=>{t=void 0}))}}function Ze(e){return{open:t=>e.call("payment.open",t)}}function Je(e){return{requestPermission:()=>e.call("notifications.requestPermission"),getPermission:()=>e.call("notifications.getPermission")}}function et(e){return{loadRewarded:t=>e.call("ads.loadRewarded",{placement:t}),showRewarded:t=>e.call("ads.showRewarded",{placement:t}),loadInterstitial:t=>e.call("ads.loadInterstitial",{placement:t}),showInterstitial:t=>e.call("ads.showInterstitial",{placement:t}),showBanner:t=>e.call("ads.showBanner",t),hideBanner:()=>e.call("ads.hideBanner"),on:(t,n)=>e.on(t,n),onBeforeBreak:t=>e.onRequest("ads.beforeBreak",t)}}function tt(e){return{get:async t=>(await e.call("storage.get",{key:t})).value??null,getMany:async t=>(await e.call("storage.getMany",{keys:t})).values,set:(t,n)=>e.call("storage.set",{key:t,value:n}),remove:t=>e.call("storage.remove",{key:t}),keys:async()=>(await e.call("storage.keys")).keys,clear:()=>e.call("storage.clear")}}function nt(e){return{showToast:t=>e.call("ui.showToast",t),showAlert:t=>e.call("ui.showAlert",t),showConfirm:t=>e.call("ui.showConfirm",t),showPopup:t=>e.call("ui.showPopup",t),setBackButtonVisible:t=>e.call("ui.setBackButtonVisible",{visible:t}),setHeaderColor:t=>e.call("ui.setHeaderColor",{color:t}),setBackgroundColor:t=>e.call("ui.setBackgroundColor",{color:t}),setOrientation:t=>e.call("ui.setOrientation",{orientation:t}),getTheme:()=>e.call("ui.getTheme"),onBackButtonPressed:t=>e.on("ui.backButtonPressed",t),onThemeChanged:t=>e.on("ui.themeChanged",t),onViewportChanged:t=>e.on("ui.viewportChanged",t)}}function rt(e){return{impact:(t="medium")=>e.call("haptic.impact",{style:t}),notification:t=>e.call("haptic.notification",{type:t}),selection:()=>e.call("haptic.selection")}}var ot="0.1.0";function me(e,t){let n=new D(e,t);return{version:ot,transport:e.name,supports:o=>n.supports(o),call:(o,s,a)=>n.call(o,s,a),on:(o,s)=>n.on(o,s),app:Oe(n),lifecycle:Ue(n),ui:nt(n),haptic:rt(n),storage:tt(n),link:ze(n),clipboard:Fe(n),share:Xe(n),analytics:Ye(n),device:Le(n),permissions:De(n),qr:Be(n),location:qe(n),media:$e(n),auth:Qe(n),payment:Ze(n),notifications:Je(n),ads:et(n)}}var fe=new Set;function Y(e,t){return e.__idcMiniApp??(e.__idcMiniApp={_dispatch(n){for(let o of fe)o(n)}}),fe.add(t),()=>fe.delete(t)}var st=e=>typeof e.MiniAppAndroid?.call=="function";function it(e){return{name:"android",send:t=>e.MiniAppAndroid?.call(JSON.stringify(t)),listen:t=>Y(e,t)}}var at=e=>typeof e.webkit?.messageHandlers?.miniapp?.postMessage=="function";function lt(e){return{name:"ios",send:t=>e.webkit?.messageHandlers?.miniapp?.postMessage(JSON.stringify(t)),listen:t=>Y(e,t)}}var T=(e,t)=>e>>>t|e<<32-t,ut=e=>(e-Math.floor(e))*4294967296>>>0,$=[];for(let e=2;$.length<64;e++)$.every(t=>e%t!==0)&&$.push(e);var It=Uint32Array.from($,e=>ut(Math.cbrt(e))),Ot=Uint32Array.from($.slice(0,8),e=>ut(Math.sqrt(e)));function ct(e){let t=e.length+72&-64,n=new Uint8Array(t);n.set(e),n[e.length]=128;let o=new DataView(n.buffer);o.setUint32(t-8,Math.floor(e.length/2**29)),o.setUint32(t-4,e.length*8>>>0);let s=Uint32Array.from(Ot),a=new Uint32Array(64),c=new Uint32Array(8);for(let m=0;m<t;m+=64){for(let u=0;u<16;u++)a[u]=o.getUint32(m+u*4);for(let u=16;u<64;u++){let y=a[u-15],k=a[u-2];a[u]=a[u-16]+(T(y,7)^T(y,18)^y>>>3)+a[u-7]+(T(k,17)^T(k,19)^k>>>10)}c.set(s);for(let u=0;u<64;u++){let[y,k,C,J,v,N,_,E]=Array.from(c),H=E+(T(v,6)^T(v,11)^T(v,25))+(v&N^~v&_)+It[u]+a[u],V=(T(y,2)^T(y,13)^T(y,22))+(y&k^y&C^k&C);c.set([H+V,y,k,C,J+H,v,N,_])}for(let u=0;u<8;u++)s[u]=s[u]+c[u]}let f=new Uint8Array(32),g=new DataView(f.buffer);for(let m=0;m<8;m++)g.setUint32(m*4,s[m]);return f}var b="idcMiniApp:",W=new TextEncoder,Ut=["pointerup","touchend","keydown","click"],Lt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGN46uELAAOQAXsmNkYKAAAAAElFTkSuQmCC",pt={id:"mockUserId_00000000000",displayName:"Mock User",avatarUrl:Lt,locale:"en"},he=/^[A-Za-z0-9_-]{1,32}$/;function Dt(e){if(e===void 0)return pt;let t=ct(W.encode(e)),n=btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").slice(0,22);return{...pt,id:n,displayName:`Mock User ${e}`}}var dt=3e3;function Q(e){if(He(e),e.url!==void 0&&de(e),e.image!==void 0){let t=B(e.image);t.ok||d(t.reason)}}function Bt(){let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)},key:t=>[...e.keys()][t]??null,get length(){return e.size}}}function Z(e){let t=e.key;return(typeof t!="string"||t.length===0||t.length>ie)&&d(`key must be a 1-${ie} char string`),t}var ge=e=>{let t=S(e,"title"),n=P(e,"message");return t===void 0?n:`${t}
2
+
3
+ ${n}`};function mt(e,t){if(t===null)return null;let n=t.trim().toLowerCase();return e.find((s,a)=>String(a+1)===n||s.id.toLowerCase()===n||s.text.toLowerCase()===n)?.id??null}function ye(e={}){let t=e.storage??Bt(),n=e.limitBytes??se,o=e.now??Date.now,s=e.dialogs,a=e.userName!==void 0&&he.test(e.userName)?e.userName:void 0,c=e.user===void 0?Dt(a):e.user,f=async()=>{let r=e.user===void 0?await e.avatar?.catch(()=>null):null;return c&&r?{...c,avatarUrl:r}:c},g=e.notifications??"prompt",m=r=>{g=r,e.onNotificationsConsent?.(r,a)};m(g);let u=c===null?"denied":e.profile??"prompt",y="",k=e.colorScheme??"light",C=!1,J=0,v=new Map,N=null,_={},E=null,H=Promise.all([Promise.resolve(e.scopes).then(r=>{N=r?new Set(r):null},()=>{}),Promise.resolve(e.permissionReasons).then(r=>{_=r??{}},()=>{}),Promise.resolve(e.launchTokens).then(r=>{E=c?r??null:null},()=>{})]),V=(r,i)=>_[i]?`${r}
4
+
5
+ ${_[i]}`:r,U=r=>N===null||N.has(r),Pe=Number.NEGATIVE_INFINITY,ee=new Set,G=r=>setTimeout(()=>ee.forEach(i=>i(r)),0),I=(r,i)=>G({v:1,type:"event",name:r,data:i}),te=()=>{let r=[];for(let i=0;i<t.length;i++){let l=t.key(i);l?.startsWith(b)&&r.push(l.slice(b.length))}return r},ht=r=>te().filter(i=>i!==r).reduce((i,l)=>i+W.encode(l).length+W.encode(t.getItem(b+l)??"").length,0),ke=()=>{if(g!=="prompt")return g;let r=s?s.confirm(V("Allow this app to send you notifications?","notifications")):!0;return m(r?"granted":"denied"),I("permissions.changed",{name:"notifications",state:g}),g},ve=()=>(u!=="prompt"||(u=(s?s.confirm(V("Allow this app to see your name and avatar?","profile")):!0)?"granted":"denied",I("permissions.changed",{name:"profile",state:u})),u),Te=(r,i)=>{let l=Ge(r);return U(l)?l==="notifications"?{state:i?ke():g}:l==="profile"?{state:i?ve():u}:{state:"unavailable"}:{state:"unavailable"}},ne={"app.ready":()=>null,"app.setLoadingProgress":r=>(We(r),null),"app.close":()=>null,"ui.showToast":r=>(P(r,"message"),null),"ui.showAlert":r=>{let i=ge(r);return s?.alert(i),null},"ui.showConfirm":r=>{let i=ge(r);return{confirmed:s?s.confirm(i):!0}},"ui.showPopup":r=>{let i=ge(r),l=je(r);if(!s)return{buttonId:l[0]?.id??null};let h=l.map((K,vt)=>`${vt+1}. ${K.text}`).join(`
6
+ `),O=`
7
+
8
+ Pick 1-${l.length}, or Cancel to dismiss.`,j=K=>mt(l,K)===null&&!!K?.trim(),R=s.prompt(`${i}
9
+
10
+ ${h}`,"1");return j(R)&&(R=s.prompt(`${i}
11
+
12
+ ${h}${O}`,"1")),j(R)&&console.warn(`[miniapp-sdk] ui.showPopup: "${R}" matches no button, treated as dismissed`),{buttonId:mt(l,R)}},"ui.setBackButtonVisible":r=>(typeof r.visible!="boolean"&&d("visible must be a boolean"),C=r.visible,null),"ui.setHeaderColor":r=>(pe(r),null),"ui.setBackgroundColor":r=>(pe(r),null),"ui.setOrientation":r=>(q(r,"orientation",["portrait","landscape","auto"]),null),"ui.getTheme":()=>({colorScheme:k}),"haptic.impact":r=>(q(r,"style",["light","medium","heavy"]),null),"haptic.notification":r=>(q(r,"type",["success","warning","error"]),null),"haptic.selection":()=>null,"storage.get":r=>({value:t.getItem(b+Z(r))}),"storage.getMany":r=>{Array.isArray(r.keys)||d("keys must be an array");let i={};for(let l of r.keys)i[Z({key:l})]=t.getItem(b+String(l));return{values:i}},"storage.set":r=>{let i=Z(r),l=P(r,"value");if(ht(i)+W.encode(i).length+W.encode(l).length>n)throw new p("QUOTA_EXCEEDED",`storage is limited to ${n} bytes`);return t.setItem(b+i,l),null},"storage.remove":r=>(t.removeItem(b+Z(r)),null),"storage.keys":()=>({keys:te()}),"storage.clear":()=>(te().forEach(r=>t.removeItem(b+r)),null),"link.open":r=>{let i=de(r);return s?.open(i,"_blank","noopener,noreferrer"),null},"clipboard.writeText":r=>(y=P(r,"text"),null),"clipboard.readText":()=>({text:y}),"share.toChat":r=>(ce(r,!0),Q(r),e.onShare?.("share.toChat",r),{shared:!0}),"share.toPost":r=>{ce(r,!1);let i=S(r,"text");return Q(r),s&&!s.confirm(`Share to your IdolChat feed?
13
+
14
+ ${i??""}`)?{shared:!1}:(e.onShare?.("share.toPost",r),{shared:!0})},"share.toStory":r=>{let i=S(r,"text");return Ve(r),Q(r),s&&!s.confirm(`Share to your IdolChat story?
15
+
16
+ ${i??""}`)?{shared:!1}:(e.onShare?.("share.toStory",r),{shared:!0})},"share.system":r=>(S(r,"text"),S(r,"title"),Q(r),e.onShare?.("share.system",r),null),"analytics.track":r=>(Ke(r),null),"payment.open":r=>{let i=P(r,"invoiceId");return/^inv_[A-Za-z0-9_-]{22}$/.test(i)||d("invoiceId is not an invoice id"),s&&!s.confirm(`Pay invoice ${i}? (mock: no stars move)`)?{status:"cancelled"}:{status:e.payment??"paid"}},"device.getInfo":()=>({platform:"web",hostVersion:"mock",safeArea:{top:0,bottom:0,left:0,right:0}}),"permissions.query":r=>Te(r,!1),"permissions.request":r=>Te(r,!0),"notifications.requestPermission":()=>({state:ke()}),"notifications.getPermission":()=>({state:U("notifications")?g:"unavailable"}),"auth.requestProfile":async()=>({user:ve()==="granted"?await f():null})},Ae=()=>U("profile")&&u==="granted",Se=async r=>{let i=S(r,"nonce");if(i!==void 0&&!be.test(i)&&d("nonce must be 1-64 chars of [A-Za-z0-9_-]"),!E)throw new p("METHOD_NOT_SUPPORTED","no launch tokens here");try{return{token:await E({...i===void 0?{}:{nonce:i},profile:Ae(),...a===void 0||e.user!==void 0?{}:{user:a}})}}catch(l){throw new p("INTERNAL_ERROR",`launch token: ${String(l)}`)}};ne["app.init"]=async()=>({protocol:1,methods:[...Object.keys(ne),...E?["auth.getLaunchToken"]:[]].filter(r=>{let i=z(r);return i===void 0||U(i)}),limits:{storageBytes:n},user:c&&(Ae()?await f():{id:c.id}),startParam:e.startParam??null,launchToken:E?(await Se({}).catch(()=>null))?.token??null:null});let yt=new Set(re),Mt=r=>{if(r.method==="_reply"){let h=w(r.params)?r.params.id:void 0;typeof h=="string"&&v.get(h)?.();return}let i=h=>{let O=h instanceof p?h:new p("INTERNAL_ERROR",String(h));G({v:1,type:"result",id:r.id,ok:!1,error:O.toWire()})},l=o()-Pe<=F;H.then(()=>wt(r,l,i))},wt=(r,i,l)=>{try{let h=z(r.method);if(h!==void 0&&!U(h))throw new p("PERMISSION_DENIED",`no ${h} scope`);let O=r.method==="auth.getLaunchToken"&&E?Se:ne[r.method];if(O===void 0)throw new p("METHOD_NOT_SUPPORTED",yt.has(r.method)?`${r.method} can only be tested inside IdolChat`:`unknown method ${r.method}`);if(Re.has(r.method)&&!i)throw new p("PERMISSION_DENIED","gesture required");let j=O(w(r.params)?r.params:{});Promise.resolve(j).then(R=>G({v:1,type:"result",id:r.id,ok:!0,data:R}),l)}catch(h){l(h)}},Pt=r=>{r.isTrusted&&(Pe=o())};for(let r of Ut)e.doc?.addEventListener(r,Pt,{capture:!0});e.doc?.addEventListener("visibilitychange",()=>{let r=e.doc?.visibilityState==="hidden"?"lifecycle.pause":"lifecycle.resume";I(r,{reason:"background"})});let kt=new Set(oe);return{name:"mock",send:Mt,listen(r){return ee.add(r),()=>ee.delete(r)},controls:{emit(r,i){if(!kt.has(r))throw new TypeError(`${r} is not a host event`);if(w(i)&&r==="ui.themeChanged"&&(k=i.colorScheme==="dark"?"dark":"light"),w(i)&&r==="permissions.changed"){let l=i.state;(l==="prompt"||l==="granted"||l==="denied")&&(i.name==="notifications"&&m(l),i.name==="profile"&&c!==null&&(u=l))}I(r,i)},async close(){if(C)return I("ui.backButtonPressed",void 0),"backButtonPressed";let r=`mock_close_${++J}`;return await new Promise(i=>{let l=setTimeout(i,dt);v.set(r,()=>(clearTimeout(l),i())),G({v:1,type:"request",id:r,name:"app.beforeClose",timeoutMs:dt})}),v.delete(r),I("lifecycle.closing",void 0),"closing"}}}}var ft=e=>e.parent!==e;function gt(e){return{name:"postmessage",send:t=>e.parent.postMessage(t,"*"),listen(t){let n=o=>{o.source===e.parent&&t(o.data)};return e.addEventListener("message",n),()=>e.removeEventListener("message",n)}}}function Me(e){if(at(e))return lt(e);if(st(e))return it(e);if(ft(e))return gt(e);let t=qt(e),n=Kt(e),o=ye({storage:Yt(e),doc:e.document,dialogs:e,avatar:zt(e,t),scopes:t.then($t),permissionReasons:t.then(Wt),launchTokens:n.then(s=>s?.mint??null),onNotificationsConsent:(s,a)=>{n.then(c=>c?.consent(s,a))},...Ft(Xt(e))});return Object.defineProperty(e,"__idolchatMock",{value:o.controls,configurable:!0}),o}async function qt(e){try{let t=new URL("manifest.json",e.location.href),n=await e.fetch(t);if(!n.ok)return null;let o=await n.json();return we(o)?{url:t,body:o}:null}catch{return null}}function $t(e){if(e===null)return null;let t=e.body.scopes??[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Wt(e){let t=e?.body.permissionReasons;return we(t)?Object.fromEntries(Object.entries(t).filter(n=>typeof n[1]=="string")):{}}var Ht="/__idolchat/jwks.json",Vt="/__idolchat/launch-token",Gt="/__idolchat/consent",jt="x-idolchat-dev";async function Kt(e){try{let c=await e.fetch(new URL(Ht,e.location.href),{cache:"no-store"});if(!c.ok||c.headers.get(jt)!=="1")return null}catch{return null}let t=new URL(Vt,e.location.href),n=new URL(Gt,e.location.href),o=Promise.resolve();return{mint:async c=>{let f=await e.fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(c)}),g=await f.json(),m=we(g)?g.token:void 0;if(!f.ok||typeof m!="string")throw new Error(`dev server answered ${f.status}`);return m},consent:(c,f)=>o=o.then(()=>e.fetch(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(f===void 0?{state:c}:{state:c,user:f})})).then(()=>{},()=>{})}}async function zt(e,t){try{let n=await t,o=n?.body.icon;if(n===null||typeof o!="string")return null;let s=e.document.createElement("img");s.src=new URL(o,n.url).href,await s.decode();let a=Math.min(256,s.naturalWidth,s.naturalHeight);if(a===0)return null;let c=e.document.createElement("canvas");return c.width=c.height=a,c.getContext("2d")?.drawImage(s,0,0,a,a),c.toDataURL("image/png")}catch{return null}}var we=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ft(e){let t=new URLSearchParams(e),n={},o=t.get("startapp");o!==null&&(n.startParam=L.test(o)?o:null,n.startParam===null&&console.warn(`[miniapp-sdk] ?startapp=${o} ignored: a startParam is 1-64 chars of [A-Za-z0-9_-], so IdolChat would never send it`)),t.get("profile")==="0"&&(n.profile="denied"),t.get("theme")==="dark"&&(n.colorScheme="dark");let s=t.get("user");s!==null&&(he.test(s)?n.userName=s:console.warn(`[miniapp-sdk] ?user=${s} ignored: a test user name is 1-32 chars of [A-Za-z0-9_-]`));let a=t.get("notifications");return(a==="granted"||a==="denied"||a==="prompt")&&(n.notifications=a),n}function Xt(e){try{return e.location.search}catch{return""}}function Yt(e){try{return e.localStorage}catch{return}}var er=typeof window>"u"?void 0:window.MiniApp??(window.MiniApp=me(Me(window),{gestureTarget:window.document}));})();
@@ -0,0 +1,173 @@
1
+ import { type CallOptions, type CoreOptions } from "./core.js";
2
+ import type { Transport } from "./transport/types.js";
3
+ export declare const SDK_VERSION = "0.1.0";
4
+ export declare function createMiniApp(transport: Transport, opts?: CoreOptions): {
5
+ version: string;
6
+ transport: import("./index.js").TransportName;
7
+ supports: (method: string) => boolean;
8
+ call: <T = unknown>(method: string, params?: unknown, o?: CallOptions) => Promise<T>;
9
+ on: (name: string, cb: (data: unknown) => void) => () => void;
10
+ app: {
11
+ init: () => Promise<import("./protocol.js").InitResult>;
12
+ ready: () => Promise<void>;
13
+ setLoadingProgress: (progress: number) => Promise<void>;
14
+ close: () => Promise<void>;
15
+ };
16
+ lifecycle: {
17
+ onPause: (cb: (data: {
18
+ reason?: string;
19
+ }) => void) => () => void;
20
+ onResume: (cb: (data: unknown) => void) => () => void;
21
+ onClosing: (cb: (data: unknown) => void) => () => void;
22
+ onBeforeClose: (handler: () => unknown) => () => void;
23
+ };
24
+ ui: {
25
+ showToast: (p: {
26
+ message: string;
27
+ durationMs?: number;
28
+ }) => Promise<void>;
29
+ showAlert: (p: {
30
+ title?: string;
31
+ message: string;
32
+ }) => Promise<void>;
33
+ showConfirm: (p: {
34
+ title?: string;
35
+ message: string;
36
+ }) => Promise<{
37
+ confirmed: boolean;
38
+ }>;
39
+ showPopup: (p: {
40
+ title?: string;
41
+ message: string;
42
+ buttons: import("./modules/ui.js").PopupButton[];
43
+ }) => Promise<{
44
+ buttonId: string | null;
45
+ }>;
46
+ setBackButtonVisible: (visible: boolean) => Promise<void>;
47
+ setHeaderColor: (color: string) => Promise<void>;
48
+ setBackgroundColor: (color: string) => Promise<void>;
49
+ setOrientation: (orientation: "portrait" | "landscape" | "auto") => Promise<void>;
50
+ getTheme: () => Promise<{
51
+ colorScheme: "light" | "dark";
52
+ }>;
53
+ onBackButtonPressed: (cb: () => void) => () => void;
54
+ onThemeChanged: (cb: (data: {
55
+ colorScheme: "light" | "dark";
56
+ }) => void) => () => void;
57
+ onViewportChanged: (cb: (data: {
58
+ width: number;
59
+ height: number;
60
+ }) => void) => () => void;
61
+ };
62
+ haptic: {
63
+ impact: (style?: "light" | "medium" | "heavy") => Promise<void>;
64
+ notification: (type: "success" | "warning" | "error") => Promise<void>;
65
+ selection: () => Promise<void>;
66
+ };
67
+ storage: {
68
+ get: (key: string) => Promise<string | null>;
69
+ getMany: (keys: string[]) => Promise<Record<string, string | null>>;
70
+ set: (key: string, value: string) => Promise<void>;
71
+ remove: (key: string) => Promise<void>;
72
+ keys: () => Promise<string[]>;
73
+ clear: () => Promise<void>;
74
+ };
75
+ link: {
76
+ open: (url: string) => Promise<void>;
77
+ };
78
+ clipboard: {
79
+ writeText: (text: string) => Promise<void>;
80
+ readText: () => Promise<string>;
81
+ };
82
+ share: {
83
+ system: (p: import("./index.js").ShareParams & {
84
+ title?: string;
85
+ }) => Promise<void>;
86
+ toChat: (p: import("./index.js").ShareParams & {
87
+ text: string;
88
+ }) => Promise<{
89
+ shared: boolean;
90
+ }>;
91
+ toPost: (p: import("./index.js").ShareComposerParams) => Promise<{
92
+ shared: boolean;
93
+ }>;
94
+ toStory: (p: import("./index.js").ShareComposerParams) => Promise<{
95
+ shared: boolean;
96
+ }>;
97
+ };
98
+ analytics: {
99
+ track: (name: string, props?: Record<string, string | number | boolean>) => Promise<void>;
100
+ };
101
+ device: {
102
+ getInfo: () => Promise<{
103
+ platform: string;
104
+ hostVersion: string;
105
+ } & Record<string, unknown>>;
106
+ };
107
+ permissions: {
108
+ query: (name: import("./index.js").PermissionName) => Promise<{
109
+ state: import("./index.js").PermissionState;
110
+ }>;
111
+ request: (name: import("./index.js").PermissionName) => Promise<{
112
+ state: import("./index.js").PermissionState;
113
+ }>;
114
+ onChanged: (cb: (data: {
115
+ name: import("./index.js").PermissionName;
116
+ state: import("./index.js").PermissionState;
117
+ }) => void) => () => void;
118
+ };
119
+ qr: {
120
+ scan: () => Promise<{
121
+ text: string | null;
122
+ }>;
123
+ };
124
+ location: {
125
+ get: () => Promise<{
126
+ latitude: number;
127
+ longitude: number;
128
+ accuracy: number;
129
+ }>;
130
+ };
131
+ media: {
132
+ saveImage: (dataUrl: string) => Promise<void>;
133
+ };
134
+ auth: {
135
+ getLaunchToken: (p?: {
136
+ nonce?: string;
137
+ }) => Promise<string>;
138
+ requestProfile: () => Promise<{
139
+ user: import("./protocol.js").MiniAppUser | null;
140
+ }>;
141
+ };
142
+ payment: {
143
+ open: (p: {
144
+ invoiceId: string;
145
+ }) => Promise<{
146
+ status: "paid" | "cancelled" | "failed" | "processing";
147
+ }>;
148
+ };
149
+ notifications: {
150
+ requestPermission: () => Promise<{
151
+ state: "granted" | "denied";
152
+ }>;
153
+ getPermission: () => Promise<{
154
+ state: import("./index.js").PermissionState;
155
+ }>;
156
+ };
157
+ ads: {
158
+ loadRewarded: (placement: string) => Promise<void>;
159
+ showRewarded: (placement: string) => Promise<{
160
+ rewarded: boolean;
161
+ }>;
162
+ loadInterstitial: (placement: string) => Promise<void>;
163
+ showInterstitial: (placement: string) => Promise<void>;
164
+ showBanner: (p: {
165
+ placement: string;
166
+ position?: "top" | "bottom";
167
+ }) => Promise<void>;
168
+ hideBanner: () => Promise<void>;
169
+ on: (name: import("./modules/platform.js").AdEventName, cb: (data: unknown) => void) => () => void;
170
+ onBeforeBreak: (handler: () => unknown) => () => void;
171
+ };
172
+ };
173
+ export type MiniApp = ReturnType<typeof createMiniApp>;
@@ -0,0 +1,46 @@
1
+ import { type InitResult } from "./protocol.js";
2
+ import type { Transport } from "./transport/types.js";
3
+ export declare const DEFAULT_TIMEOUT_MS = 10000;
4
+ export declare const GESTURE_WINDOW_MS = 10000;
5
+ export interface CoreOptions {
6
+ timeoutMs?: number;
7
+ /** Where to watch for user gestures (normally `document`). */
8
+ gestureTarget?: Pick<EventTarget, "addEventListener"> | undefined;
9
+ now?: () => number;
10
+ }
11
+ export interface CallOptions {
12
+ /** Overrides the default; `0` disables the timeout. */
13
+ timeoutMs?: number;
14
+ }
15
+ type RequestHandler = (data: unknown) => unknown;
16
+ /** The app side of the protocol: correlates calls to results, fans out events, answers host requests. */
17
+ export declare class MiniAppCore {
18
+ readonly transport: Transport;
19
+ private readonly timeoutMs;
20
+ private readonly now;
21
+ private readonly pending;
22
+ private readonly events;
23
+ private readonly requests;
24
+ private seq;
25
+ private lastGestureAt;
26
+ private initPromise;
27
+ private methods;
28
+ constructor(transport: Transport, opts?: CoreOptions);
29
+ /** Negotiates once; every other call waits for it. */
30
+ init(): Promise<InitResult>;
31
+ /** False until `init()` has resolved, then whether the host lists the method. */
32
+ supports(method: string): boolean;
33
+ /** `T` is the result shape the protocol documents for `method`; the host is trusted to honour it. */
34
+ call<T = unknown>(method: string, params?: unknown, opts?: CallOptions): Promise<T>;
35
+ /** `T` is the event payload the protocol documents for `name`. */
36
+ on<T = unknown>(name: string, handler: (data: T) => void): () => void;
37
+ /** One handler per request name; the latest registration wins. */
38
+ onRequest(name: string, handler: RequestHandler): () => void;
39
+ private nextId;
40
+ private hasGesture;
41
+ private post;
42
+ private send;
43
+ private receive;
44
+ private answer;
45
+ }
46
+ export {};
@@ -0,0 +1,56 @@
1
+ import { type WireError } from "../protocol.js";
2
+ export { MiniAppError, type WireError } from "../protocol.js";
3
+ export { LAUNCH_NONCE_PATTERN, METHOD_SCOPES, START_PARAM_PATTERN, STORY_TEXT_MAX, scopeOf, type PermissionName, } from "../methods.js";
4
+ export { analyticsEvent, hexColor, oneOf, shareText, storyContent } from "../validate.js";
5
+ export { SHARE_IMAGE_LIMITS, checkShareImage, type ShareImageCheck, type ShareImageType, } from "../share-image.js";
6
+ export interface CallContext {
7
+ method: string;
8
+ /** The app's claim only; a host must not treat it as proof of a user gesture. */
9
+ gesture: boolean;
10
+ }
11
+ /** Return the result data, or throw a `MiniAppError` to answer `ok: false` with its code. */
12
+ export type HostHandler = (params: unknown, ctx: CallContext) => unknown;
13
+ export type HostDiagnostic = {
14
+ kind: "call";
15
+ method: string;
16
+ id: string;
17
+ gesture: boolean;
18
+ } | {
19
+ kind: "result";
20
+ method: string;
21
+ id: string;
22
+ ok: boolean;
23
+ error?: WireError;
24
+ } | {
25
+ kind: "rejected";
26
+ reason: "origin" | "source" | "malformed";
27
+ origin: string;
28
+ };
29
+ /** Structural subsets of `Window`, so tests and non-DOM callers can pass fakes. */
30
+ export interface AppWindow {
31
+ postMessage(message: unknown, targetOrigin: string): void;
32
+ }
33
+ export interface MessageSource {
34
+ addEventListener(type: "message", listener: (e: Event) => void): void;
35
+ removeEventListener(type: "message", listener: (e: Event) => void): void;
36
+ }
37
+ export interface PostMessageHostOptions {
38
+ iframe: {
39
+ readonly contentWindow: AppWindow | null;
40
+ };
41
+ /** Exact origin of the app document (`"null"` for an opaque sandbox, where `source` is the only guard). */
42
+ appOrigin: string;
43
+ handlers: Partial<Record<string, HostHandler>>;
44
+ onEvent?: (e: HostDiagnostic) => void;
45
+ /** The window that receives the iframe's messages; defaults to the global `window`. */
46
+ window?: MessageSource;
47
+ }
48
+ export interface PostMessageHost {
49
+ /** Sends a host → app event, e.g. `lifecycle.pause`. */
50
+ emit(name: string, data?: unknown): void;
51
+ /** Sends a host → app request and waits for the app's `_reply`; rejects with TIMEOUT. */
52
+ request(name: string, data?: unknown, timeoutMs?: number): Promise<unknown>;
53
+ dispose(): void;
54
+ }
55
+ /** Hosts an app running in an iframe on a web page (the console's /play simulator). */
56
+ export declare function createPostMessageHost(opts: PostMessageHostOptions): PostMessageHost;
@@ -0,0 +1,18 @@
1
+ import { type MiniApp } from "./client.js";
2
+ export { createMiniApp, SDK_VERSION, type MiniApp } from "./client.js";
3
+ export { MiniAppCore, DEFAULT_TIMEOUT_MS, GESTURE_WINDOW_MS, type CallOptions, type CoreOptions, } from "./core.js";
4
+ export { METHODS, EVENTS, REQUESTS, STORAGE_LIMIT_BYTES, START_PARAM_PATTERN, type MethodName, type EventName, type RequestName, } from "./methods.js";
5
+ export * from "./protocol.js";
6
+ export type { PermissionName, PermissionState } from "./modules/device.js";
7
+ export type { ShareComposerParams, ShareParams } from "./modules/links.js";
8
+ export { SHARE_IMAGE_LIMITS, checkShareImage, type ShareImageCheck, type ShareImageType, } from "./share-image.js";
9
+ export { detectTransport } from "./transport/detect.js";
10
+ export { createMockTransport, type MockOptions } from "./transport/mock.js";
11
+ export type { Transport, TransportName } from "./transport/types.js";
12
+ declare global {
13
+ interface Window {
14
+ MiniApp?: MiniApp;
15
+ }
16
+ }
17
+ /** The page-wide instance, also published as `window.MiniApp`; undefined outside a browser. */
18
+ export declare const miniApp: MiniApp | undefined;
@@ -0,0 +1,34 @@
1
+ /** The method catalog of protocol v1, kept in step with the protocol. */
2
+ export declare const METHODS: readonly ["app.init", "app.ready", "app.setLoadingProgress", "app.close", "ui.showToast", "ui.showAlert", "ui.showConfirm", "ui.showPopup", "ui.setBackButtonVisible", "ui.setHeaderColor", "ui.setBackgroundColor", "ui.setOrientation", "ui.getTheme", "haptic.impact", "haptic.notification", "haptic.selection", "storage.get", "storage.getMany", "storage.set", "storage.remove", "storage.keys", "storage.clear", "link.open", "clipboard.writeText", "clipboard.readText", "share.system", "share.toChat", "share.toPost", "share.toStory", "analytics.track", "device.getInfo", "permissions.query", "permissions.request", "qr.scan", "location.get", "media.saveImage", "auth.getLaunchToken", "auth.requestProfile", "payment.open", "notifications.requestPermission", "notifications.getPermission", "ads.loadRewarded", "ads.showRewarded", "ads.loadInterstitial", "ads.showInterstitial", "ads.showBanner", "ads.hideBanner"];
3
+ export type MethodName = (typeof METHODS)[number];
4
+ export declare const EVENTS: readonly ["lifecycle.pause", "lifecycle.resume", "lifecycle.closing", "ui.backButtonPressed", "ui.themeChanged", "ui.viewportChanged", "permissions.changed", "ads.loaded", "ads.failed", "ads.shown", "ads.closed", "ads.rewarded"];
5
+ export type EventName = (typeof EVENTS)[number];
6
+ export declare const REQUESTS: readonly ["app.beforeClose", "ads.beforeBreak"];
7
+ export type RequestName = (typeof REQUESTS)[number];
8
+ /** Calls that wait on the user (a sheet, an ad, a prompt) never time out. */
9
+ export declare function waitsOnUser(method: string): boolean;
10
+ export declare const STORAGE_LIMIT_BYTES: number;
11
+ export declare const STORAGE_KEY_MAX = 128;
12
+ /** `startParam` of a share link and of a server notification (protocol §7, §12). */
13
+ export declare const START_PARAM_PATTERN: RegExp;
14
+ /** `share.toStory`'s `text`, after trimming (protocol §7). */
15
+ export declare const STORY_TEXT_MAX = 500;
16
+ /** `auth.getLaunchToken`'s `nonce`, chosen by the app's own server (protocol §7). */
17
+ export declare const LAUNCH_NONCE_PATTERN: RegExp;
18
+ /** The 👆 calls: a host answers them `PERMISSION_DENIED` without a recent real tap (protocol §5). */
19
+ export declare const GESTURE_METHODS: ReadonlySet<string>;
20
+ /** The permission names of protocol §6. */
21
+ export declare const PERMISSION_NAMES: readonly ["profile", "camera", "microphone", "location", "notifications", "photos"];
22
+ export type PermissionName = (typeof PERMISSION_NAMES)[number];
23
+ /**
24
+ * The 🔒 calls and the scope each needs (protocol §6). Without it a host leaves the call out of
25
+ * `app.init`'s `methods` and answers it `PERMISSION_DENIED`; state reads answer `unavailable`.
26
+ */
27
+ export declare const METHOD_SCOPES: {
28
+ readonly "auth.requestProfile": "profile";
29
+ readonly "qr.scan": "camera";
30
+ readonly "location.get": "location";
31
+ readonly "media.saveImage": "photos";
32
+ readonly "notifications.requestPermission": "notifications";
33
+ };
34
+ export declare const scopeOf: (method: string) => PermissionName | undefined;
@@ -0,0 +1,18 @@
1
+ import type { MiniAppCore } from "../core.js";
2
+ import type { InitResult } from "../protocol.js";
3
+ export declare function appModule(core: MiniAppCore): {
4
+ init: () => Promise<InitResult>;
5
+ ready: () => Promise<void>;
6
+ /** 0–100. */
7
+ setLoadingProgress: (progress: number) => Promise<void>;
8
+ close: () => Promise<void>;
9
+ };
10
+ export declare function lifecycleModule(core: MiniAppCore): {
11
+ onPause: (cb: (data: {
12
+ reason?: string;
13
+ }) => void) => () => void;
14
+ onResume: (cb: (data: unknown) => void) => () => void;
15
+ onClosing: (cb: (data: unknown) => void) => () => void;
16
+ /** The host waits up to the request's timeout (3 s) for this to settle, e.g. to flush a save. */
17
+ onBeforeClose: (handler: () => unknown) => () => void;
18
+ };
@@ -0,0 +1,37 @@
1
+ import type { MiniAppCore } from "../core.js";
2
+ export type PermissionName = "profile" | "camera" | "microphone" | "location" | "notifications" | "photos";
3
+ export type PermissionState = "granted" | "denied" | "prompt" | "unavailable";
4
+ export declare function deviceModule(core: MiniAppCore): {
5
+ getInfo: () => Promise<{
6
+ platform: string;
7
+ hostVersion: string;
8
+ } & Record<string, unknown>>;
9
+ };
10
+ export declare function permissionsModule(core: MiniAppCore): {
11
+ query: (name: PermissionName) => Promise<{
12
+ state: PermissionState;
13
+ }>;
14
+ request: (name: PermissionName) => Promise<{
15
+ state: PermissionState;
16
+ }>;
17
+ onChanged: (cb: (data: {
18
+ name: PermissionName;
19
+ state: PermissionState;
20
+ }) => void) => () => void;
21
+ };
22
+ export declare function qrModule(core: MiniAppCore): {
23
+ scan: () => Promise<{
24
+ text: string | null;
25
+ }>;
26
+ };
27
+ export declare function locationModule(core: MiniAppCore): {
28
+ get: () => Promise<{
29
+ latitude: number;
30
+ longitude: number;
31
+ accuracy: number;
32
+ }>;
33
+ };
34
+ export declare function mediaModule(core: MiniAppCore): {
35
+ /** `dataUrl` must be a `data:image/...` URL. */
36
+ saveImage: (dataUrl: string) => Promise<void>;
37
+ };
@@ -0,0 +1,42 @@
1
+ import type { MiniAppCore } from "../core.js";
2
+ export declare function linkModule(core: MiniAppCore): {
3
+ open: (url: string) => Promise<void>;
4
+ };
5
+ export declare function clipboardModule(core: MiniAppCore): {
6
+ writeText: (text: string) => Promise<void>;
7
+ readText: () => Promise<string>;
8
+ };
9
+ /** The host attaches a link to the current app only (protocol §7, "Share links"). */
10
+ export interface ShareParams {
11
+ text?: string;
12
+ startParam?: string;
13
+ /** @deprecated An external http(s) link placed in the text; the app link is still attached. */
14
+ url?: string;
15
+ /** A base64 `data:` URL within `SHARE_IMAGE_LIMITS`, e.g. from `canvas.toDataURL()`. */
16
+ image?: string;
17
+ }
18
+ /** `share.toPost` / `share.toStory`: the user publishes from IdolChat's composer, or cancels. */
19
+ export type ShareComposerParams = Omit<ShareParams, "url">;
20
+ export declare function shareModule(core: MiniAppCore): {
21
+ /** The OS share sheet; resolves once it closes. */
22
+ system: (p: ShareParams & {
23
+ title?: string;
24
+ }) => Promise<void>;
25
+ /** The user picks chats; the message is sent as the user. */
26
+ toChat: (p: ShareParams & {
27
+ text: string;
28
+ }) => Promise<{
29
+ shared: boolean;
30
+ }>;
31
+ /** IdolChat's post composer, prefilled with the text, image and the app's card. */
32
+ toPost: (p: ShareComposerParams) => Promise<{
33
+ shared: boolean;
34
+ }>;
35
+ /** IdolChat's story composer; a story needs `image` or `text` (1–500 chars). */
36
+ toStory: (p: ShareComposerParams) => Promise<{
37
+ shared: boolean;
38
+ }>;
39
+ };
40
+ export declare function analyticsModule(core: MiniAppCore): {
41
+ track: (name: string, props?: Record<string, string | number | boolean>) => Promise<void>;
42
+ };
@@ -0,0 +1,52 @@
1
+ import type { MiniAppCore } from "../core.js";
2
+ import { type MiniAppUser } from "../protocol.js";
3
+ import type { PermissionState } from "./device.js";
4
+ export declare function authModule(core: MiniAppCore): {
5
+ /** A fresh EdDSA JWT for the app's server to verify (protocol §7); `nonce` is echoed. */
6
+ getLaunchToken: (p?: {
7
+ nonce?: string;
8
+ }) => Promise<string>;
9
+ /**
10
+ * The user's name and avatar, asking the first time (ADR-0030); `user` is null when refused.
11
+ * A host that does not list the method asked at open, so its `app.init` user is the answer.
12
+ * Concurrent calls share one request, as they share the host's one dialog.
13
+ */
14
+ requestProfile: () => Promise<{
15
+ user: MiniAppUser | null;
16
+ }>;
17
+ };
18
+ export declare function paymentModule(core: MiniAppCore): {
19
+ /** IdolChat's confirm dialog for your server's invoice; grant from the webhook, never this result. */
20
+ open: (p: {
21
+ invoiceId: string;
22
+ }) => Promise<{
23
+ status: "paid" | "cancelled" | "failed" | "processing";
24
+ }>;
25
+ };
26
+ export declare function notificationsModule(core: MiniAppCore): {
27
+ /** Prompts the user; the host records the answer so the app's server may notify this user. */
28
+ requestPermission: () => Promise<{
29
+ state: "granted" | "denied";
30
+ }>;
31
+ /** Never prompts. */
32
+ getPermission: () => Promise<{
33
+ state: PermissionState;
34
+ }>;
35
+ };
36
+ export type AdEventName = "ads.loaded" | "ads.failed" | "ads.shown" | "ads.closed" | "ads.rewarded";
37
+ export declare function adsModule(core: MiniAppCore): {
38
+ loadRewarded: (placement: string) => Promise<void>;
39
+ showRewarded: (placement: string) => Promise<{
40
+ rewarded: boolean;
41
+ }>;
42
+ loadInterstitial: (placement: string) => Promise<void>;
43
+ showInterstitial: (placement: string) => Promise<void>;
44
+ showBanner: (p: {
45
+ placement: string;
46
+ position?: "top" | "bottom";
47
+ }) => Promise<void>;
48
+ hideBanner: () => Promise<void>;
49
+ on: (name: AdEventName, cb: (data: unknown) => void) => () => void;
50
+ /** The host asks before an ad break; resolve once the app is paused. */
51
+ onBeforeBreak: (handler: () => unknown) => () => void;
52
+ };
@@ -0,0 +1,13 @@
1
+ import type { MiniAppCore } from "../core.js";
2
+ /**
3
+ * Per (app, user) key-value store on the host, 1 MiB in total. App saves must use it rather than
4
+ * localStorage: the same app runs on different origins (iOS local bundle vs online), see the protocol.
5
+ */
6
+ export declare function storageModule(core: MiniAppCore): {
7
+ get: (key: string) => Promise<string | null>;
8
+ getMany: (keys: string[]) => Promise<Record<string, string | null>>;
9
+ set: (key: string, value: string) => Promise<void>;
10
+ remove: (key: string) => Promise<void>;
11
+ keys: () => Promise<string[]>;
12
+ clear: () => Promise<void>;
13
+ };
@@ -0,0 +1,49 @@
1
+ import type { MiniAppCore } from "../core.js";
2
+ export interface PopupButton {
3
+ id: string;
4
+ text: string;
5
+ type?: "default" | "cancel" | "destructive";
6
+ }
7
+ export declare function uiModule(core: MiniAppCore): {
8
+ showToast: (p: {
9
+ message: string;
10
+ durationMs?: number;
11
+ }) => Promise<void>;
12
+ showAlert: (p: {
13
+ title?: string;
14
+ message: string;
15
+ }) => Promise<void>;
16
+ showConfirm: (p: {
17
+ title?: string;
18
+ message: string;
19
+ }) => Promise<{
20
+ confirmed: boolean;
21
+ }>;
22
+ showPopup: (p: {
23
+ title?: string;
24
+ message: string;
25
+ buttons: PopupButton[];
26
+ }) => Promise<{
27
+ buttonId: string | null;
28
+ }>;
29
+ setBackButtonVisible: (visible: boolean) => Promise<void>;
30
+ setHeaderColor: (color: string) => Promise<void>;
31
+ setBackgroundColor: (color: string) => Promise<void>;
32
+ setOrientation: (orientation: "portrait" | "landscape" | "auto") => Promise<void>;
33
+ getTheme: () => Promise<{
34
+ colorScheme: "light" | "dark";
35
+ }>;
36
+ onBackButtonPressed: (cb: () => void) => () => void;
37
+ onThemeChanged: (cb: (data: {
38
+ colorScheme: "light" | "dark";
39
+ }) => void) => () => void;
40
+ onViewportChanged: (cb: (data: {
41
+ width: number;
42
+ height: number;
43
+ }) => void) => () => void;
44
+ };
45
+ export declare function hapticModule(core: MiniAppCore): {
46
+ impact: (style?: "light" | "medium" | "heavy") => Promise<void>;
47
+ notification: (type: "success" | "warning" | "error") => Promise<void>;
48
+ selection: () => Promise<void>;
49
+ };