@napplet/conformance-cli 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js.map +1 -1
- package/dist/host-bundle.global.js +200 -199
- package/dist/ui/assets/{index-CXfC5ZeJ.js → index-O6oNQSqa.js} +210 -202
- package/dist/ui/index.html +1 -1
- package/package.json +5 -5
|
@@ -1,199 +1,13 @@
|
|
|
1
|
-
(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))t(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&t(o)}).observe(document,{childList:!0,subtree:!0});function r(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function t(s){if(s.ep)return;s.ep=!0;const i=r(s);fetch(s.href,i)}})();var Le=["shell","relay","identity","storage","inc","theme","keys","media","notify","config","resource","cvm","outbox","upload","intent","ble","webrtc","link","count","lists","serial","fs","common","dm","gamepad","llm"],u={id:"string"},Dt={"llm.select":{dir:"out",fields:{...u}},"llm.select.result":{dir:"in",fields:{...u}},"llm.describe":{dir:"out",fields:{...u,handle:"string"}},"llm.describe.result":{dir:"in",fields:{...u}},"llm.generate":{dir:"out",fields:{...u,request:"object"}},"llm.generate.result":{dir:"in",fields:{...u}},"llm.delta":{dir:"in",fields:{requestId:"string",sequence:"number",text:"string"}},"llm.cancel":{dir:"out",fields:{...u,requestId:"string"}},"llm.cancel.result":{dir:"in",fields:{...u}},"gamepad.subscribe":{dir:"out",forbiddenFields:["id"],forbiddenReason:"NAP-GAMEPAD fire-and-forget envelopes do not carry it"},"gamepad.unsubscribe":{dir:"out",forbiddenFields:["id"],forbiddenReason:"NAP-GAMEPAD fire-and-forget envelopes do not carry it"},"gamepad.state":{dir:"in",fields:{available:"boolean",focused:"boolean",pads:"array"}},"shell.ready":{dir:"out"},"shell.init":{dir:"in",fields:{capabilities:"object",services:"array"}},"relay.subscribe":{dir:"out",fields:{...u,subId:"string",filters:"array"}},"relay.close":{dir:"out",fields:{...u,subId:"string"}},"relay.publish":{dir:"out",fields:{...u,event:"object"}},"relay.publishEncrypted":{dir:"out",fields:{...u,event:"object",recipient:"string"}},"relay.query":{dir:"out",fields:{...u,filters:"array"}},"relay.event":{dir:"in"},"relay.eose":{dir:"in"},"relay.closed":{dir:"in"},"relay.publish.result":{dir:"in"},"relay.publishEncrypted.result":{dir:"in"},"relay.query.result":{dir:"in"},"identity.getPublicKey":{dir:"out",fields:{...u}},"identity.getRelays":{dir:"out",fields:{...u}},"identity.getProfile":{dir:"out",fields:{...u}},"identity.getFollows":{dir:"out",fields:{...u}},"identity.getList":{dir:"out",fields:{...u,listType:"string"}},"identity.getZaps":{dir:"out",fields:{...u}},"identity.getMutes":{dir:"out",fields:{...u}},"identity.getBlocked":{dir:"out",fields:{...u}},"identity.getBadges":{dir:"out",fields:{...u}},"identity.changed":{dir:"in"},"identity.getPublicKey.result":{dir:"in"},"identity.getRelays.result":{dir:"in"},"identity.getProfile.result":{dir:"in"},"identity.getFollows.result":{dir:"in"},"identity.getList.result":{dir:"in"},"identity.getZaps.result":{dir:"in"},"identity.getMutes.result":{dir:"in"},"identity.getBlocked.result":{dir:"in"},"identity.getBadges.result":{dir:"in"},"storage.get":{dir:"out",fields:{...u,key:"string"}},"storage.set":{dir:"out",fields:{...u,key:"string",value:"string"}},"storage.remove":{dir:"out",fields:{...u,key:"string"}},"storage.keys":{dir:"out",fields:{...u}},"storage.get.result":{dir:"in"},"storage.set.result":{dir:"in"},"storage.remove.result":{dir:"in"},"storage.keys.result":{dir:"in"},"inc.emit":{dir:"out",fields:{topic:"string"},forbiddenFields:["sender"]},"inc.subscribe":{dir:"out",fields:{...u,topic:"string"}},"inc.unsubscribe":{dir:"out",fields:{topic:"string"}},"inc.channel.open":{dir:"out",fields:{...u,target:"string"}},"inc.channel.emit":{dir:"out",fields:{channelId:"string"}},"inc.channel.broadcast":{dir:"out"},"inc.channel.list":{dir:"out",fields:{...u}},"inc.channel.close":{dir:"out",fields:{channelId:"string"}},"inc.subscribe.result":{dir:"in"},"inc.event":{dir:"in",fields:{topic:"string",sender:"string"}},"inc.channel.open.result":{dir:"in"},"inc.channel.opened":{dir:"in",fields:{channelId:"string",peer:"string"}},"inc.channel.event":{dir:"in"},"inc.channel.list.result":{dir:"in"},"inc.channel.closed":{dir:"in"},"theme.get":{dir:"out",fields:{...u}},"theme.get.result":{dir:"in"},"theme.changed":{dir:"in"},"keys.forward":{dir:"out",fields:{key:"string",code:"string",ctrl:"boolean",alt:"boolean",shift:"boolean",meta:"boolean"}},"keys.registerAction":{dir:"out",fields:{...u,action:"object"}},"keys.unregisterAction":{dir:"out",fields:{actionId:"string"}},"keys.registerAction.result":{dir:"in"},"keys.bindings":{dir:"in"},"keys.action":{dir:"in"},"media.session.create":{dir:"out",fields:{...u,owner:"object"}},"media.session.update":{dir:"out",fields:{sessionId:"string",metadata:"object"}},"media.session.destroy":{dir:"out",fields:{sessionId:"string"}},"media.state":{dir:"out",fields:{sessionId:"string",status:"string"}},"media.capabilities":{dir:"out",fields:{sessionId:"string",actions:"array"}},"media.session.create.result":{dir:"in"},"media.command":{dir:"in"},"media.controls":{dir:"in"},"notify.send":{dir:"out",fields:{...u,title:"string"}},"notify.dismiss":{dir:"out",fields:{notificationId:"string"}},"notify.badge":{dir:"out",fields:{count:"number"}},"notify.channel.register":{dir:"out",fields:{channelId:"string",label:"string"}},"notify.permission.request":{dir:"out",fields:{...u}},"notify.send.result":{dir:"in"},"notify.permission.result":{dir:"in"},"notify.action":{dir:"in"},"notify.clicked":{dir:"in"},"notify.dismissed":{dir:"in"},"notify.controls":{dir:"in"},"config.registerSchema":{dir:"out",fields:{...u,schema:"object"}},"config.get":{dir:"out",fields:{...u}},"config.subscribe":{dir:"out"},"config.unsubscribe":{dir:"out"},"config.openSettings":{dir:"out"},"config.registerSchema.result":{dir:"in"},"config.values":{dir:"in"},"config.schemaError":{dir:"in"},"resource.info":{dir:"out",fields:{...u}},"resource.bytes":{dir:"out",fields:{...u,url:"string"}},"resource.bytesMany":{dir:"out",fields:{...u,requests:"array"}},"resource.cancel":{dir:"out",fields:{...u}},"resource.info.result":{dir:"in"},"resource.info.error":{dir:"in"},"resource.bytes.result":{dir:"in"},"resource.bytes.error":{dir:"in"},"resource.bytesMany.result":{dir:"in"},"resource.bytesMany.error":{dir:"in"},"cvm.discover":{dir:"out",fields:{...u}},"cvm.request":{dir:"out",fields:{...u,server:"object",message:"object"}},"cvm.close":{dir:"out",fields:{...u,server:"object"}},"cvm.registry.list":{dir:"out",fields:{...u}},"cvm.registry.has":{dir:"out",fields:{...u,family:"string"}},"cvm.registry.describe":{dir:"out",fields:{...u,family:"string"}},"cvm.registry.call":{dir:"out",fields:{...u,family:"string",tool:"string"}},"cvm.discover.result":{dir:"in"},"cvm.request.result":{dir:"in"},"cvm.close.result":{dir:"in"},"cvm.event":{dir:"in"},"cvm.registry.list.result":{dir:"in"},"cvm.registry.has.result":{dir:"in"},"cvm.registry.describe.result":{dir:"in"},"cvm.registry.call.result":{dir:"in"},"outbox.getEvent":{dir:"out",fields:{...u,eventId:"string"}},"outbox.query":{dir:"out",fields:{...u,filters:"present"}},"outbox.subscribe":{dir:"out",fields:{...u,subId:"string",filters:"present"}},"outbox.close":{dir:"out",fields:{...u,subId:"string"}},"outbox.publish":{dir:"out",fields:{...u,event:"object"}},"outbox.resolveRelays":{dir:"out",fields:{...u,target:"present"}},"outbox.getEvent.result":{dir:"in"},"outbox.query.result":{dir:"in"},"outbox.event":{dir:"in"},"outbox.closed":{dir:"in"},"outbox.publish.result":{dir:"in"},"outbox.resolveRelays.result":{dir:"in"},"upload.info":{dir:"out",fields:{...u}},"upload.upload":{dir:"out",fields:{...u,request:"object"}},"upload.status":{dir:"out",fields:{...u,uploadId:"string"}},"upload.info.result":{dir:"in"},"upload.upload.result":{dir:"in"},"upload.status.result":{dir:"in"},"upload.status.changed":{dir:"in"},"intent.invoke":{dir:"out",fields:{...u,request:"object"}},"intent.available":{dir:"out",fields:{...u,archetype:"string"}},"intent.handlers":{dir:"out",fields:{...u}},"intent.invoke.result":{dir:"in",fields:{...u,result:"object"}},"intent.available.result":{dir:"in"},"intent.handlers.result":{dir:"in"},"intent.deliver":{dir:"in",fields:{delivery:"object"}},"intent.changed":{dir:"in"},"ble.open":{dir:"out",fields:{...u,request:"object"}},"ble.services":{dir:"out",fields:{...u,sessionId:"string"}},"ble.read":{dir:"out",fields:{...u,sessionId:"string",target:"object"}},"ble.write":{dir:"out",fields:{...u,sessionId:"string",target:"object",data:"array"}},"ble.subscribe":{dir:"out",fields:{...u,sessionId:"string",target:"object"}},"ble.unsubscribe":{dir:"out",fields:{...u,sessionId:"string",target:"object"}},"ble.close":{dir:"out",fields:{...u,sessionId:"string"}},"ble.open.result":{dir:"in"},"ble.services.result":{dir:"in"},"ble.read.result":{dir:"in"},"ble.write.result":{dir:"in"},"ble.subscribe.result":{dir:"in"},"ble.unsubscribe.result":{dir:"in"},"ble.close.result":{dir:"in"},"ble.event":{dir:"in"},"common.encodeNip19":{dir:"out",fields:{...u,input:"object"}},"common.decodeNip19":{dir:"out",fields:{...u,value:"string"}},"common.getProfile":{dir:"out",fields:{...u,target:"string"}},"common.follows":{dir:"out",fields:{...u}},"common.follow":{dir:"out",fields:{...u,pubkeys:"array"}},"common.unfollow":{dir:"out",fields:{...u,pubkeys:"array"}},"common.react":{dir:"out",fields:{...u,targetEventId:"string",reaction:"string"}},"common.report":{dir:"out",fields:{...u,target:"object",reason:"string",text:"string"}},"common.encodeNip19.result":{dir:"in"},"common.decodeNip19.result":{dir:"in"},"common.getProfile.result":{dir:"in"},"common.follows.result":{dir:"in"},"common.follow.result":{dir:"in"},"common.unfollow.result":{dir:"in"},"common.react.result":{dir:"in"},"common.report.result":{dir:"in"},"webrtc.open":{dir:"out",fields:{...u,request:"object"}},"webrtc.send":{dir:"out",fields:{...u,sessionId:"string",payload:"present"}},"webrtc.close":{dir:"out",fields:{...u,sessionId:"string"}},"webrtc.open.result":{dir:"in"},"webrtc.send.result":{dir:"in"},"webrtc.close.result":{dir:"in"},"webrtc.event":{dir:"in"},"link.open":{dir:"out",fields:{...u,url:"string"}},"link.open.result":{dir:"in"},"count.query":{dir:"out",fields:{...u,filters:"array"}},"count.query.result":{dir:"in"},"lists.supported":{dir:"out",fields:{...u}},"lists.add":{dir:"out",fields:{...u,list:"object",items:"array"}},"lists.remove":{dir:"out",fields:{...u,list:"object",items:"array"}},"lists.supported.result":{dir:"in"},"lists.add.result":{dir:"in"},"lists.remove.result":{dir:"in"},"serial.open":{dir:"out",fields:{...u,request:"object"}},"serial.write":{dir:"out",fields:{...u,sessionId:"string",data:"array"}},"serial.close":{dir:"out",fields:{...u,sessionId:"string"}},"serial.open.result":{dir:"in"},"serial.write.result":{dir:"in"},"serial.close.result":{dir:"in"},"serial.event":{dir:"in"},"fs.info":{dir:"out",fields:{...u}},"fs.pickFile":{dir:"out",fields:{...u}},"fs.pickFiles":{dir:"out",fields:{...u}},"fs.pickDirectory":{dir:"out",fields:{...u}},"fs.pickSaveFile":{dir:"out",fields:{...u}},"fs.stat":{dir:"out",fields:{...u,path:"string"}},"fs.list":{dir:"out",fields:{...u,path:"string"}},"fs.read":{dir:"out",fields:{...u,path:"string"}},"fs.write":{dir:"out",fields:{...u,path:"string",data:"string"}},"fs.mkdir":{dir:"out",fields:{...u,path:"string"}},"fs.remove":{dir:"out",fields:{...u,path:"string"}},"fs.move":{dir:"out",fields:{...u,fromPath:"string",toPath:"string"}},"fs.watch":{dir:"out",fields:{...u,path:"string"}},"fs.unwatch":{dir:"out",fields:{...u,watchId:"string"}},"fs.info.result":{dir:"in"},"fs.pickFile.result":{dir:"in"},"fs.pickFiles.result":{dir:"in"},"fs.pickDirectory.result":{dir:"in"},"fs.pickSaveFile.result":{dir:"in"},"fs.stat.result":{dir:"in"},"fs.list.result":{dir:"in"},"fs.read.result":{dir:"in"},"fs.write.result":{dir:"in"},"fs.mkdir.result":{dir:"in"},"fs.remove.result":{dir:"in"},"fs.move.result":{dir:"in"},"fs.watch.result":{dir:"in"},"fs.unwatch.result":{dir:"in"},"fs.changed":{dir:"in"},"dm.status":{dir:"out",fields:{...u}},"dm.conversations":{dir:"out",fields:{...u}},"dm.messages":{dir:"out",fields:{...u,conversationId:"string"}},"dm.send":{dir:"out",fields:{...u,recipients:"array",content:"string"}},"dm.subscribe":{dir:"out",fields:{...u}},"dm.unsubscribe":{dir:"out",fields:{...u,subscriptionId:"string"}},"dm.status.result":{dir:"in"},"dm.conversations.result":{dir:"in"},"dm.messages.result":{dir:"in"},"dm.send.result":{dir:"in"},"dm.subscribe.result":{dir:"in"},"dm.unsubscribe.result":{dir:"in"},"dm.message":{dir:"in"}},Nt=e=>typeof e=="string",we=e=>typeof e=="string"&&e.length>0,Rn=e=>typeof e=="boolean",Ee=(...e)=>n=>typeof n=="string"&&e.includes(n),Bt=e=>typeof e=="string"&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)&&e.length>=4;function _e(e,n={}){return r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const t=r;return Object.keys(t).some(s=>!(s in e)&&!(s in n))?!1:Object.entries(e).every(([s,i])=>i(t[s]))&&Object.entries(n).every(([s,i])=>t[s]===void 0||i(t[s]))}}var Qn=e=>n=>Array.isArray(n)&&n.length>0&&n.every(e),Lt=_e({type:Ee("text"),text:Nt}),$t=_e({type:Ee("image"),mimeType:Ee("image/png","image/jpeg","image/webp"),data:Bt}),Ft=e=>Lt(e)||$t(e),Gt=_e({role:Ee("system","user","assistant"),content:Qn(Ft)}),Wt=_e({},{model:we,images:Rn,json:Rn}),Vt=_e({handle:we,messages:Qn(Gt)},{format:Ee("text","json")}),zt={"llm.select":{optional:{requirements:Wt}},"llm.describe":{required:{handle:we}},"llm.generate":{required:{request:Vt}},"llm.cancel":{required:{requestId:we}}};function Qt(e,n,r){const t=zt[e];if(!t)return;const s=t.required??{},i=t.optional??{};n.id!==void 0&&!we(n.id)&&r.push({code:"wrong-type",field:"id",message:"NAP-LLM request ids are non-empty text"});for(const o of Object.keys(n))o==="type"||o==="id"||o in s||o in i||r.push({code:"forbidden-field",field:o,message:`Field "${o}" is not a parameter of ${e}; NAP-LLM requests carry exactly their API row parameters`});for(const[o,l]of Object.entries({...s,...i})){const a=n[o];if(a===void 0){o in s&&r.push({code:"missing-field",field:o,message:`Field "${o}" is required by ${e}`});continue}l(a)||r.push({code:"wrong-type",field:o,message:`Field "${o}" must match the NAP-LLM ${e} schema`})}}function $e(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return"array";const n=typeof e;return n==="string"||n==="number"||n==="boolean"?n:n==="object"?"object":"present"}function Kt(e,n){return n==="present"?e!=null:$e(e)===n}function Zt(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return;const r=e;typeof r.archetype!="string"&&n.push({code:r.archetype===void 0?"missing-field":"wrong-type",message:'Intent request requires a string "archetype" field',field:"request.archetype"});for(const s of["action","convention"])typeof r[s]!="string"&&n.push({code:r[s]===void 0?"missing-field":"wrong-type",message:`Intent request field "${s}" must be a string`,field:`request.${s}`});const t=typeof r.convention=="string"?/^napplet:([^/?#]+)\/([^/?#]+)$/.exec(r.convention):null;(!t||t[1]!==r.archetype||t[2]!==r.action)&&n.push({code:"wrong-type",message:"Intent convention must be stable and match archetype and action",field:"request.convention"}),r.handler!==void 0&&typeof r.handler!="string"&&n.push({code:"wrong-type",message:'Intent request field "handler" must be a string',field:"request.handler"}),r.behavior!==void 0&&$e(r.behavior)!=="object"&&n.push({code:"wrong-type",message:'Intent request field "behavior" must be an object',field:"request.behavior"}),r.handlerHint!==void 0&&Yt(r.handlerHint,n),"sender"in r&&n.push({code:"forbidden-field",message:"Intent request does not define a caller-supplied sender field",field:"request.sender"})}function Yt(e,n){if($e(e)!=="object"){n.push({code:"wrong-type",message:'Intent request field "handlerHint" must be an object',field:"request.handlerHint"});return}const{address:r,relays:t}=e;(typeof r!="string"||!/^35129:[0-9a-f]{64}:.+$/s.test(r))&&n.push({code:r===void 0?"missing-field":"wrong-type",message:'Intent handler hint "address" must be a 35129:<pubkey>:<d> coordinate',field:"request.handlerHint.address"}),t!==void 0&&!(Array.isArray(t)&&t.every(s=>typeof s=="string"))&&n.push({code:"wrong-type",message:'Intent handler hint "relays" must be an array of strings',field:"request.handlerHint.relays"})}function Kn(e,n,r){Array.isArray(e)&&e.every(t=>typeof t=="string")||r.push({code:"wrong-type",message:`Field "${n}" must be an array of strings`,field:n})}function Xt(e,n){e.servers!==void 0&&Kn(e.servers,"servers",n)}function Jt(e,n){if(Array.isArray(e)){if(e.length===0){n.push({code:"invalid-resource-request",message:'Field "requests" must contain at least one resource request',field:"requests"});return}for(const[r,t]of e.entries()){const s=`requests[${r}]`;if(typeof t!="object"||t===null||Array.isArray(t)){n.push({code:"invalid-resource-request",message:`Field "${s}" must be a resource request object`,field:s});continue}const i=t;typeof i.url!="string"&&n.push({code:i.url===void 0?"missing-field":"wrong-type",message:`Field "${s}.url" must be a string`,field:`${s}.url`}),i.servers!==void 0&&Kn(i.servers,`${s}.servers`,n)}}}function er(e){const n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{ok:!1,errors:[{code:"not-an-object",message:"Envelope must be a non-null object"}]};const r=e,t=r.type;if(typeof t!="string")return{ok:!1,errors:[{code:"missing-type",message:"Envelope is missing a string `type` field"}]};const s=t.indexOf(".");if(s<=0)return{ok:!1,type:t,errors:[{code:"malformed-type",message:`Envelope type "${t}" is not in domain.action form`}]};const i=t.slice(0,s);if(!Le.includes(i))return{ok:!1,type:t,domain:i,errors:[{code:"unknown-domain",message:`"${i}" is not a known NAP domain`}]};const l=Dt[t];if(!l)return{ok:!1,type:t,domain:i,errors:[{code:"unknown-type",message:`"${t}" is not a known ${i} message type`}]};for(const[a,d]of Object.entries(l.fields??{})){if(!(a in r)||r[a]===void 0){n.push({code:"missing-field",message:`Required field "${a}" is missing`,field:a});continue}Kt(r[a],d)||n.push({code:"wrong-type",message:`Field "${a}" should be ${d} but is ${$e(r[a])}`,field:a})}if(l.dir==="in")return{ok:!1,type:t,domain:i,direction:"in",errors:[{code:"inbound-type-emitted",message:`"${t}" is a shell→napplet message; a napplet must not emit it`},...n]};for(const a of l.forbiddenFields??[])a in r&&n.push({code:"forbidden-field",message:`Field "${a}" cannot be emitted by a napplet: ${l.forbiddenReason??"it must be runtime-derived"}`,field:a});return i==="llm"&&Qt(t,r,n),t==="intent.invoke"&&Zt(r.request,n),t==="resource.bytes"&&Xt(r,n),t==="resource.bytesMany"&&Jt(r.requests,n),{ok:n.length===0,type:t,domain:i,direction:"out",errors:n}}var Zn=5129,nr=15129,ce=35129,gn=[Zn,nr,ce],Yn=["image/png","image/jpeg","image/webp"],Xn=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function Jn(e,n){return e.tags.find(r=>r[0]===n)}function tr(e){return gn.includes(e)}function Fe(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function et(e){return Jn(e,"d")?.[1]||void 0}function rr(e){return e.tags.filter(n=>n[0]==="R").map(n=>n[1]?.trim()??"").filter(Boolean)}function nt(e){return et(e)??Jn(e,"title")?.[1]??e.id}function sr(e){const n=[],r=[];for(const i of e.tags.filter(o=>o[0]==="screenshot")){const o=In(i,n);o&&r.push(o)}const t=e.tags.filter(i=>i[0]==="preview");let s;return t.length>1?n.push({code:"invalid-presentation-media",message:"Multiple preview tags; clients ignore the preview (NIP-5D §Presentation media)"}):t.length===1&&(s=In(t[0],n)),{screenshots:r,preview:s,warnings:n}}function In(e,n){const r=e[0],t=c=>{n.push({code:"invalid-presentation-media",message:`Ignore ${r} tag: ${c} (NIP-5D §Presentation media)`})},s=new Map;for(const c of e.slice(1)){const m=typeof c=="string"?c.indexOf(" "):-1,y=m<0?c:c.slice(0,m),w=m<0?void 0:c.slice(m+1),P=s.get(y)??[];w!==void 0?P.push(w):P.push(""),s.set(y,P)}const i=s.get("x");if(!i||i.length!==1||!Fe(i[0]))return t("exactly one x field with a lowercase sha256 is required");const o={sha256:i[0]},l=(c,m)=>{const y=s.get(c);if(y){if(y.length!==1||!m(y[0])){n.push({code:"invalid-presentation-media",message:`Ignore ${c} field on ${r} ${o.sha256}: malformed or repeated (NIP-5D §Presentation media)`});return}return y[0]}},a=l("m",c=>Xn.test(c));if(a!==void 0){if(!(r==="preview"?a.toLowerCase().startsWith("video/"):Yn.includes(a.toLowerCase())))return t(`${a} cannot match a decodable ${r==="preview"?"video":"PNG, JPEG or WebP"} format`);o.mimeType=a}const d=l("dim",c=>/^[1-9][0-9]*x[1-9][0-9]*$/.test(c));if(d!==void 0){const[c,m]=d.split("x").map(Number);o.dim={width:c,height:m}}const h=l("size",c=>/^(?:0|[1-9][0-9]*)$/.test(c));if(h!==void 0&&(o.size=Number(h)),r==="preview"){const c=l("duration",m=>/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/.test(m));c!==void 0&&(o.duration=Number(c))}const p=l("alt",c=>c.trim().length>0);return p!==void 0&&(o.alt=p),o}function Ge(e){const n=[],r=[];if(!e)return{ok:!1,requires:[],optional:[],errors:[{code:"missing-manifest-event",message:"No NIP-5D manifest event was resolved"}],warnings:r};const t=et(e),s=rr(e);tr(e.kind)||n.push({code:"invalid-napplet-kind",message:`Manifest event kind ${e.kind} is not a NIP-5D napplet kind`});const i=e.tags.filter(l=>l[0]==="d");e.kind===ce&&(i.length!==1||!t)?n.push({code:"missing-d-tag",message:"Named manifests require exactly one non-empty d tag"}):e.kind!==ce&&i.length>0&&n.push({code:"unexpected-d-tag",message:"Only named manifests carry a d tag"});const o=e.tags.filter(l=>l[0]==="x");return(o.length!==1||o[0].length!==2||!Fe(o[0][1]))&&n.push({code:"invalid-artifact-hash",message:"Manifest requires exactly one x tag with the lowercase sha256 of /index.html"}),(typeof e.content!="string"||!e.content.trim())&&n.push({code:"missing-description",message:"Manifest content must contain a non-empty plain-text description"}),ir(e,n,r),or(e,n,r),{ok:n.length===0,kind:e.kind,dTag:t,requires:s,optional:e.tags.filter(l=>l[0]==="O").map(l=>l[1]).filter(Boolean),errors:n,warnings:r}}function ir(e,n,r){for(const t of e.tags.filter(s=>s[0]==="R"||s[0]==="O")){const s=t[1];t.length!==2||!s||/[.:\s]/.test(s)||s.startsWith("NAP-")?n.push({code:t[0]==="R"?"invalid-required-nap":"invalid-optional-nap",message:`${t[0]} must name one bare NAP domain`}):Le.includes(s)||r.push({code:"unknown-required-nap",message:`Domain "${s}" is not in this tool's registry; check its NAP and runtime availability`})}}function or(e,n,r){for(const i of["title","source","a","A"]){const o=e.tags.filter(l=>l[0]===i);(o.length>1||o.length&&(i==="a"||i==="A")&&e.kind!==Zn)&&n.push({code:"invalid-metadata",message:`Invalid ${i} tag cardinality for kind ${e.kind}`})}const t=e.tags.filter(i=>i[0]==="source");for(const i of t)(i.length!==2||!xn(i[1]))&&n.push({code:"invalid-metadata",message:"source must contain one HTTP(S), SSH, Git, SCP, or nostr repository location"});ar(e,t.length===1&&t[0].length===2&&xn(t[0][1]),n,r);for(const i of e.tags.filter(o=>o[0]==="i"))(!i[1]?.trim()||i[1].includes("?"))&&n.push({code:"invalid-metadata",message:"Intent advertisements must be non-empty queryless identities"});const s=e.tags.filter(i=>i[0]==="icon");(s.length>1||s.some(i=>i.length!==3||!Fe(i[1])||!Yn.includes(i[2])))&&r.push({code:"invalid-icon",message:"Ignore invalid icon metadata and use generic artwork (NIP-5D §Icon)"}),r.push(...sr(e).warnings)}function ar(e,n,r,t){const s=e.tags.filter(o=>o[0]==="source-commit");s.length>1||s.some(o=>o.length!==2||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(o[1]))?r.push({code:"invalid-metadata",message:"source-commit must appear once with a full lowercase-hex Git commit ID (40 or 64 characters)"}):s.length===1&&!n&&t.push({code:"unused-source-commit",message:"source-commit without a Git repository source is ignored (NIP-5D §Source)"});const i=e.tags.filter(o=>o[0]==="source-archive");(i.length>1||i.some(o=>o.length!==4||!lr(o[1])||!Fe(o[2])||!Xn.test(o[3]??"")))&&r.push({code:"invalid-metadata",message:"source-archive must appear once with an HTTPS URL without credentials or fragment, a lowercase sha256, and a MIME type"})}function lr(e){if(!e||e.includes("#"))return!1;try{const n=new URL(e);return n.protocol==="https:"&&!n.username&&!n.password}catch{return!1}}function xn(e){if(!e||/^[a-z]:[\\/]/i.test(e))return!1;try{const{protocol:n}=new URL(e);if(["http:","https:","ssh:","git:"].includes(n))return!0;if(n==="nostr:")return e.length>8&&e.startsWith("nostr://");if(n==="file:")return!1}catch{}return!e.includes("://")&&/^(?:[^@\s/:]+@)?[^:\s/]+:[^\s]+$/.test(e)}var de="f".repeat(64),dr={id:"reference-source-endpoint",catalogId:"reference-source"},cr="https://reference.invalid/blob",ur=`named:${de}:reference-handler`,pr={kind:35129,pubkey:de,id:"0".repeat(64),tags:[["d","reference-handler"],["z","note"],["i","napplet:note/open","event"]]},fr="reference-subscriber",mr="napplet:note/open";function ke(e,n,r){return f({type:e,id:n,result:{entries:[r]}})}var f=e=>[e],j=()=>[];function kn(e){if(typeof e!="string"||!e.startsWith("data:"))return null;const n=e.indexOf(",");if(n<0)return{blob:new Blob([],{type:"text/plain"}),mime:"text/plain"};const r=e.slice(5,n),t=e.slice(n+1),s=r.split(";").filter(Boolean),i=s.includes("base64"),o=s.find(l=>l.includes("/"))??"text/plain";try{if(i){const l=globalThis.atob(t),a=Uint8Array.from(l,d=>d.charCodeAt(0));return{blob:new Blob([a],{type:o}),mime:o}}return{blob:new Blob([decodeURIComponent(t)],{type:o}),mime:o}}catch{return null}}var gr={"gamepad.subscribe":()=>f({type:"gamepad.state",available:!1,reason:"unavailable",focused:!1,pads:[]}),"gamepad.unsubscribe":j,"relay.subscribe":e=>f({type:"relay.eose",subId:e.subId}),"relay.close":j,"relay.publish":e=>f({type:"relay.publish.result",id:e.id,ok:!0,event:e.event}),"relay.publishEncrypted":e=>f({type:"relay.publishEncrypted.result",id:e.id,ok:!0,event:e.event}),"relay.query":e=>f({type:"relay.query.result",id:e.id,events:[]}),"identity.getPublicKey":e=>f({type:"identity.getPublicKey.result",id:e.id,pubkey:de}),"identity.getRelays":e=>f({type:"identity.getRelays.result",id:e.id,relays:{}}),"identity.getProfile":e=>f({type:"identity.getProfile.result",id:e.id,profile:null}),"identity.getFollows":e=>f({type:"identity.getFollows.result",id:e.id,pubkeys:[]}),"identity.getList":e=>f({type:"identity.getList.result",id:e.id,entries:[]}),"identity.getZaps":e=>f({type:"identity.getZaps.result",id:e.id,zaps:[]}),"identity.getMutes":e=>f({type:"identity.getMutes.result",id:e.id,pubkeys:[]}),"identity.getBlocked":e=>f({type:"identity.getBlocked.result",id:e.id,pubkeys:[]}),"identity.getBadges":e=>f({type:"identity.getBadges.result",id:e.id,badges:[]}),"storage.get":e=>f({type:"storage.get.result",id:e.id,value:null}),"storage.set":e=>f({type:"storage.set.result",id:e.id}),"storage.remove":e=>f({type:"storage.remove.result",id:e.id}),"storage.keys":e=>f({type:"storage.keys.result",id:e.id,keys:[]}),"inc.emit":j,"inc.subscribe":e=>f({type:"inc.subscribe.result",id:e.id}),"inc.unsubscribe":j,"inc.channel.open":e=>f({type:"inc.channel.open.result",id:e.id,channelId:`chan-${String(e.id)}`,peer:"reference-peer"}),"inc.channel.emit":j,"inc.channel.broadcast":j,"inc.channel.list":e=>f({type:"inc.channel.list.result",id:e.id,channels:[]}),"inc.channel.close":j,"theme.get":e=>f({type:"theme.get.result",id:e.id,theme:{colors:{background:"#000000",text:"#ffffff",primary:"#663399"}}}),"keys.forward":j,"keys.registerAction":e=>f({type:"keys.registerAction.result",id:e.id,actionId:`action-${String(e.id)}`}),"keys.unregisterAction":j,"media.session.create":e=>f({type:"media.session.create.result",id:e.id,sessionId:`session-${String(e.id)}`,owner:e.owner}),"media.session.update":j,"media.session.destroy":j,"media.state":j,"media.capabilities":j,"notify.send":e=>f({type:"notify.send.result",id:e.id,notificationId:`notif-${String(e.id)}`}),"notify.dismiss":j,"notify.badge":j,"notify.channel.register":j,"notify.permission.request":e=>f({type:"notify.permission.result",id:e.id,granted:!0}),"config.registerSchema":e=>f({type:"config.registerSchema.result",id:e.id,ok:!0}),"config.get":e=>f({type:"config.values",id:e.id,values:{}}),"config.subscribe":()=>f({type:"config.values",values:{}}),"config.unsubscribe":j,"config.openSettings":j,"resource.bytes":e=>{const n=kn(e.url);return f(n?{type:"resource.bytes.result",id:e.id,blob:n.blob,mime:n.mime}:{type:"resource.bytes.result",id:e.id,blob:new Blob([]),mime:"application/octet-stream"})},"resource.bytesMany":e=>f({type:"resource.bytesMany.result",id:e.id,items:Array.isArray(e.requests)?e.requests.map(n=>{const r=typeof n=="object"&&n!==null&&!Array.isArray(n)?n.url:void 0,t=kn(r);return{url:typeof r=="string"?r:"",ok:!0,blob:t?.blob??new Blob([]),mime:t?.mime??"application/octet-stream"}}):[]}),"resource.info":e=>f({type:"resource.info.result",id:e.id,info:{schemes:[{scheme:"data",enabled:!0},{scheme:"https",enabled:!0}],maxServers:8}}),"resource.cancel":j,"cvm.discover":e=>f({type:"cvm.discover.result",id:e.id,servers:[]}),"cvm.request":e=>f({type:"cvm.request.result",id:e.id,message:{}}),"cvm.close":e=>f({type:"cvm.close.result",id:e.id}),"outbox.getEvent":e=>f({type:"outbox.getEvent.result",id:e.id}),"outbox.query":e=>f({type:"outbox.query.result",id:e.id,events:[]}),"outbox.subscribe":e=>f({type:"outbox.closed",subId:e.subId,reason:"reference shell complete"}),"outbox.close":j,"outbox.publish":e=>f({type:"outbox.publish.result",id:e.id,ok:!0}),"outbox.resolveRelays":e=>f({type:"outbox.resolveRelays.result",id:e.id,plan:{}}),"upload.info":e=>f({type:"upload.info.result",id:e.id,info:{rails:[{rail:"nip96",enabled:!0,returns:["https"]},{rail:"blossom",enabled:!0,returns:["https","blossom"]}]}}),"upload.upload":e=>f({type:"upload.upload.result",id:e.id,result:{url:cr}}),"upload.status":e=>f({type:"upload.status.result",id:e.id,status:{}}),"ble.open":e=>f({type:"ble.open.result",id:e.id,session:{id:"ble-reference",state:"open",device:{id:"reference-device",name:"Reference BLE"}}}),"ble.services":e=>f({type:"ble.services.result",id:e.id,services:[]}),"ble.read":e=>f({type:"ble.read.result",id:e.id,data:[]}),"ble.write":e=>f({type:"ble.write.result",id:e.id}),"ble.subscribe":e=>f({type:"ble.subscribe.result",id:e.id}),"ble.unsubscribe":e=>f({type:"ble.unsubscribe.result",id:e.id}),"ble.close":e=>f({type:"ble.close.result",id:e.id}),"common.encodeNip19":e=>f({type:"common.encodeNip19.result",id:e.id,ok:!0,value:"npub1reference",nip19Type:"npub"}),"common.decodeNip19":e=>f({type:"common.decodeNip19.result",id:e.id,ok:!0,nip19Type:"npub",hex:de}),"common.getProfile":e=>f({type:"common.getProfile.result",id:e.id,ok:!0,pubkey:de,profile:null}),"common.follows":e=>f({type:"common.follows.result",id:e.id,ok:!0,pubkeys:[]}),"common.follow":e=>f({type:"common.follow.result",id:e.id,ok:!0}),"common.unfollow":e=>f({type:"common.unfollow.result",id:e.id,ok:!0}),"common.react":e=>f({type:"common.react.result",id:e.id,ok:!0,eventId:"0".repeat(64)}),"common.report":e=>f({type:"common.report.result",id:e.id,ok:!0,eventId:"1".repeat(64)}),"webrtc.open":e=>f({type:"webrtc.open.result",id:e.id,session:{id:"webrtc-reference",scope:{type:"direct",pubkey:de},channel:"default",state:"connecting"}}),"webrtc.send":e=>f({type:"webrtc.send.result",id:e.id}),"webrtc.close":e=>f({type:"webrtc.close.result",id:e.id}),"link.open":e=>f({type:"link.open.result",id:e.id,status:"opened"}),"count.query":e=>f({type:"count.query.result",id:e.id,ok:!0,count:0}),"lists.supported":e=>f({type:"lists.supported.result",id:e.id,lists:[]}),"lists.add":e=>f({type:"lists.add.result",id:e.id,ok:!0,added:0,skipped:0}),"lists.remove":e=>f({type:"lists.remove.result",id:e.id,ok:!0,removed:0,skipped:0}),"serial.open":e=>f({type:"serial.open.result",id:e.id,session:{id:`serial-${String(e.id)}`,state:"open"}}),"serial.write":e=>f({type:"serial.write.result",id:e.id}),"serial.close":e=>f({type:"serial.close.result",id:e.id}),"fs.info":e=>f({type:"fs.info.result",id:e.id,info:{roots:[{path:"/shared",name:"Shared files",permissions:["read","list","write","create","delete","watch"]}],limits:{maxReadBytes:1048576,maxWriteBytes:1048576,maxWatchCount:16}}}),"fs.pickFile":e=>ke("fs.pickFile.result",e.id,{path:"/picked/file.txt",kind:"file",name:"file.txt",permissions:["read"]}),"fs.pickFiles":e=>ke("fs.pickFiles.result",e.id,{path:"/picked/file.txt",kind:"file",name:"file.txt",permissions:["read"]}),"fs.pickDirectory":e=>ke("fs.pickDirectory.result",e.id,{path:"/picked",kind:"directory",name:"picked",permissions:["read","list"]}),"fs.pickSaveFile":e=>ke("fs.pickSaveFile.result",e.id,{path:"/picked/export.json",kind:"file",name:"export.json",permissions:["write","create"]}),"fs.stat":e=>f({type:"fs.stat.result",id:e.id,metadata:{path:e.path,kind:"file",size:0}}),"fs.list":e=>f({type:"fs.list.result",id:e.id,entries:[]}),"fs.read":e=>f({type:"fs.read.result",id:e.id,result:{data:"",offset:0,bytesRead:0,eof:!0,size:0}}),"fs.write":e=>f({type:"fs.write.result",id:e.id,result:{bytesWritten:0,size:0}}),"fs.mkdir":e=>f({type:"fs.mkdir.result",id:e.id}),"fs.remove":e=>f({type:"fs.remove.result",id:e.id}),"fs.move":e=>f({type:"fs.move.result",id:e.id}),"fs.watch":e=>f({type:"fs.watch.result",id:e.id,watchId:`watch-${String(e.id)}`}),"fs.unwatch":e=>f({type:"fs.unwatch.result",id:e.id})},tt={name:"Reference connection",model:"reference-model",route:"Reference shell → reference provider (no network)",images:!0,json:!0},be=(e,n)=>({error:{code:e,message:n}}),qe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{};function hr(e,n){let r=e.get(n.id);return r||(r={handles:new Set,active:new Map,sequence:0},e.set(n.id,r)),r}function rt(e){return{handle:e,...tt}}function yr(e,n){const r=qe(n.requirements);if(r.model!==void 0&&r.model!==tt.model)return be("unsupported","No connection offers the requested model");e.sequence+=1;const t=`reference-llm-h${e.sequence}`;return e.handles.add(t),{model:rt(t)}}function br(e,n){const r=String(n.handle);return e.handles.has(r)?{model:rt(r)}:be("selection-expired","Select a model again")}function vr(e){const n=Array.isArray(e.messages)?e.messages:[];let r="";for(const t of n){const s=qe(t);if(!(s.role!=="user"||!Array.isArray(s.content)))for(const i of s.content){const o=qe(i);o.type==="text"&&typeof o.text=="string"&&(r=o.text)}}return r}function wr(e,n,r){const t=a=>[{type:"llm.generate.result",id:n,...a}];if(e.active.has(n))return t(be("invalid-request","Request id is still active"));const s=qe(r.request);if(!e.handles.has(String(s.handle)))return t(be("selection-expired","Select a model again"));const i=vr(s);if(i.includes("[[decline]]"))return t(be("user-cancelled","The user declined disclosure"));if(i.includes("[[stall]]"))return e.active.set(n,r),[];if(i.includes("[[refuse]]"))return t({result:{text:"",finish:"refusal"}});const o=s.format==="json"?JSON.stringify({echo:i}):`Echo: ${i}`,l={inputTokens:JSON.stringify(s.messages).length,outputTokens:o.length};return[{type:"llm.delta",requestId:n,sequence:0,text:o.slice(0,Math.ceil(o.length/2))},...t({result:{text:o,finish:"stop",usage:l}})]}function Er(e,n,r){const t=String(r.requestId);return e.active.delete(t)?[{type:"llm.generate.result",id:t,error:{code:"cancelled",message:"Generation cancelled; provider charges may still apply."}},{type:"llm.cancel.result",id:n,cancelled:!0}]:[{type:"llm.cancel.result",id:n,cancelled:!1}]}function Sr(e,n,r){const t=String(r.type),s=String(r.id),i=hr(e,n);switch(t){case"llm.select":return[{type:"llm.select.result",id:s,...yr(i,r)}];case"llm.describe":return[{type:"llm.describe.result",id:s,...br(i,r)}];case"llm.generate":return structuredClone(wr(i,s,r));case"llm.cancel":return Er(i,s,r);default:return[{type:`${t}.result`,id:s,error:{code:"invalid-request",message:`Unknown operation ${t}`}}]}}function Tr(){const e=new Map;return{handle:(n,r)=>Sr(e,n,r),reset(){e.clear()}}}function _r(e){const n=new Set,r=Tr();return Object.assign((s,i)=>{const o=Rr(i),l=er(i);if(e.records.push({envelope:i,verdict:l,timestamp:e.now()}),!o||!l.ok)return[];const a=s.domains??Le;if(!a.includes(o.slice(0,o.indexOf("."))))return[];if(o==="shell.ready")return n.has(s.id)?[]:(n.add(s.id),f({type:"shell.init",capabilities:{domains:[...a]},services:[]}));const d=i;if(o.startsWith("llm."))return r.handle(s,d);if(o==="intent.invoke")return e.intents.handleInvoke(s,d);if(o==="intent.available")return f({type:"intent.available.result",id:d.id,availability:e.intents.availability(d.archetype)});if(o==="intent.handlers")return f({type:"intent.handlers.result",id:d.id,handlers:e.intents.handlers()});if(o==="inc.emit")return Ir(s,d,e.queueDelivery);const h=gr[o];return h?h(d):[]},{reset(){r.reset()}})}function Rr(e){if(!e||typeof e!="object")return;const n=e.type;return typeof n=="string"?n:void 0}function Ir(e,n,r){if(n.topic!==mr)return[];const t={type:"inc.event",topic:n.topic,sender:e.id};return"payload"in n&&(t.payload=n.payload),r(fr,t),[]}function xr(e){return e.kind===5129?`snapshot:${e.id}`:e.kind===15129?`root:${e.pubkey}`:`named:${e.pubkey}:${e.tags.find(n=>n[0]==="d")?.[1]??""}`}function kr(e,n){if(!e.tags.some(t=>t[0]==="z"&&t[1]===n))return[];const r=[];for(const t of e.tags)t[0]!=="i"||/^napplet:([^/?#]+)\/([^/?#]+)$/.exec(t[1]??"")?.[1]!==n||r.push({convention:t[1],params:t.slice(2)});return r}function Mr(e,n,r){const t=[];for(const s of e){const i=kr(s,n);if(!i.length)continue;const o=s.tags.find(a=>a[0]==="title")?.[1],l=xr(s);t.push({id:l,...o?{title:o}:{},actions:[...new Set(i.map(({convention:a})=>a.slice(a.indexOf("/")+1)))],conventions:[...new Set(i.map(({convention:a})=>a))],contracts:i,...l===r?{isDefault:!0}:{}})}return{archetype:n,available:t.length>0,candidates:t,hasDefault:t.some(s=>s.isDefault)}}function Ur(e,n=[pr],r={note:ur}){const t=s=>Mr(n,String(s),r[String(s)]);return{availability:t,handlers:()=>[...new Set(n.flatMap(s=>s.tags.filter(i=>i[0]==="z").map(i=>i[1])))].map(t),handleInvoke(s,i){const o=i.request,l=t(o.archetype).candidates.filter(m=>m.conventions.includes(o.convention)),a=o.handler&&!["default","choose"].includes(o.handler),d=o.handler==="choose"?void 0:a?l.find(m=>m.id===o.handler):l.find(m=>m.isDefault)??l[0];if(!d)return f({type:"intent.invoke.result",id:i.id,result:{ok:!1,error:"no handler"}});const{archetype:h,action:p,convention:c}=o;return e(d.id,structuredClone({type:"intent.deliver",delivery:{sender:s.catalogId,archetype:h,action:p,convention:c,..."payload"in o?{payload:o.payload}:{}}})),f({type:"intent.invoke.result",id:i.id,result:{ok:!0,archetype:h,action:p,convention:c,handler:d.id}})}}}function Pr(e={}){const n=[],r=Ar(),t=_r({now:e.now??Date.now,records:n,queueDelivery:r.queue,intents:Ur(r.queue,e.manifests,e.defaults)});return{get records(){return n},handle:s=>t(dr,s),handleFrom:t,takeDeliveries:r.take,reset(){n.length=0,t.reset(),r.clear()}}}function Ar(){const e=new Map;return{queue(n,r){const t=e.get(n);t?t.push(r):e.set(n,[r])},take(n){const r=e.get(n)??[];return e.delete(n),r},clear(){e.clear()}}}function jr(e){return{manifestHtml:e.manifestHtml,manifestEvent:e.manifestEvent??null,sandbox:e.sandbox??{allowScripts:!0,allowSameOrigin:!1},installedGlobal:e.boot.installedGlobal,bootError:e.boot.bootError,emitted:e.boot.emitted,forbiddenGlobals:e.forbiddenGlobals??[],degraded:e.boot.degraded,lifecycle:e.lifecycle??null}}var qr=`
|
|
2
|
-
if (domains.includes('llm')) {
|
|
3
|
-
const llmFields = { 'llm.select.result': 'model', 'llm.describe.result': 'model', 'llm.generate.result': 'result', 'llm.cancel.result': 'cancelled' };
|
|
4
|
-
const llmDeltas = new Map();
|
|
5
|
-
window.addEventListener('message', (event) => {
|
|
6
|
-
if (event.source !== window.parent) return;
|
|
7
|
-
const msg = event.data;
|
|
8
|
-
if (!msg || typeof msg !== 'object' || msg.type !== 'llm.delta' || 'id' in msg || typeof msg.requestId !== 'string') return;
|
|
9
|
-
const entry = llmDeltas.get(msg.requestId);
|
|
10
|
-
if (!entry || typeof msg.sequence !== 'number' || typeof msg.text !== 'string') return;
|
|
11
|
-
if (msg.sequence !== entry.next) { entry.next = Infinity; return; }
|
|
12
|
-
entry.next += 1;
|
|
13
|
-
if (entry.onDelta) entry.onDelta({ requestId: msg.requestId, sequence: msg.sequence, text: msg.text });
|
|
14
|
-
});
|
|
15
|
-
const llmRequest = (payload, id) => {
|
|
16
|
-
const type = payload.type;
|
|
17
|
-
return request(id === undefined ? payload : { ...payload, id }, type + '.result').then((message) => {
|
|
18
|
-
const field = llmFields[message.type];
|
|
19
|
-
const hasValue = message[field] !== undefined && message[field] !== null;
|
|
20
|
-
const hasError = message.error !== undefined && message.error !== null;
|
|
21
|
-
if (hasValue === hasError) throw new Error(type + '.result must carry exactly one of ' + field + ' or error');
|
|
22
|
-
if (hasError) {
|
|
23
|
-
const failure = new Error(String(message.error.message));
|
|
24
|
-
failure.name = 'LlmError';
|
|
25
|
-
failure.code = message.error.code;
|
|
26
|
-
throw failure;
|
|
27
|
-
}
|
|
28
|
-
return message[field];
|
|
29
|
-
});
|
|
30
|
-
};
|
|
31
|
-
napplet.llm = {
|
|
32
|
-
select: (requirements) => llmRequest(requirements === undefined ? { type: 'llm.select' } : { type: 'llm.select', requirements }),
|
|
33
|
-
describe: (handle) => llmRequest({ type: 'llm.describe', handle }),
|
|
34
|
-
generate: (generation, options) => {
|
|
35
|
-
const id = nextId();
|
|
36
|
-
const entry = { next: 0, onDelta: options && options.onDelta };
|
|
37
|
-
llmDeltas.set(id, entry);
|
|
38
|
-
const signal = options && options.signal;
|
|
39
|
-
const abort = () => { napplet.llm.cancel(id).catch(() => undefined); };
|
|
40
|
-
if (signal) { if (signal.aborted) abort(); else signal.addEventListener('abort', abort, { once: true }); }
|
|
41
|
-
const pendingGeneration = llmRequest({ type: 'llm.generate', request: generation }, id).finally(() => {
|
|
42
|
-
llmDeltas.delete(id);
|
|
43
|
-
if (signal) signal.removeEventListener('abort', abort);
|
|
44
|
-
});
|
|
45
|
-
return Object.assign(pendingGeneration, { requestId: id });
|
|
46
|
-
},
|
|
47
|
-
cancel: (requestId) => llmRequest({ type: 'llm.cancel', requestId }),
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
`,st="__nappletConformance.error",it="__nappletConformance.installed";function Mn(e){return new Promise(n=>setTimeout(n,e))}function Or(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}var Cr=`(() => {
|
|
51
|
-
const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
52
|
-
const numberIn = (value, min, max) => typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max;
|
|
53
|
-
const isGamepadState = (value) => {
|
|
54
|
-
if (!record(value) || typeof value.available !== 'boolean' || typeof value.focused !== 'boolean' || !Array.isArray(value.pads)) return false;
|
|
55
|
-
if (value.available) {
|
|
56
|
-
if (value.reason !== undefined) return false;
|
|
57
|
-
} else if (value.focused || (value.reason !== 'blocked' && value.reason !== 'unavailable')) return false;
|
|
58
|
-
return Array.from(value.pads).every((pad) => {
|
|
59
|
-
if (pad === null) return true;
|
|
60
|
-
if (!record(pad) || !Number.isInteger(pad.index) || pad.index < 0 || typeof pad.id !== 'string' || typeof pad.mapping !== 'string' || pad.connected !== true) return false;
|
|
61
|
-
if (typeof pad.timestamp !== 'number' || !Number.isFinite(pad.timestamp) || !Array.isArray(pad.axes) || !Array.isArray(pad.buttons)) return false;
|
|
62
|
-
if (!value.focused && pad.timestamp !== 0) return false;
|
|
63
|
-
if (!Array.from(pad.axes).every((axis) => numberIn(axis, -1, 1) && (value.focused || axis === 0))) return false;
|
|
64
|
-
return Array.from(pad.buttons).every((button) => record(button) && numberIn(button.value, 0, 1) && typeof button.pressed === 'boolean' && typeof button.touched === 'boolean' && (value.focused || (button.value === 0 && !button.pressed && !button.touched)));
|
|
65
|
-
});
|
|
66
|
-
};
|
|
67
|
-
const copyGamepadState = (state) => {
|
|
68
|
-
const copy = { available: state.available, focused: state.focused };
|
|
69
|
-
if (state.reason !== undefined) copy.reason = state.reason;
|
|
70
|
-
copy.pads = state.pads.map((pad) => pad === null ? null : {
|
|
71
|
-
index: pad.index, id: pad.id, mapping: pad.mapping, connected: pad.connected,
|
|
72
|
-
timestamp: pad.timestamp, axes: pad.axes.slice(), buttons: pad.buttons.map((button) => ({ value: button.value, pressed: button.pressed, touched: button.touched })),
|
|
73
|
-
});
|
|
74
|
-
return copy;
|
|
75
|
-
};
|
|
76
|
-
return { isGamepadState, copyGamepadState };
|
|
77
|
-
})()`;function Hr(){return`(() => {
|
|
1
|
+
(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))t(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&t(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function t(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();var $e=["shell","relay","identity","storage","inc","theme","keys","media","notify","config","resource","cvm","outbox","upload","intent","ble","webrtc","link","count","lists","serial","fs","common","dm","gamepad","llm"],Oe={shell:{proposal:{url:"https://github.com/napplet/naps/pull/101",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Optional readiness and environment binding has focused shim and reference-runtime coverage.",evidence:["packages/nap/src/shell/shim.test.ts"]},relay:{proposal:{url:"https://github.com/napplet/naps/pull/2",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Relay reads, publishing, and subscription lifecycle have maintained shim and integration tests; upstream naming remains under review.",evidence:["packages/nap/src/relay/shim.test.ts"],implementationReference:{revision:"cb8f8eabb2d09439e9d174cb9eb6ef2caad0eca1",evidence:".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md",scope:"RelayEventResult sidecar migration; subsequent changes are not covered."}},identity:{proposal:{url:"https://github.com/napplet/naps/pull/102",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Read-only identity queries and updates have focused binding and reference-runtime coverage.",evidence:["packages/nap/src/identity/shim.test.ts"]},storage:{proposal:{url:"https://github.com/napplet/naps/pull/3",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Key-value binding has focused request/result tests and tutorial usage; host storage isolation remains the host responsibility.",evidence:["packages/nap/src/storage/shim.test.ts"]},inc:{proposal:{url:"https://github.com/napplet/naps/pull/104",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Topic and channel bindings have compatibility tests and authenticated-endpoint reference-runtime coverage.",evidence:["packages/nap/src/inc/shim.ts","packages/conformance-cli/src/browser.test.ts"]},theme:{proposal:{url:"https://github.com/napplet/naps/pull/103",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Theme queries and pushed updates have focused binding and opaque-iframe integration coverage.",evidence:["packages/nap/src/theme/shim.test.ts","packages/conformance-cli/src/browser.test.ts"]},keys:{proposal:{url:"https://github.com/napplet/naps/pull/9",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Keyboard binding ships, but dedicated domain regression coverage is limited; retain explicit evaluation opt-in.",evidence:["packages/nap/src/keys/shim.ts"]},media:{proposal:{url:"https://github.com/napplet/naps/pull/10",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Session creation and playback binding have focused regression coverage; proposed torrent playback amendments are not implied.",evidence:["packages/nap/src/media/shim.test.ts"]},notify:{proposal:{url:"https://github.com/napplet/naps/pull/11",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Notification binding ships with limited dedicated domain regression evidence; broader host integration confidence is unverified.",evidence:["packages/nap/src/notify/shim.ts"]},config:{proposal:{url:"https://github.com/napplet/naps/pull/14",status:"draft",checkedAt:"2026-10-31"},maturity:"exploratory",rationale:"Configuration binding is tested, but the upstream draft is marked MAY DEFER; use for design exploration.",evidence:["packages/nap/src/config/shim.test.ts"]},resource:{proposal:{url:"https://github.com/napplet/naps/pull/80",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Resource fetching has focused shim and type tests; the reverted merge and reopened proposal do not change that implementation assessment.",evidence:["packages/nap/src/resource/shim.test.ts"],implementationReference:{revision:"8e75eadf317d7fe809415e4755cd48f63cfb63f3",evidence:".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md",scope:"Shared ResourceSidecarEntry types during the sidecar migration; subsequent resource changes are not covered."}},cvm:{proposal:{url:"https://github.com/napplet/naps/pull/31",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Session and registry bindings are tested; upstream explicitly marks the contract NEEDS WORK.",evidence:["packages/nap/src/cvm/shim.test.ts"]},outbox:{proposal:{url:"https://github.com/napplet/naps/pull/32",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Routing and subscription bindings have focused tests and an integration regression for structured-clone boundaries.",evidence:["packages/nap/src/outbox/shim.test.ts","packages/nap/src/boundary-integration.test.ts"],implementationReference:{revision:"57db924bac022cc14c67d9fca1a4d92cf1bd4725",evidence:".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md",scope:"RelayEventResult and stream lifecycle migration; subsequent changes are not covered."}},upload:{proposal:{url:"https://github.com/napplet/naps/pull/33",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Upload binding has focused tests for request/result behavior; host rail support remains runtime-specific.",evidence:["packages/nap/src/upload/shim.test.ts"]},intent:{proposal:{url:"https://github.com/napplet/naps/pull/91",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Convention normalization and dispatch have focused binding and reference-runtime integration tests.",evidence:["packages/nap/src/intent/shim.test.ts"]},ble:{proposal:{url:"https://github.com/napplet/naps/pull/62",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"GATT binding has unit coverage; real-device behavior across host backends is not established by these tests.",evidence:["packages/nap/src/ble/shim.test.ts"]},webrtc:{proposal:{url:"https://github.com/napplet/naps/pull/59",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Signaling and session binding have unit coverage; interoperable live peer sessions remain unverified here.",evidence:["packages/nap/src/webrtc/shim.test.ts"]},link:{proposal:{url:"https://github.com/napplet/naps/pull/53",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"The small link-opening binding has focused regression coverage; navigation authorization stays with the host.",evidence:["packages/nap/src/link/shim.test.ts"]},count:{proposal:{url:"https://github.com/napplet/naps/pull/69",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Count binding is tested, but accuracy and aggregation across real relay backends remain outside that evidence.",evidence:["packages/nap/src/count/shim.test.ts"]},lists:{proposal:{url:"https://github.com/napplet/naps/pull/68",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"List mutation binding is tested; concurrent real-host mutation behavior is not established by binding tests.",evidence:["packages/nap/src/lists/shim.test.ts"]},serial:{proposal:{url:"https://github.com/napplet/naps/pull/61",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Serial binding has unit coverage; device and native-host integration evidence is limited.",evidence:["packages/nap/src/serial/shim.test.ts"]},fs:{proposal:{url:"https://github.com/napplet/naps/pull/88",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Filesystem binding has MVP coverage; portability and authorization across storage backends remain under evaluation.",evidence:["packages/nap/src/fs/shim.test.ts"]},common:{proposal:{url:"https://github.com/napplet/naps/pull/67",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Social action binding is tested; broader host integration and evolving action semantics warrant explicit opt-in.",evidence:["packages/nap/src/common/shim.test.ts"]},dm:{proposal:{url:"https://github.com/napplet/naps/pull/74",status:"draft",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Direct-message binding has shim and type coverage; transport interoperability is not established by those tests.",evidence:["packages/nap/src/dm/shim.test.ts"]},gamepad:{proposal:{url:"https://github.com/napplet/naps/pull/130",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Cross-repository delivery includes binding, security, runtime, and conformance verification; the reopened proposal is still subject to change.",evidence:["packages/nap/src/gamepad/shim.test.ts",".planning/phases/163-nap-gamepad-across-repositories/163-VERIFICATION.md"],implementationReference:{revision:"0b28f77e3dfa0f07dd7c0f9d61a7090ee99f3a5e",evidence:".planning/phases/163-nap-gamepad-across-repositories/163-SECURITY.md",scope:"Phase 163 binding, runtime isolation, and conformance verification."}},llm:{proposal:{url:"https://github.com/napplet/naps/pull/134",status:"draft",checkedAt:"2026-10-31"},maturity:"exploratory",rationale:"Early published draft has binding and mock-runtime tests; provider behavior and API design remain exploratory.",evidence:["packages/nap/src/llm/shim.test.ts","packages/conformance-cli/src/browser.test.ts"]}};for(const e of Object.values(Oe))Object.freeze(e.proposal),Object.freeze(e.evidence),e.implementationReference&&Object.freeze(e.implementationReference),Object.freeze(e);Object.freeze(Oe);function Dt(e){return Object.hasOwn(Oe,e)?Oe[e]:void 0}function Bt(e){const n=new Set(e.allowedMaturities??["supported"]),s=new Set(e.optIn??[]),t=[],r=[];for(const i of new Set(e.candidates)){const o=Dt(i);o?!o.maturity||!["supported","experimental","exploratory"].includes(o.maturity)?r.push({domain:i,reason:"unclassified"}):n.has(o.maturity)||s.has(i)?t.push(i):r.push({domain:i,reason:"maturity-not-allowed",maturity:o.maturity}):r.push({domain:i,reason:"unknown-domain"})}return{domains:t,excluded:r}}var u={id:"string"},Lt={"llm.select":{dir:"out",fields:{...u}},"llm.select.result":{dir:"in",fields:{...u}},"llm.describe":{dir:"out",fields:{...u,handle:"string"}},"llm.describe.result":{dir:"in",fields:{...u}},"llm.generate":{dir:"out",fields:{...u,request:"object"}},"llm.generate.result":{dir:"in",fields:{...u}},"llm.delta":{dir:"in",fields:{requestId:"string",sequence:"number",text:"string"}},"llm.cancel":{dir:"out",fields:{...u,requestId:"string"}},"llm.cancel.result":{dir:"in",fields:{...u}},"gamepad.subscribe":{dir:"out",forbiddenFields:["id"],forbiddenReason:"NAP-GAMEPAD fire-and-forget envelopes do not carry it"},"gamepad.unsubscribe":{dir:"out",forbiddenFields:["id"],forbiddenReason:"NAP-GAMEPAD fire-and-forget envelopes do not carry it"},"gamepad.state":{dir:"in",fields:{available:"boolean",focused:"boolean",pads:"array"}},"shell.ready":{dir:"out"},"shell.init":{dir:"in",fields:{capabilities:"object",services:"array"}},"relay.subscribe":{dir:"out",fields:{...u,subId:"string",filters:"array"}},"relay.close":{dir:"out",fields:{...u,subId:"string"}},"relay.publish":{dir:"out",fields:{...u,event:"object"}},"relay.publishEncrypted":{dir:"out",fields:{...u,event:"object",recipient:"string"}},"relay.query":{dir:"out",fields:{...u,filters:"array"}},"relay.event":{dir:"in"},"relay.eose":{dir:"in"},"relay.closed":{dir:"in"},"relay.publish.result":{dir:"in"},"relay.publishEncrypted.result":{dir:"in"},"relay.query.result":{dir:"in"},"identity.getPublicKey":{dir:"out",fields:{...u}},"identity.getRelays":{dir:"out",fields:{...u}},"identity.getProfile":{dir:"out",fields:{...u}},"identity.getFollows":{dir:"out",fields:{...u}},"identity.getList":{dir:"out",fields:{...u,listType:"string"}},"identity.getZaps":{dir:"out",fields:{...u}},"identity.getMutes":{dir:"out",fields:{...u}},"identity.getBlocked":{dir:"out",fields:{...u}},"identity.getBadges":{dir:"out",fields:{...u}},"identity.changed":{dir:"in"},"identity.getPublicKey.result":{dir:"in"},"identity.getRelays.result":{dir:"in"},"identity.getProfile.result":{dir:"in"},"identity.getFollows.result":{dir:"in"},"identity.getList.result":{dir:"in"},"identity.getZaps.result":{dir:"in"},"identity.getMutes.result":{dir:"in"},"identity.getBlocked.result":{dir:"in"},"identity.getBadges.result":{dir:"in"},"storage.get":{dir:"out",fields:{...u,key:"string"}},"storage.set":{dir:"out",fields:{...u,key:"string",value:"string"}},"storage.remove":{dir:"out",fields:{...u,key:"string"}},"storage.keys":{dir:"out",fields:{...u}},"storage.get.result":{dir:"in"},"storage.set.result":{dir:"in"},"storage.remove.result":{dir:"in"},"storage.keys.result":{dir:"in"},"inc.emit":{dir:"out",fields:{topic:"string"},forbiddenFields:["sender"]},"inc.subscribe":{dir:"out",fields:{...u,topic:"string"}},"inc.unsubscribe":{dir:"out",fields:{topic:"string"}},"inc.channel.open":{dir:"out",fields:{...u,target:"string"}},"inc.channel.emit":{dir:"out",fields:{channelId:"string"}},"inc.channel.broadcast":{dir:"out"},"inc.channel.list":{dir:"out",fields:{...u}},"inc.channel.close":{dir:"out",fields:{channelId:"string"}},"inc.subscribe.result":{dir:"in"},"inc.event":{dir:"in",fields:{topic:"string",sender:"string"}},"inc.channel.open.result":{dir:"in"},"inc.channel.opened":{dir:"in",fields:{channelId:"string",peer:"string"}},"inc.channel.event":{dir:"in"},"inc.channel.list.result":{dir:"in"},"inc.channel.closed":{dir:"in"},"theme.get":{dir:"out",fields:{...u}},"theme.get.result":{dir:"in"},"theme.changed":{dir:"in"},"keys.forward":{dir:"out",fields:{key:"string",code:"string",ctrl:"boolean",alt:"boolean",shift:"boolean",meta:"boolean"}},"keys.registerAction":{dir:"out",fields:{...u,action:"object"}},"keys.unregisterAction":{dir:"out",fields:{actionId:"string"}},"keys.registerAction.result":{dir:"in"},"keys.bindings":{dir:"in"},"keys.action":{dir:"in"},"media.session.create":{dir:"out",fields:{...u,owner:"object"}},"media.session.update":{dir:"out",fields:{sessionId:"string",metadata:"object"}},"media.session.destroy":{dir:"out",fields:{sessionId:"string"}},"media.state":{dir:"out",fields:{sessionId:"string",status:"string"}},"media.capabilities":{dir:"out",fields:{sessionId:"string",actions:"array"}},"media.session.create.result":{dir:"in"},"media.command":{dir:"in"},"media.controls":{dir:"in"},"notify.send":{dir:"out",fields:{...u,title:"string"}},"notify.dismiss":{dir:"out",fields:{notificationId:"string"}},"notify.badge":{dir:"out",fields:{count:"number"}},"notify.channel.register":{dir:"out",fields:{channelId:"string",label:"string"}},"notify.permission.request":{dir:"out",fields:{...u}},"notify.send.result":{dir:"in"},"notify.permission.result":{dir:"in"},"notify.action":{dir:"in"},"notify.clicked":{dir:"in"},"notify.dismissed":{dir:"in"},"notify.controls":{dir:"in"},"config.registerSchema":{dir:"out",fields:{...u,schema:"object"}},"config.get":{dir:"out",fields:{...u}},"config.subscribe":{dir:"out"},"config.unsubscribe":{dir:"out"},"config.openSettings":{dir:"out"},"config.registerSchema.result":{dir:"in"},"config.values":{dir:"in"},"config.schemaError":{dir:"in"},"resource.info":{dir:"out",fields:{...u}},"resource.bytes":{dir:"out",fields:{...u,url:"string"}},"resource.bytesMany":{dir:"out",fields:{...u,requests:"array"}},"resource.cancel":{dir:"out",fields:{...u}},"resource.info.result":{dir:"in"},"resource.info.error":{dir:"in"},"resource.bytes.result":{dir:"in"},"resource.bytes.error":{dir:"in"},"resource.bytesMany.result":{dir:"in"},"resource.bytesMany.error":{dir:"in"},"cvm.discover":{dir:"out",fields:{...u}},"cvm.request":{dir:"out",fields:{...u,server:"object",message:"object"}},"cvm.close":{dir:"out",fields:{...u,server:"object"}},"cvm.registry.list":{dir:"out",fields:{...u}},"cvm.registry.has":{dir:"out",fields:{...u,family:"string"}},"cvm.registry.describe":{dir:"out",fields:{...u,family:"string"}},"cvm.registry.call":{dir:"out",fields:{...u,family:"string",tool:"string"}},"cvm.discover.result":{dir:"in"},"cvm.request.result":{dir:"in"},"cvm.close.result":{dir:"in"},"cvm.event":{dir:"in"},"cvm.registry.list.result":{dir:"in"},"cvm.registry.has.result":{dir:"in"},"cvm.registry.describe.result":{dir:"in"},"cvm.registry.call.result":{dir:"in"},"outbox.getEvent":{dir:"out",fields:{...u,eventId:"string"}},"outbox.query":{dir:"out",fields:{...u,filters:"present"}},"outbox.subscribe":{dir:"out",fields:{...u,subId:"string",filters:"present"}},"outbox.close":{dir:"out",fields:{...u,subId:"string"}},"outbox.publish":{dir:"out",fields:{...u,event:"object"}},"outbox.resolveRelays":{dir:"out",fields:{...u,target:"present"}},"outbox.getEvent.result":{dir:"in"},"outbox.query.result":{dir:"in"},"outbox.event":{dir:"in"},"outbox.closed":{dir:"in"},"outbox.publish.result":{dir:"in"},"outbox.resolveRelays.result":{dir:"in"},"upload.info":{dir:"out",fields:{...u}},"upload.upload":{dir:"out",fields:{...u,request:"object"}},"upload.status":{dir:"out",fields:{...u,uploadId:"string"}},"upload.info.result":{dir:"in"},"upload.upload.result":{dir:"in"},"upload.status.result":{dir:"in"},"upload.status.changed":{dir:"in"},"intent.invoke":{dir:"out",fields:{...u,request:"object"}},"intent.available":{dir:"out",fields:{...u,archetype:"string"}},"intent.handlers":{dir:"out",fields:{...u}},"intent.invoke.result":{dir:"in",fields:{...u,result:"object"}},"intent.available.result":{dir:"in"},"intent.handlers.result":{dir:"in"},"intent.deliver":{dir:"in",fields:{delivery:"object"}},"intent.changed":{dir:"in"},"ble.open":{dir:"out",fields:{...u,request:"object"}},"ble.services":{dir:"out",fields:{...u,sessionId:"string"}},"ble.read":{dir:"out",fields:{...u,sessionId:"string",target:"object"}},"ble.write":{dir:"out",fields:{...u,sessionId:"string",target:"object",data:"array"}},"ble.subscribe":{dir:"out",fields:{...u,sessionId:"string",target:"object"}},"ble.unsubscribe":{dir:"out",fields:{...u,sessionId:"string",target:"object"}},"ble.close":{dir:"out",fields:{...u,sessionId:"string"}},"ble.open.result":{dir:"in"},"ble.services.result":{dir:"in"},"ble.read.result":{dir:"in"},"ble.write.result":{dir:"in"},"ble.subscribe.result":{dir:"in"},"ble.unsubscribe.result":{dir:"in"},"ble.close.result":{dir:"in"},"ble.event":{dir:"in"},"common.encodeNip19":{dir:"out",fields:{...u,input:"object"}},"common.decodeNip19":{dir:"out",fields:{...u,value:"string"}},"common.getProfile":{dir:"out",fields:{...u,target:"string"}},"common.follows":{dir:"out",fields:{...u}},"common.follow":{dir:"out",fields:{...u,pubkeys:"array"}},"common.unfollow":{dir:"out",fields:{...u,pubkeys:"array"}},"common.react":{dir:"out",fields:{...u,targetEventId:"string",reaction:"string"}},"common.report":{dir:"out",fields:{...u,target:"object",reason:"string",text:"string"}},"common.encodeNip19.result":{dir:"in"},"common.decodeNip19.result":{dir:"in"},"common.getProfile.result":{dir:"in"},"common.follows.result":{dir:"in"},"common.follow.result":{dir:"in"},"common.unfollow.result":{dir:"in"},"common.react.result":{dir:"in"},"common.report.result":{dir:"in"},"webrtc.open":{dir:"out",fields:{...u,request:"object"}},"webrtc.send":{dir:"out",fields:{...u,sessionId:"string",payload:"present"}},"webrtc.close":{dir:"out",fields:{...u,sessionId:"string"}},"webrtc.open.result":{dir:"in"},"webrtc.send.result":{dir:"in"},"webrtc.close.result":{dir:"in"},"webrtc.event":{dir:"in"},"link.open":{dir:"out",fields:{...u,url:"string"}},"link.open.result":{dir:"in"},"count.query":{dir:"out",fields:{...u,filters:"array"}},"count.query.result":{dir:"in"},"lists.supported":{dir:"out",fields:{...u}},"lists.add":{dir:"out",fields:{...u,list:"object",items:"array"}},"lists.remove":{dir:"out",fields:{...u,list:"object",items:"array"}},"lists.supported.result":{dir:"in"},"lists.add.result":{dir:"in"},"lists.remove.result":{dir:"in"},"serial.open":{dir:"out",fields:{...u,request:"object"}},"serial.write":{dir:"out",fields:{...u,sessionId:"string",data:"array"}},"serial.close":{dir:"out",fields:{...u,sessionId:"string"}},"serial.open.result":{dir:"in"},"serial.write.result":{dir:"in"},"serial.close.result":{dir:"in"},"serial.event":{dir:"in"},"fs.info":{dir:"out",fields:{...u}},"fs.pickFile":{dir:"out",fields:{...u}},"fs.pickFiles":{dir:"out",fields:{...u}},"fs.pickDirectory":{dir:"out",fields:{...u}},"fs.pickSaveFile":{dir:"out",fields:{...u}},"fs.stat":{dir:"out",fields:{...u,path:"string"}},"fs.list":{dir:"out",fields:{...u,path:"string"}},"fs.read":{dir:"out",fields:{...u,path:"string"}},"fs.write":{dir:"out",fields:{...u,path:"string",data:"string"}},"fs.mkdir":{dir:"out",fields:{...u,path:"string"}},"fs.remove":{dir:"out",fields:{...u,path:"string"}},"fs.move":{dir:"out",fields:{...u,fromPath:"string",toPath:"string"}},"fs.watch":{dir:"out",fields:{...u,path:"string"}},"fs.unwatch":{dir:"out",fields:{...u,watchId:"string"}},"fs.info.result":{dir:"in"},"fs.pickFile.result":{dir:"in"},"fs.pickFiles.result":{dir:"in"},"fs.pickDirectory.result":{dir:"in"},"fs.pickSaveFile.result":{dir:"in"},"fs.stat.result":{dir:"in"},"fs.list.result":{dir:"in"},"fs.read.result":{dir:"in"},"fs.write.result":{dir:"in"},"fs.mkdir.result":{dir:"in"},"fs.remove.result":{dir:"in"},"fs.move.result":{dir:"in"},"fs.watch.result":{dir:"in"},"fs.unwatch.result":{dir:"in"},"fs.changed":{dir:"in"},"dm.status":{dir:"out",fields:{...u}},"dm.conversations":{dir:"out",fields:{...u}},"dm.messages":{dir:"out",fields:{...u,conversationId:"string"}},"dm.send":{dir:"out",fields:{...u,recipients:"array",content:"string"}},"dm.subscribe":{dir:"out",fields:{...u}},"dm.unsubscribe":{dir:"out",fields:{...u,subscriptionId:"string"}},"dm.status.result":{dir:"in"},"dm.conversations.result":{dir:"in"},"dm.messages.result":{dir:"in"},"dm.send.result":{dir:"in"},"dm.subscribe.result":{dir:"in"},"dm.unsubscribe.result":{dir:"in"},"dm.message":{dir:"in"}},$t=e=>typeof e=="string",we=e=>typeof e=="string"&&e.length>0,kn=e=>typeof e=="boolean",Ee=(...e)=>n=>typeof n=="string"&&e.includes(n),Ft=e=>typeof e=="string"&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)&&e.length>=4;function Te(e,n={}){return s=>{if(typeof s!="object"||s===null||Array.isArray(s))return!1;const t=s;return Object.keys(t).some(r=>!(r in e)&&!(r in n))?!1:Object.entries(e).every(([r,i])=>i(t[r]))&&Object.entries(n).every(([r,i])=>t[r]===void 0||i(t[r]))}}var Kn=e=>n=>Array.isArray(n)&&n.length>0&&n.every(e),Wt=Te({type:Ee("text"),text:$t}),zt=Te({type:Ee("image"),mimeType:Ee("image/png","image/jpeg","image/webp"),data:Ft}),Gt=e=>Wt(e)||zt(e),Vt=Te({role:Ee("system","user","assistant"),content:Kn(Gt)}),Qt=Te({},{model:we,images:kn,json:kn}),Kt=Te({handle:we,messages:Kn(Vt)},{format:Ee("text","json")}),Yt={"llm.select":{optional:{requirements:Qt}},"llm.describe":{required:{handle:we}},"llm.generate":{required:{request:Kt}},"llm.cancel":{required:{requestId:we}}};function Zt(e,n,s){const t=Yt[e];if(!t)return;const r=t.required??{},i=t.optional??{};n.id!==void 0&&!we(n.id)&&s.push({code:"wrong-type",field:"id",message:"NAP-LLM request ids are non-empty text"});for(const o of Object.keys(n))o==="type"||o==="id"||o in r||o in i||s.push({code:"forbidden-field",field:o,message:`Field "${o}" is not a parameter of ${e}; NAP-LLM requests carry exactly their API row parameters`});for(const[o,l]of Object.entries({...r,...i})){const a=n[o];if(a===void 0){o in r&&s.push({code:"missing-field",field:o,message:`Field "${o}" is required by ${e}`});continue}l(a)||s.push({code:"wrong-type",field:o,message:`Field "${o}" must match the NAP-LLM ${e} schema`})}}function Fe(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return"array";const n=typeof e;return n==="string"||n==="number"||n==="boolean"?n:n==="object"?"object":"present"}function Xt(e,n){return n==="present"?e!=null:Fe(e)===n}function Jt(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return;const s=e;typeof s.archetype!="string"&&n.push({code:s.archetype===void 0?"missing-field":"wrong-type",message:'Intent request requires a string "archetype" field',field:"request.archetype"});for(const r of["action","convention"])typeof s[r]!="string"&&n.push({code:s[r]===void 0?"missing-field":"wrong-type",message:`Intent request field "${r}" must be a string`,field:`request.${r}`});const t=typeof s.convention=="string"?/^napplet:([^/?#]+)\/([^/?#]+)$/.exec(s.convention):null;(!t||t[1]!==s.archetype||t[2]!==s.action)&&n.push({code:"wrong-type",message:"Intent convention must be stable and match archetype and action",field:"request.convention"}),s.handler!==void 0&&typeof s.handler!="string"&&n.push({code:"wrong-type",message:'Intent request field "handler" must be a string',field:"request.handler"}),s.behavior!==void 0&&Fe(s.behavior)!=="object"&&n.push({code:"wrong-type",message:'Intent request field "behavior" must be an object',field:"request.behavior"}),s.handlerHint!==void 0&&es(s.handlerHint,n),"sender"in s&&n.push({code:"forbidden-field",message:"Intent request does not define a caller-supplied sender field",field:"request.sender"})}function es(e,n){if(Fe(e)!=="object"){n.push({code:"wrong-type",message:'Intent request field "handlerHint" must be an object',field:"request.handlerHint"});return}const{address:s,relays:t}=e;(typeof s!="string"||!/^35129:[0-9a-f]{64}:.+$/s.test(s))&&n.push({code:s===void 0?"missing-field":"wrong-type",message:'Intent handler hint "address" must be a 35129:<pubkey>:<d> coordinate',field:"request.handlerHint.address"}),t!==void 0&&!(Array.isArray(t)&&t.every(r=>typeof r=="string"))&&n.push({code:"wrong-type",message:'Intent handler hint "relays" must be an array of strings',field:"request.handlerHint.relays"})}function Yn(e,n,s){Array.isArray(e)&&e.every(t=>typeof t=="string")||s.push({code:"wrong-type",message:`Field "${n}" must be an array of strings`,field:n})}function ns(e,n){e.servers!==void 0&&Yn(e.servers,"servers",n)}function ts(e,n){if(Array.isArray(e)){if(e.length===0){n.push({code:"invalid-resource-request",message:'Field "requests" must contain at least one resource request',field:"requests"});return}for(const[s,t]of e.entries()){const r=`requests[${s}]`;if(typeof t!="object"||t===null||Array.isArray(t)){n.push({code:"invalid-resource-request",message:`Field "${r}" must be a resource request object`,field:r});continue}const i=t;typeof i.url!="string"&&n.push({code:i.url===void 0?"missing-field":"wrong-type",message:`Field "${r}.url" must be a string`,field:`${r}.url`}),i.servers!==void 0&&Yn(i.servers,`${r}.servers`,n)}}}function ss(e){const n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{ok:!1,errors:[{code:"not-an-object",message:"Envelope must be a non-null object"}]};const s=e,t=s.type;if(typeof t!="string")return{ok:!1,errors:[{code:"missing-type",message:"Envelope is missing a string `type` field"}]};const r=t.indexOf(".");if(r<=0)return{ok:!1,type:t,errors:[{code:"malformed-type",message:`Envelope type "${t}" is not in domain.action form`}]};const i=t.slice(0,r);if(!$e.includes(i))return{ok:!1,type:t,domain:i,errors:[{code:"unknown-domain",message:`"${i}" is not a known NAP domain`}]};const l=Lt[t];if(!l)return{ok:!1,type:t,domain:i,errors:[{code:"unknown-type",message:`"${t}" is not a known ${i} message type`}]};for(const[a,c]of Object.entries(l.fields??{})){if(!(a in s)||s[a]===void 0){n.push({code:"missing-field",message:`Required field "${a}" is missing`,field:a});continue}Xt(s[a],c)||n.push({code:"wrong-type",message:`Field "${a}" should be ${c} but is ${Fe(s[a])}`,field:a})}if(l.dir==="in")return{ok:!1,type:t,domain:i,direction:"in",errors:[{code:"inbound-type-emitted",message:`"${t}" is a shell→napplet message; a napplet must not emit it`},...n]};for(const a of l.forbiddenFields??[])a in s&&n.push({code:"forbidden-field",message:`Field "${a}" cannot be emitted by a napplet: ${l.forbiddenReason??"it must be runtime-derived"}`,field:a});return i==="llm"&&Zt(t,s,n),t==="intent.invoke"&&Jt(s.request,n),t==="resource.bytes"&&ns(s,n),t==="resource.bytesMany"&&ts(s.requests,n),{ok:n.length===0,type:t,domain:i,direction:"out",errors:n}}var Zn=5129,rs=15129,ce=35129,hn=[Zn,rs,ce],Xn=["image/png","image/jpeg","image/webp"],Jn=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function et(e,n){return e.tags.find(s=>s[0]===n)}function is(e){return hn.includes(e)}function We(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function nt(e){return et(e,"d")?.[1]||void 0}function os(e){return e.tags.filter(n=>n[0]==="R").map(n=>n[1]?.trim()??"").filter(Boolean)}function tt(e){return nt(e)??et(e,"title")?.[1]??e.id}function as(e){const n=[],s=[];for(const i of e.tags.filter(o=>o[0]==="screenshot")){const o=In(i,n);o&&s.push(o)}const t=e.tags.filter(i=>i[0]==="preview");let r;return t.length>1?n.push({code:"invalid-presentation-media",message:"Multiple preview tags; clients ignore the preview (NIP-5D §Presentation media)"}):t.length===1&&(r=In(t[0],n)),{screenshots:s,preview:r,warnings:n}}function In(e,n){const s=e[0],t=d=>{n.push({code:"invalid-presentation-media",message:`Ignore ${s} tag: ${d} (NIP-5D §Presentation media)`})},r=new Map;for(const d of e.slice(1)){const f=typeof d=="string"?d.indexOf(" "):-1,y=f<0?d:d.slice(0,f),w=f<0?void 0:d.slice(f+1),A=r.get(y)??[];w!==void 0?A.push(w):A.push(""),r.set(y,A)}const i=r.get("x");if(!i||i.length!==1||!We(i[0]))return t("exactly one x field with a lowercase sha256 is required");const o={sha256:i[0]},l=(d,f)=>{const y=r.get(d);if(y){if(y.length!==1||!f(y[0])){n.push({code:"invalid-presentation-media",message:`Ignore ${d} field on ${s} ${o.sha256}: malformed or repeated (NIP-5D §Presentation media)`});return}return y[0]}},a=l("m",d=>Jn.test(d));if(a!==void 0){if(!(s==="preview"?a.toLowerCase().startsWith("video/"):Xn.includes(a.toLowerCase())))return t(`${a} cannot match a decodable ${s==="preview"?"video":"PNG, JPEG or WebP"} format`);o.mimeType=a}const c=l("dim",d=>/^[1-9][0-9]*x[1-9][0-9]*$/.test(d));if(c!==void 0){const[d,f]=c.split("x").map(Number);o.dim={width:d,height:f}}const h=l("size",d=>/^(?:0|[1-9][0-9]*)$/.test(d));if(h!==void 0&&(o.size=Number(h)),s==="preview"){const d=l("duration",f=>/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/.test(f));d!==void 0&&(o.duration=Number(d))}const p=l("alt",d=>d.trim().length>0);return p!==void 0&&(o.alt=p),o}function ze(e){const n=[],s=[];if(!e)return{ok:!1,requires:[],optional:[],errors:[{code:"missing-manifest-event",message:"No NIP-5D manifest event was resolved"}],warnings:s};const t=nt(e),r=os(e);is(e.kind)||n.push({code:"invalid-napplet-kind",message:`Manifest event kind ${e.kind} is not a NIP-5D napplet kind`});const i=e.tags.filter(l=>l[0]==="d");e.kind===ce&&(i.length!==1||!t)?n.push({code:"missing-d-tag",message:"Named manifests require exactly one non-empty d tag"}):e.kind!==ce&&i.length>0&&n.push({code:"unexpected-d-tag",message:"Only named manifests carry a d tag"});const o=e.tags.filter(l=>l[0]==="x");return(o.length!==1||o[0].length!==2||!We(o[0][1]))&&n.push({code:"invalid-artifact-hash",message:"Manifest requires exactly one x tag with the lowercase sha256 of /index.html"}),(typeof e.content!="string"||!e.content.trim())&&n.push({code:"missing-description",message:"Manifest content must contain a non-empty plain-text description"}),ls(e,n,s),ds(e,n,s),{ok:n.length===0,kind:e.kind,dTag:t,requires:r,optional:e.tags.filter(l=>l[0]==="O").map(l=>l[1]).filter(Boolean),errors:n,warnings:s}}function ls(e,n,s){for(const t of e.tags.filter(r=>r[0]==="R"||r[0]==="O")){const r=t[1];t.length!==2||!r||/[.:\s]/.test(r)||r.startsWith("NAP-")?n.push({code:t[0]==="R"?"invalid-required-nap":"invalid-optional-nap",message:`${t[0]} must name one bare NAP domain`}):$e.includes(r)||s.push({code:"unknown-required-nap",message:`Domain "${r}" is not in this tool's registry; check its NAP and runtime availability`})}}function ds(e,n,s){for(const i of["title","source","a","A"]){const o=e.tags.filter(l=>l[0]===i);(o.length>1||o.length&&(i==="a"||i==="A")&&e.kind!==Zn)&&n.push({code:"invalid-metadata",message:`Invalid ${i} tag cardinality for kind ${e.kind}`})}const t=e.tags.filter(i=>i[0]==="source");for(const i of t)(i.length!==2||!xn(i[1]))&&n.push({code:"invalid-metadata",message:"source must contain one HTTP(S), SSH, Git, SCP, or nostr repository location"});cs(e,t.length===1&&t[0].length===2&&xn(t[0][1]),n,s);for(const i of e.tags.filter(o=>o[0]==="i"))(!i[1]?.trim()||i[1].includes("?"))&&n.push({code:"invalid-metadata",message:"Intent advertisements must be non-empty queryless identities"});const r=e.tags.filter(i=>i[0]==="icon");(r.length>1||r.some(i=>i.length!==3||!We(i[1])||!Xn.includes(i[2])))&&s.push({code:"invalid-icon",message:"Ignore invalid icon metadata and use generic artwork (NIP-5D §Icon)"}),s.push(...as(e).warnings)}function cs(e,n,s,t){const r=e.tags.filter(o=>o[0]==="source-commit");r.length>1||r.some(o=>o.length!==2||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(o[1]))?s.push({code:"invalid-metadata",message:"source-commit must appear once with a full lowercase-hex Git commit ID (40 or 64 characters)"}):r.length===1&&!n&&t.push({code:"unused-source-commit",message:"source-commit without a Git repository source is ignored (NIP-5D §Source)"});const i=e.tags.filter(o=>o[0]==="source-archive");(i.length>1||i.some(o=>o.length!==4||!us(o[1])||!We(o[2])||!Jn.test(o[3]??"")))&&s.push({code:"invalid-metadata",message:"source-archive must appear once with an HTTPS URL without credentials or fragment, a lowercase sha256, and a MIME type"})}function us(e){if(!e||e.includes("#"))return!1;try{const n=new URL(e);return n.protocol==="https:"&&!n.username&&!n.password}catch{return!1}}function xn(e){if(!e||/^[a-z]:[\\/]/i.test(e))return!1;try{const{protocol:n}=new URL(e);if(["http:","https:","ssh:","git:"].includes(n))return!0;if(n==="nostr:")return e.length>8&&e.startsWith("nostr://");if(n==="file:")return!1}catch{}return!e.includes("://")&&/^(?:[^@\s/:]+@)?[^:\s/]+:[^\s]+$/.test(e)}var de="f".repeat(64),ps={id:"reference-source-endpoint",catalogId:"reference-source"},ms="https://reference.invalid/blob",fs=`named:${de}:reference-handler`,gs={kind:35129,pubkey:de,id:"0".repeat(64),tags:[["d","reference-handler"],["z","note"],["i","napplet:note/open","event"]]},hs="reference-subscriber",ys="napplet:note/open";function xe(e,n,s){return m({type:e,id:n,result:{entries:[s]}})}var m=e=>[e],j=()=>[];function Mn(e){if(typeof e!="string"||!e.startsWith("data:"))return null;const n=e.indexOf(",");if(n<0)return{blob:new Blob([],{type:"text/plain"}),mime:"text/plain"};const s=e.slice(5,n),t=e.slice(n+1),r=s.split(";").filter(Boolean),i=r.includes("base64"),o=r.find(l=>l.includes("/"))??"text/plain";try{if(i){const l=globalThis.atob(t),a=Uint8Array.from(l,c=>c.charCodeAt(0));return{blob:new Blob([a],{type:o}),mime:o}}return{blob:new Blob([decodeURIComponent(t)],{type:o}),mime:o}}catch{return null}}var bs={"gamepad.subscribe":()=>m({type:"gamepad.state",available:!1,reason:"unavailable",focused:!1,pads:[]}),"gamepad.unsubscribe":j,"relay.subscribe":e=>m({type:"relay.eose",subId:e.subId}),"relay.close":j,"relay.publish":e=>m({type:"relay.publish.result",id:e.id,ok:!0,event:e.event}),"relay.publishEncrypted":e=>m({type:"relay.publishEncrypted.result",id:e.id,ok:!0,event:e.event}),"relay.query":e=>m({type:"relay.query.result",id:e.id,events:[]}),"identity.getPublicKey":e=>m({type:"identity.getPublicKey.result",id:e.id,pubkey:de}),"identity.getRelays":e=>m({type:"identity.getRelays.result",id:e.id,relays:{}}),"identity.getProfile":e=>m({type:"identity.getProfile.result",id:e.id,profile:null}),"identity.getFollows":e=>m({type:"identity.getFollows.result",id:e.id,pubkeys:[]}),"identity.getList":e=>m({type:"identity.getList.result",id:e.id,entries:[]}),"identity.getZaps":e=>m({type:"identity.getZaps.result",id:e.id,zaps:[]}),"identity.getMutes":e=>m({type:"identity.getMutes.result",id:e.id,pubkeys:[]}),"identity.getBlocked":e=>m({type:"identity.getBlocked.result",id:e.id,pubkeys:[]}),"identity.getBadges":e=>m({type:"identity.getBadges.result",id:e.id,badges:[]}),"storage.get":e=>m({type:"storage.get.result",id:e.id,value:null}),"storage.set":e=>m({type:"storage.set.result",id:e.id}),"storage.remove":e=>m({type:"storage.remove.result",id:e.id}),"storage.keys":e=>m({type:"storage.keys.result",id:e.id,keys:[]}),"inc.emit":j,"inc.subscribe":e=>m({type:"inc.subscribe.result",id:e.id}),"inc.unsubscribe":j,"inc.channel.open":e=>m({type:"inc.channel.open.result",id:e.id,channelId:`chan-${String(e.id)}`,peer:"reference-peer"}),"inc.channel.emit":j,"inc.channel.broadcast":j,"inc.channel.list":e=>m({type:"inc.channel.list.result",id:e.id,channels:[]}),"inc.channel.close":j,"theme.get":e=>m({type:"theme.get.result",id:e.id,theme:{colors:{background:"#000000",text:"#ffffff",primary:"#663399"}}}),"keys.forward":j,"keys.registerAction":e=>m({type:"keys.registerAction.result",id:e.id,actionId:`action-${String(e.id)}`}),"keys.unregisterAction":j,"media.session.create":e=>m({type:"media.session.create.result",id:e.id,sessionId:`session-${String(e.id)}`,owner:e.owner}),"media.session.update":j,"media.session.destroy":j,"media.state":j,"media.capabilities":j,"notify.send":e=>m({type:"notify.send.result",id:e.id,notificationId:`notif-${String(e.id)}`}),"notify.dismiss":j,"notify.badge":j,"notify.channel.register":j,"notify.permission.request":e=>m({type:"notify.permission.result",id:e.id,granted:!0}),"config.registerSchema":e=>m({type:"config.registerSchema.result",id:e.id,ok:!0}),"config.get":e=>m({type:"config.values",id:e.id,values:{}}),"config.subscribe":()=>m({type:"config.values",values:{}}),"config.unsubscribe":j,"config.openSettings":j,"resource.bytes":e=>{const n=Mn(e.url);return m(n?{type:"resource.bytes.result",id:e.id,blob:n.blob,mime:n.mime}:{type:"resource.bytes.result",id:e.id,blob:new Blob([]),mime:"application/octet-stream"})},"resource.bytesMany":e=>m({type:"resource.bytesMany.result",id:e.id,items:Array.isArray(e.requests)?e.requests.map(n=>{const s=typeof n=="object"&&n!==null&&!Array.isArray(n)?n.url:void 0,t=Mn(s);return{url:typeof s=="string"?s:"",ok:!0,blob:t?.blob??new Blob([]),mime:t?.mime??"application/octet-stream"}}):[]}),"resource.info":e=>m({type:"resource.info.result",id:e.id,info:{schemes:[{scheme:"data",enabled:!0},{scheme:"https",enabled:!0}],maxServers:8}}),"resource.cancel":j,"cvm.discover":e=>m({type:"cvm.discover.result",id:e.id,servers:[]}),"cvm.request":e=>m({type:"cvm.request.result",id:e.id,message:{}}),"cvm.close":e=>m({type:"cvm.close.result",id:e.id}),"outbox.getEvent":e=>m({type:"outbox.getEvent.result",id:e.id}),"outbox.query":e=>m({type:"outbox.query.result",id:e.id,events:[]}),"outbox.subscribe":e=>m({type:"outbox.closed",subId:e.subId,reason:"reference shell complete"}),"outbox.close":j,"outbox.publish":e=>m({type:"outbox.publish.result",id:e.id,ok:!0}),"outbox.resolveRelays":e=>m({type:"outbox.resolveRelays.result",id:e.id,plan:{}}),"upload.info":e=>m({type:"upload.info.result",id:e.id,info:{rails:[{rail:"nip96",enabled:!0,returns:["https"]},{rail:"blossom",enabled:!0,returns:["https","blossom"]}]}}),"upload.upload":e=>m({type:"upload.upload.result",id:e.id,result:{url:ms}}),"upload.status":e=>m({type:"upload.status.result",id:e.id,status:{}}),"ble.open":e=>m({type:"ble.open.result",id:e.id,session:{id:"ble-reference",state:"open",device:{id:"reference-device",name:"Reference BLE"}}}),"ble.services":e=>m({type:"ble.services.result",id:e.id,services:[]}),"ble.read":e=>m({type:"ble.read.result",id:e.id,data:[]}),"ble.write":e=>m({type:"ble.write.result",id:e.id}),"ble.subscribe":e=>m({type:"ble.subscribe.result",id:e.id}),"ble.unsubscribe":e=>m({type:"ble.unsubscribe.result",id:e.id}),"ble.close":e=>m({type:"ble.close.result",id:e.id}),"common.encodeNip19":e=>m({type:"common.encodeNip19.result",id:e.id,ok:!0,value:"npub1reference",nip19Type:"npub"}),"common.decodeNip19":e=>m({type:"common.decodeNip19.result",id:e.id,ok:!0,nip19Type:"npub",hex:de}),"common.getProfile":e=>m({type:"common.getProfile.result",id:e.id,ok:!0,pubkey:de,profile:null}),"common.follows":e=>m({type:"common.follows.result",id:e.id,ok:!0,pubkeys:[]}),"common.follow":e=>m({type:"common.follow.result",id:e.id,ok:!0}),"common.unfollow":e=>m({type:"common.unfollow.result",id:e.id,ok:!0}),"common.react":e=>m({type:"common.react.result",id:e.id,ok:!0,eventId:"0".repeat(64)}),"common.report":e=>m({type:"common.report.result",id:e.id,ok:!0,eventId:"1".repeat(64)}),"webrtc.open":e=>m({type:"webrtc.open.result",id:e.id,session:{id:"webrtc-reference",scope:{type:"direct",pubkey:de},channel:"default",state:"connecting"}}),"webrtc.send":e=>m({type:"webrtc.send.result",id:e.id}),"webrtc.close":e=>m({type:"webrtc.close.result",id:e.id}),"link.open":e=>m({type:"link.open.result",id:e.id,status:"opened"}),"count.query":e=>m({type:"count.query.result",id:e.id,ok:!0,count:0}),"lists.supported":e=>m({type:"lists.supported.result",id:e.id,lists:[]}),"lists.add":e=>m({type:"lists.add.result",id:e.id,ok:!0,added:0,skipped:0}),"lists.remove":e=>m({type:"lists.remove.result",id:e.id,ok:!0,removed:0,skipped:0}),"serial.open":e=>m({type:"serial.open.result",id:e.id,session:{id:`serial-${String(e.id)}`,state:"open"}}),"serial.write":e=>m({type:"serial.write.result",id:e.id}),"serial.close":e=>m({type:"serial.close.result",id:e.id}),"fs.info":e=>m({type:"fs.info.result",id:e.id,info:{roots:[{path:"/shared",name:"Shared files",permissions:["read","list","write","create","delete","watch"]}],limits:{maxReadBytes:1048576,maxWriteBytes:1048576,maxWatchCount:16}}}),"fs.pickFile":e=>xe("fs.pickFile.result",e.id,{path:"/picked/file.txt",kind:"file",name:"file.txt",permissions:["read"]}),"fs.pickFiles":e=>xe("fs.pickFiles.result",e.id,{path:"/picked/file.txt",kind:"file",name:"file.txt",permissions:["read"]}),"fs.pickDirectory":e=>xe("fs.pickDirectory.result",e.id,{path:"/picked",kind:"directory",name:"picked",permissions:["read","list"]}),"fs.pickSaveFile":e=>xe("fs.pickSaveFile.result",e.id,{path:"/picked/export.json",kind:"file",name:"export.json",permissions:["write","create"]}),"fs.stat":e=>m({type:"fs.stat.result",id:e.id,metadata:{path:e.path,kind:"file",size:0}}),"fs.list":e=>m({type:"fs.list.result",id:e.id,entries:[]}),"fs.read":e=>m({type:"fs.read.result",id:e.id,result:{data:"",offset:0,bytesRead:0,eof:!0,size:0}}),"fs.write":e=>m({type:"fs.write.result",id:e.id,result:{bytesWritten:0,size:0}}),"fs.mkdir":e=>m({type:"fs.mkdir.result",id:e.id}),"fs.remove":e=>m({type:"fs.remove.result",id:e.id}),"fs.move":e=>m({type:"fs.move.result",id:e.id}),"fs.watch":e=>m({type:"fs.watch.result",id:e.id,watchId:`watch-${String(e.id)}`}),"fs.unwatch":e=>m({type:"fs.unwatch.result",id:e.id})},st={name:"Reference connection",model:"reference-model",route:"Reference shell → reference provider (no network)",images:!0,json:!0},be=(e,n)=>({error:{code:e,message:n}}),qe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{};function vs(e,n){let s=e.get(n.id);return s||(s={handles:new Set,active:new Map,sequence:0},e.set(n.id,s)),s}function rt(e){return{handle:e,...st}}function ws(e,n){const s=qe(n.requirements);if(s.model!==void 0&&s.model!==st.model)return be("unsupported","No connection offers the requested model");e.sequence+=1;const t=`reference-llm-h${e.sequence}`;return e.handles.add(t),{model:rt(t)}}function Es(e,n){const s=String(n.handle);return e.handles.has(s)?{model:rt(s)}:be("selection-expired","Select a model again")}function Ss(e){const n=Array.isArray(e.messages)?e.messages:[];let s="";for(const t of n){const r=qe(t);if(!(r.role!=="user"||!Array.isArray(r.content)))for(const i of r.content){const o=qe(i);o.type==="text"&&typeof o.text=="string"&&(s=o.text)}}return s}function Rs(e,n,s){const t=a=>[{type:"llm.generate.result",id:n,...a}];if(e.active.has(n))return t(be("invalid-request","Request id is still active"));const r=qe(s.request);if(!e.handles.has(String(r.handle)))return t(be("selection-expired","Select a model again"));const i=Ss(r);if(i.includes("[[decline]]"))return t(be("user-cancelled","The user declined disclosure"));if(i.includes("[[stall]]"))return e.active.set(n,s),[];if(i.includes("[[refuse]]"))return t({result:{text:"",finish:"refusal"}});const o=r.format==="json"?JSON.stringify({echo:i}):`Echo: ${i}`,l={inputTokens:JSON.stringify(r.messages).length,outputTokens:o.length};return[{type:"llm.delta",requestId:n,sequence:0,text:o.slice(0,Math.ceil(o.length/2))},...t({result:{text:o,finish:"stop",usage:l}})]}function Ts(e,n,s){const t=String(s.requestId);return e.active.delete(t)?[{type:"llm.generate.result",id:t,error:{code:"cancelled",message:"Generation cancelled; provider charges may still apply."}},{type:"llm.cancel.result",id:n,cancelled:!0}]:[{type:"llm.cancel.result",id:n,cancelled:!1}]}function _s(e,n,s){const t=String(s.type),r=String(s.id),i=vs(e,n);switch(t){case"llm.select":return[{type:"llm.select.result",id:r,...ws(i,s)}];case"llm.describe":return[{type:"llm.describe.result",id:r,...Es(i,s)}];case"llm.generate":return structuredClone(Rs(i,r,s));case"llm.cancel":return Ts(i,r,s);default:return[{type:`${t}.result`,id:r,error:{code:"invalid-request",message:`Unknown operation ${t}`}}]}}function ks(){const e=new Map;return{handle:(n,s)=>_s(e,n,s),reset(){e.clear()}}}function Is(e){const n=new Set,s=e.domains?new Set(e.domains):null,t=ks();return Object.assign((i,o)=>{const l=xs(o),a=ss(o);if(e.records.push({envelope:o,verdict:a,timestamp:e.now()}),!l||!a.ok)return[];const c=i.domains??$e,h=s?c.filter(f=>s.has(f)):c;if(!h.includes(l.slice(0,l.indexOf("."))))return[];if(l==="shell.ready")return n.has(i.id)?[]:(n.add(i.id),m({type:"shell.init",capabilities:{domains:[...h]},services:[]}));const p=o;if(l.startsWith("llm."))return t.handle(i,p);if(l==="intent.invoke")return e.intents.handleInvoke(i,p);if(l==="intent.available")return m({type:"intent.available.result",id:p.id,availability:e.intents.availability(p.archetype)});if(l==="intent.handlers")return m({type:"intent.handlers.result",id:p.id,handlers:e.intents.handlers()});if(l==="inc.emit")return Ms(i,p,e.queueDelivery);const d=bs[l];return d?d(p):[]},{reset(){t.reset()}})}function xs(e){if(!e||typeof e!="object")return;const n=e.type;return typeof n=="string"?n:void 0}function Ms(e,n,s){if(n.topic!==ys)return[];const t={type:"inc.event",topic:n.topic,sender:e.id};return"payload"in n&&(t.payload=n.payload),s(hs,t),[]}function Us(e){return e.kind===5129?`snapshot:${e.id}`:e.kind===15129?`root:${e.pubkey}`:`named:${e.pubkey}:${e.tags.find(n=>n[0]==="d")?.[1]??""}`}function As(e,n){if(!e.tags.some(t=>t[0]==="z"&&t[1]===n))return[];const s=[];for(const t of e.tags)t[0]!=="i"||/^napplet:([^/?#]+)\/([^/?#]+)$/.exec(t[1]??"")?.[1]!==n||s.push({convention:t[1],params:t.slice(2)});return s}function Ps(e,n,s){const t=[];for(const r of e){const i=As(r,n);if(!i.length)continue;const o=r.tags.find(a=>a[0]==="title")?.[1],l=Us(r);t.push({id:l,...o?{title:o}:{},actions:[...new Set(i.map(({convention:a})=>a.slice(a.indexOf("/")+1)))],conventions:[...new Set(i.map(({convention:a})=>a))],contracts:i,...l===s?{isDefault:!0}:{}})}return{archetype:n,available:t.length>0,candidates:t,hasDefault:t.some(r=>r.isDefault)}}function js(e,n=[gs],s={note:fs}){const t=r=>Ps(n,String(r),s[String(r)]);return{availability:t,handlers:()=>[...new Set(n.flatMap(r=>r.tags.filter(i=>i[0]==="z").map(i=>i[1])))].map(t),handleInvoke(r,i){const o=i.request,l=t(o.archetype).candidates.filter(f=>f.conventions.includes(o.convention)),a=o.handler&&!["default","choose"].includes(o.handler),c=o.handler==="choose"?void 0:a?l.find(f=>f.id===o.handler):l.find(f=>f.isDefault)??l[0];if(!c)return m({type:"intent.invoke.result",id:i.id,result:{ok:!1,error:"no handler"}});const{archetype:h,action:p,convention:d}=o;return e(c.id,structuredClone({type:"intent.deliver",delivery:{sender:r.catalogId,archetype:h,action:p,convention:d,..."payload"in o?{payload:o.payload}:{}}})),m({type:"intent.invoke.result",id:i.id,result:{ok:!0,archetype:h,action:p,convention:d,handler:c.id}})}}}function Os(e={}){const n=[],s=qs(),t=Is({now:e.now??Date.now,records:n,domains:e.domains,queueDelivery:s.queue,intents:js(s.queue,e.manifests,e.defaults)});return{get records(){return n},handle:r=>t(ps,r),handleFrom:t,takeDeliveries:s.take,reset(){n.length=0,t.reset(),s.clear()}}}function qs(){const e=new Map;return{queue(n,s){const t=e.get(n);t?t.push(s):e.set(n,[s])},take(n){const s=e.get(n)??[];return e.delete(n),s},clear(){e.clear()}}}function Cs(e){return{manifestHtml:e.manifestHtml,manifestEvent:e.manifestEvent??null,sandbox:e.sandbox??{allowScripts:!0,allowSameOrigin:!1},installedGlobal:e.boot.installedGlobal,bootError:e.boot.bootError,emitted:e.boot.emitted,forbiddenGlobals:e.forbiddenGlobals??[],degraded:e.boot.degraded,lifecycle:e.lifecycle??null}}var it="__nappletConformance.error",ot="__nappletConformance.installed";function Un(e){return new Promise(n=>setTimeout(n,e))}function Ns(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Hs(){return`(() => {
|
|
78
2
|
const report = (reason) => {
|
|
79
|
-
try { window.parent.postMessage({ type: '${
|
|
3
|
+
try { window.parent.postMessage({ type: '${it}', reason: String(reason && reason.message || reason) }, '*'); }
|
|
80
4
|
catch {}
|
|
81
5
|
};
|
|
82
6
|
window.addEventListener('error', (event) => report(event.error || event.message));
|
|
83
7
|
window.addEventListener('unhandledrejection', (event) => report(event.reason));
|
|
84
|
-
})();`}
|
|
85
|
-
(() => {
|
|
86
|
-
const domains = `,Nr=`;
|
|
87
|
-
const napplet = {};
|
|
88
|
-
for (const domain of domains) {
|
|
89
|
-
if (domain === 'resource' || domain === 'gamepad') napplet[domain] = {};
|
|
90
|
-
}
|
|
91
|
-
const gamepadTools = `,Br=`;
|
|
92
|
-
let gamepadState = { available: true, focused: false, pads: [] };
|
|
93
|
-
const gamepadHandlers = new Set();
|
|
94
|
-
// Subscribe on first use, like the nap binding, so napplets that never touch
|
|
95
|
-
// gamepad emit no gamepad traffic for checks to attribute to them.
|
|
96
|
-
let gamepadSubscribed = false;
|
|
97
|
-
const gamepadSubscribe = () => {
|
|
98
|
-
if (gamepadSubscribed) return;
|
|
99
|
-
gamepadSubscribed = true;
|
|
100
|
-
window.parent.postMessage({ type: 'gamepad.subscribe' }, '*');
|
|
101
|
-
};
|
|
102
|
-
const pending = new Map();
|
|
103
|
-
let seq = 0;
|
|
104
|
-
const nextId = () => {
|
|
105
|
-
try {
|
|
106
|
-
if (window.crypto && typeof window.crypto.randomUUID === 'function') return window.crypto.randomUUID();
|
|
107
|
-
} catch {}
|
|
108
|
-
seq += 1;
|
|
109
|
-
return 'conformance-' + Date.now().toString(36) + '-' + seq.toString(36);
|
|
110
|
-
};
|
|
111
|
-
const request = (message, resultType, errorType) => new Promise((resolve, reject) => {
|
|
112
|
-
const id = message.id || nextId();
|
|
113
|
-
const timeout = window.setTimeout(() => {
|
|
114
|
-
pending.delete(id);
|
|
115
|
-
reject(new Error(message.type + ' timed out'));
|
|
116
|
-
}, 5000);
|
|
117
|
-
pending.set(id, { resolve, reject, resultType, errorType, timeout });
|
|
118
|
-
window.parent.postMessage({ ...message, id }, '*');
|
|
119
|
-
});
|
|
120
|
-
window.addEventListener('message', (event) => {
|
|
121
|
-
if (event.source !== window.parent) return;
|
|
122
|
-
const msg = event.data;
|
|
123
|
-
if (gamepadSubscribed && msg && msg.type === 'gamepad.state' && !('id' in msg) && gamepadTools.isGamepadState(msg)) {
|
|
124
|
-
gamepadState = gamepadTools.copyGamepadState(msg);
|
|
125
|
-
const recipients = Array.from(gamepadHandlers);
|
|
126
|
-
for (const entry of recipients) {
|
|
127
|
-
if (!gamepadHandlers.has(entry)) continue;
|
|
128
|
-
try { entry.handler(gamepadTools.copyGamepadState(gamepadState)); }
|
|
129
|
-
catch (error) { queueMicrotask(() => { throw error; }); }
|
|
130
|
-
}
|
|
131
|
-
return;
|
|
132
|
-
}
|
|
133
|
-
if (!msg || typeof msg !== 'object' || typeof msg.id !== 'string') return;
|
|
134
|
-
const slot = pending.get(msg.id);
|
|
135
|
-
if (!slot) return;
|
|
136
|
-
if (msg.type !== slot.resultType && msg.type !== slot.errorType) return;
|
|
137
|
-
pending.delete(msg.id);
|
|
138
|
-
window.clearTimeout(slot.timeout);
|
|
139
|
-
if (msg.type === slot.errorType) {
|
|
140
|
-
slot.reject(new Error(msg.message ? msg.error + ': ' + msg.message : String(msg.error || 'request failed')));
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
slot.resolve(msg);
|
|
144
|
-
});
|
|
145
|
-
if (napplet.gamepad) {
|
|
146
|
-
napplet.gamepad = {
|
|
147
|
-
get available() { gamepadSubscribe(); return gamepadState.available; },
|
|
148
|
-
get focused() { gamepadSubscribe(); return gamepadState.focused; },
|
|
149
|
-
getGamepads() { gamepadSubscribe(); return gamepadTools.copyGamepadState(gamepadState).pads; },
|
|
150
|
-
onChange(handler) {
|
|
151
|
-
const entry = { handler };
|
|
152
|
-
gamepadHandlers.add(entry);
|
|
153
|
-
gamepadSubscribe();
|
|
154
|
-
return { close() { gamepadHandlers.delete(entry); } };
|
|
155
|
-
},
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
if (napplet.resource) {
|
|
159
|
-
napplet.resource.info = () =>
|
|
160
|
-
request({ type: 'resource.info' }, 'resource.info.result', 'resource.info.error')
|
|
161
|
-
.then((msg) => msg.info);
|
|
162
|
-
napplet.resource.bytes = (url, options) => {
|
|
163
|
-
const message = { type: 'resource.bytes', url: String(url) };
|
|
164
|
-
if (options && options.servers !== undefined) message.servers = options.servers;
|
|
165
|
-
return request(message, 'resource.bytes.result', 'resource.bytes.error')
|
|
166
|
-
.then((msg) => msg.blob);
|
|
167
|
-
};
|
|
168
|
-
napplet.resource.bytesMany = (requests) =>
|
|
169
|
-
request({ type: 'resource.bytesMany', requests: Array.from(requests || []) }, 'resource.bytesMany.result', 'resource.bytesMany.error')
|
|
170
|
-
.then((msg) => msg.items);
|
|
171
|
-
napplet.resource.bytesAsObjectURL = (url) => {
|
|
172
|
-
const handle = { url: '', revoke: () => {} };
|
|
173
|
-
let objectUrl = '';
|
|
174
|
-
let revoked = false;
|
|
175
|
-
const ready = napplet.resource.bytes(url).then((blob) => {
|
|
176
|
-
if (revoked) return;
|
|
177
|
-
objectUrl = URL.createObjectURL(blob);
|
|
178
|
-
handle.url = objectUrl;
|
|
179
|
-
return objectUrl;
|
|
180
|
-
});
|
|
181
|
-
handle.revoke = () => {
|
|
182
|
-
if (revoked) return;
|
|
183
|
-
revoked = true;
|
|
184
|
-
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
|
185
|
-
};
|
|
186
|
-
Object.defineProperty(handle, 'ready', { value: ready, enumerable: false });
|
|
187
|
-
return handle;
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
${qr}
|
|
191
|
-
window.napplet = napplet;
|
|
192
|
-
`,Lr=`
|
|
193
|
-
})();
|
|
194
|
-
`;function $r(e,n){const r=`window.parent.postMessage({ type: '${it}', installed: !!window.napplet }, '*');`;return n!==void 0?`${n}
|
|
8
|
+
})();`}function Ds(e,n){const s=`window.parent.postMessage({ type: '${ot}', installed: !!window.napplet }, '*');`;return`${n}
|
|
195
9
|
;globalThis.NappletShimPrelude.install(${JSON.stringify({domains:e})});
|
|
196
|
-
${r}`:Dr+JSON.stringify(e)+Nr+Cr+Br+r+Lr}function Fr(e,n,r,t){const s=`<base href="${Or(n)}">`,i=$r(r,t).replace(/<\/script/gi,"<\\/script"),o=`<script>${Hr()}<\/script><script>${i}<\/script>`,l=/<head(?:\s[^>]*)?>/i.exec(e);if(l){const a=l.index+l[0].length;return`${e.slice(0,a)}${s}${o}${e.slice(a)}`}return`${s}${o}${e}`}function Gr(e){if(!e.startsWith("data:"))return null;const n=e.indexOf(",");if(n<0)return"";const r=e.slice(0,n),t=e.slice(n+1);return r.endsWith(";base64")?atob(t):decodeURIComponent(t)}async function Wr(e){if(e==="about:blank")return"<!doctype html><html><head></head><body></body></html>";const n=Gr(e);if(n!==null)return n;const r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch napplet HTML: ${r.status} ${r.statusText}`);return r.text()}async function Un(e,n,r,t){const s=Pr(),i=r.createElement("iframe");i.setAttribute("sandbox",n.allowSameOrigin?"allow-scripts allow-same-origin":"allow-scripts"),i.setAttribute("allow","gamepad 'none'"),i.setAttribute("aria-hidden","true"),i.style.position="absolute",i.style.width="1px",i.style.height="1px",i.style.left="-9999px";let o=null,l=!1;const a=p=>{if(p.source!==i.contentWindow)return;const c=p.data;if(c&&typeof c=="object"&&c.type===it){l=c.installed===!0;return}if(c&&typeof c=="object"&&c.type===st){o=`napplet boot error: ${String(c.reason??"unknown error")}`;return}const m=s.handle(p.data),y=p.source;for(const w of m)y?.postMessage(w,"*")};let d=!1;const h=new Promise(p=>{i.addEventListener("load",()=>{d=!0,p()},{once:!0})});t.addEventListener("message",a);try{const p=n.html??await Wr(n.url);i.srcdoc=Fr(p,n.url,e,n.runtimePreludeSource),(r.body??r.documentElement).appendChild(i)}catch(p){o=p instanceof Error?p.message:String(p)}if(!o){const p=Symbol("timeout");await Promise.race([h.then(()=>"loaded"),Mn(n.readyTimeoutMs).then(()=>p)])===p||!d?o=`napplet did not boot (iframe did not load within ${n.readyTimeoutMs}ms; a conformant napplet must run under sandbox="allow-scripts" without allow-same-origin)`:await Mn(n.settleMs)}t.removeEventListener("message",a);try{i.remove()}catch{}return{installedGlobal:l,bootError:o,emitted:[...s.records]}}async function Vr(e){const n=e.document??document,r=e.window??window,t={url:e.url,html:e.html,readyTimeoutMs:e.readyTimeoutMs??5e3,settleMs:e.settleMs,allowSameOrigin:e.allowSameOrigin??!1,runtimePreludeSource:e.runtimePreludeSource},s=await Un(Le,t,n,r);let i=null;{const o=await Un([],t,n,r);i={bootError:o.bootError,emitted:o.emitted}}return{installedGlobal:s.installedGlobal,bootError:s.bootError,emitted:s.emitted,degraded:i}}var zr=e=>({status:"pass",detail:e}),Qr=(e,n)=>({status:"fail",detail:e,diagnostics:n}),Kr=e=>({status:"skip",detail:e}),A={pass:zr,fail:Qr,skip:Kr};function Zr(e,n){const r=Ge(e.manifestEvent);return[...r.errors,...r.warnings].filter(t=>n.includes(t.code))}function me(e,n,r,t="error"){return{id:e,area:"manifest",severity:t,title:n,run:s=>{if(!s.manifestEvent)return A.skip("No NIP-5D manifest event was resolved");const i=Zr(s,r);return i.length?A.fail(i[0].message,i):A.pass()}}}var Yr=[me("manifest/event-kind","Resolved event is a NIP-5D napplet manifest",["invalid-napplet-kind","missing-d-tag","unexpected-d-tag"]),me("manifest/index-html","Manifest declares a hashed /index.html",["invalid-artifact-hash","missing-description","invalid-metadata"]),me("manifest/requires","R/O tags name bare NAP domains",["invalid-required-nap","invalid-optional-nap"]),me("manifest/requires-known","R/O domains are in this toolchain registry (advisory)",["unknown-required-nap"],"warning"),me("manifest/media-usable","Icon, screenshots, preview and source pins are usable (advisory)",["invalid-icon","invalid-presentation-media","unused-source-commit"],"warning"),{id:"boot/sandbox-allow-scripts",area:"boot",severity:"error",title:"Runs under allow-scripts without allow-same-origin",run:e=>e.sandbox.allowScripts?e.sandbox.allowSameOrigin?A.fail("Napplet relied on allow-same-origin, which a shell must not grant"):A.pass():A.fail("Napplet was not loaded with allow-scripts")},{id:"boot/installs-global",area:"boot",severity:"error",title:"Runs after runtime-injected window.napplet is installed",run:e=>e.installedGlobal?A.pass():A.fail("runtime did not inject window.napplet before load")},{id:"boot/no-boot-error",area:"boot",severity:"error",title:"Boots without an uncaught error",run:e=>e.bootError?A.fail(e.bootError):A.pass()},{id:"boot/no-forbidden-globals",area:"boot",severity:"error",title:"Does not access forbidden browser authority surfaces",run:e=>e.forbiddenGlobals.length?A.fail(`Accessed forbidden surface(s): ${e.forbiddenGlobals.join(", ")}`,e.forbiddenGlobals):A.pass()},{id:"wire/envelope-well-formed",area:"wire",severity:"error",title:"Every emitted envelope is well-formed",run:e=>{if(e.emitted.length===0)return A.skip("Napplet emitted no envelopes");const n=e.emitted.filter(t=>!t.verdict.ok);if(n.length===0)return A.pass(`${e.emitted.length} envelope(s) valid`);const r=n.map(t=>({envelope:t.envelope,errors:t.verdict.errors}));return A.fail(`${n.length}/${e.emitted.length} emitted envelope(s) invalid`,r)}},{id:"degrade/domain-absence",area:"degradation",severity:"error",title:"Does not crash when no NAP domains are injected",run:e=>e.degraded?e.degraded.bootError?A.fail(`Crashed with no injected domains: ${e.degraded.bootError}`):A.pass():A.skip("Host did not run the degraded (no-capabilities) pass")},{id:"lifecycle/clean-teardown",area:"lifecycle",severity:"warning",title:"Tears down listeners on unload",run:e=>e.lifecycle?e.lifecycle.listenerLeak?A.fail("Message listeners remained after unload"):A.pass():A.skip("Lifecycle not measured")}];function Xr(e,n={}){const r=n.now??(()=>Date.now()),t=n.checks??Yr,s=r(),i=t.map(a=>{const d=a.run(e);return{id:a.id,area:a.area,severity:a.severity,title:a.title,status:d.status,detail:d.detail,diagnostics:d.diagnostics}}),o={total:i.length,passed:i.filter(a=>a.status==="pass").length,failed:i.filter(a=>a.status==="fail").length,skipped:i.filter(a=>a.status==="skip").length,errors:i.filter(a=>a.status==="fail"&&a.severity==="error").length,warnings:i.filter(a=>a.status==="fail"&&a.severity==="warning").length};return{napplet:e.manifestEvent?nt(e.manifestEvent):void 0,startedAt:s,finishedAt:r(),checks:i,summary:o,ok:o.errors===0}}function Jr(e,n){const r=s=>e.tags.find(i=>i[0]===s)?.[1],t=e.tags.filter(s=>s[0]==="server").map(s=>s[1]).filter(Boolean);return[["event",e.id],["kind",e.kind],["d",r("d")],["name",nt(e)],["requires",n.requires.join(", ")],["optional",n.optional.join(", ")],["artifact hash (x)",r("x")],["servers",t.join(", ")]]}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function es(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function hn(e,n=""){if(!Number.isSafeInteger(e)||e<0){const r=n&&`"${n}" `;throw new Error(`${r}expected integer >= 0, got ${e}`)}}function L(e,n,r=""){const t=es(e),s=e?.length,i=n!==void 0;if(!t||i&&s!==n){const o=r&&`"${r}" `,l=i?` of length ${n}`:"",a=t?`length=${s}`:`type=${typeof e}`;throw new Error(o+"expected Uint8Array"+l+", got "+a)}return e}function Pn(e,n=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(n&&e.finished)throw new Error("Hash#digest() has already been called")}function ns(e,n){L(e,void 0,"digestInto() output");const r=n.outputLen;if(e.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function on(...e){for(let n=0;n<e.length;n++)e[n].fill(0)}function Ze(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function K(e,n){return e<<32-n|e>>>n}const ot=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ts=Array.from({length:256},(e,n)=>n.toString(16).padStart(2,"0"));function C(e){if(L(e),ot)return e.toHex();let n="";for(let r=0;r<e.length;r++)n+=ts[e[r]];return n}const X={_0:48,_9:57,A:65,F:70,a:97,f:102};function An(e){if(e>=X._0&&e<=X._9)return e-X._0;if(e>=X.A&&e<=X.F)return e-(X.A-10);if(e>=X.a&&e<=X.f)return e-(X.a-10)}function Y(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(ot)return Uint8Array.fromHex(e);const n=e.length,r=n/2;if(n%2)throw new Error("hex string expected, got unpadded hex of length "+n);const t=new Uint8Array(r);for(let s=0,i=0;s<r;s++,i+=2){const o=An(e.charCodeAt(i)),l=An(e.charCodeAt(i+1));if(o===void 0||l===void 0){const a=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+i)}t[s]=o*16+l}return t}function Oe(...e){let n=0;for(let t=0;t<e.length;t++){const s=e[t];L(s),n+=s.length}const r=new Uint8Array(n);for(let t=0,s=0;t<e.length;t++){const i=e[t];r.set(i,s),s+=i.length}return r}function rs(e,n={}){const r=(s,i)=>e(i).update(s).digest(),t=e(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=s=>e(s),Object.assign(r,n),Object.freeze(r)}function at(e=32){const n=typeof globalThis=="object"?globalThis.crypto:null;if(typeof n?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return n.getRandomValues(new Uint8Array(e))}const ss=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function lt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function dt(e,n){return Array.isArray(n)?n.length===0?!0:e?n.every(r=>typeof r=="string"):n.every(r=>Number.isSafeInteger(r)):!1}function is(e){if(typeof e!="function")throw new Error("function expected");return!0}function Se(e,n){if(typeof n!="string")throw new Error(`${e}: string expected`);return!0}function ct(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function an(e){if(!Array.isArray(e))throw new Error("array expected")}function ut(e,n){if(!dt(!0,n))throw new Error(`${e}: array of strings expected`)}function pt(e,n){if(!dt(!1,n))throw new Error(`${e}: array of numbers expected`)}function os(...e){const n=i=>i,r=(i,o)=>l=>i(o(l)),t=e.map(i=>i.encode).reduceRight(r,n),s=e.map(i=>i.decode).reduce(r,n);return{encode:t,decode:s}}function as(e){const n=typeof e=="string"?e.split(""):e,r=n.length;ut("alphabet",n);const t=new Map(n.map((s,i)=>[s,i]));return{encode:s=>(an(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return n[i]})),decode:s=>(an(s),s.map(i=>{Se("alphabet.decode",i);const o=t.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${e}`);return o}))}}function ls(e=""){return Se("join",e),{encode:n=>(ut("join.decode",n),n.join(e)),decode:n=>(Se("join.decode",n),n.split(e))}}const ft=(e,n)=>n===0?e:ft(n,e%n),Ce=(e,n)=>e+(n-ft(e,n)),Ae=(()=>{let e=[];for(let n=0;n<40;n++)e.push(2**n);return e})();function ln(e,n,r,t){if(an(e),n<=0||n>32)throw new Error(`convertRadix2: wrong from=${n}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(Ce(n,r)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${r} carryBits=${Ce(n,r)}`);let s=0,i=0;const o=Ae[n],l=Ae[r]-1,a=[];for(const d of e){if(ct(d),d>=o)throw new Error(`convertRadix2: invalid data word=${d} from=${n}`);if(s=s<<n|d,i+n>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${n}`);for(i+=n;i>=r;i-=r)a.push((s>>i-r&l)>>>0);const h=Ae[i];if(h===void 0)throw new Error("invalid carry");s&=h-1}if(s=s<<r-i&l,!t&&i>=n)throw new Error("Excess padding");if(!t&&s>0)throw new Error(`Non-zero padding: ${s}`);return t&&i>0&&a.push(s>>>0),a}function ds(e,n=!1){if(ct(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Ce(8,e)>32||Ce(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!lt(r))throw new Error("radix2.encode input should be Uint8Array");return ln(Array.from(r),8,e,!n)},decode:r=>(pt("radix2.decode",r),Uint8Array.from(ln(r,e,8,n)))}}function jn(e){return is(e),function(...n){try{return e.apply(null,n)}catch{}}}const dn=os(as("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ls("")),qn=[996825010,642813549,513874426,1027748829,705979059];function ge(e){const n=e>>25;let r=(e&33554431)<<5;for(let t=0;t<qn.length;t++)(n>>t&1)===1&&(r^=qn[t]);return r}function On(e,n,r=1){const t=e.length;let s=1;for(let i=0;i<t;i++){const o=e.charCodeAt(i);if(o<33||o>126)throw new Error(`Invalid prefix (${e})`);s=ge(s)^o>>5}s=ge(s);for(let i=0;i<t;i++)s=ge(s)^e.charCodeAt(i)&31;for(let i of n)s=ge(s)^i;for(let i=0;i<6;i++)s=ge(s);return s^=r,dn.encode(ln([s%Ae[30]],30,5,!1))}function cs(e){const n=e==="bech32"?1:734539939,r=ds(5),t=r.decode,s=r.encode,i=jn(t);function o(p,c,m=90){Se("bech32.encode prefix",p),lt(c)&&(c=Array.from(c)),pt("bech32.encode",c);const y=p.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);const w=y+7+c.length;if(m!==!1&&w>m)throw new TypeError(`Length ${w} exceeds limit ${m}`);const P=p.toLowerCase(),q=On(P,c,n);return`${P}1${dn.encode(c)}${q}`}function l(p,c=90){Se("bech32.decode input",p);const m=p.length;if(m<8||c!==!1&&m>c)throw new TypeError(`invalid string length: ${m} (${p}). Expected (8..${c})`);const y=p.toLowerCase();if(p!==y&&p!==p.toUpperCase())throw new Error("String must be lowercase or uppercase");const w=y.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const P=y.slice(0,w),q=y.slice(w+1);if(q.length<6)throw new Error("Data must be at least 6 characters long");const z=dn.decode(q).slice(0,-6),J=On(P,z,n);if(!q.endsWith(J))throw new Error(`Invalid checksum in ${p}: expected "${J}"`);return{prefix:P,words:z}}const a=jn(l);function d(p){const{prefix:c,words:m}=l(p,!1);return{prefix:c,words:m,bytes:t(m)}}function h(p,c){return o(p,s(c))}return{encode:o,decode:l,encodeFromBytes:h,decodeToBytes:d,decodeUnsafe:a,fromWords:t,fromWordsUnsafe:i,toWords:s}}const Cn=cs("bech32");var Me=new TextDecoder("utf-8");new TextEncoder;var us=5e3;function ps(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),fs(e)}catch{return{type:"invalid",data:null}}}function fs(e){let{prefix:n,words:r}=Cn.decode(e,us),t=new Uint8Array(Cn.fromWords(r));switch(n){case"nprofile":{let s=Ye(t);if(!s[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(s[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:C(s[0][0]),relays:s[1]?s[1].map(i=>Me.decode(i)):[]}}}case"nevent":{let s=Ye(t);if(!s[0]?.[0])throw new Error("missing TLV 0 for nevent");if(s[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(s[2]&&s[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(s[3]&&s[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:C(s[0][0]),relays:s[1]?s[1].map(i=>Me.decode(i)):[],author:s[2]?.[0]?C(s[2][0]):void 0,kind:s[3]?.[0]?parseInt(C(s[3][0]),16):void 0}}}case"naddr":{let s=Ye(t);if(!s[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!s[2]?.[0])throw new Error("missing TLV 2 for naddr");if(s[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!s[3]?.[0])throw new Error("missing TLV 3 for naddr");if(s[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Me.decode(s[0][0]),pubkey:C(s[2][0]),kind:parseInt(C(s[3][0]),16),relays:s[1]?s[1].map(i=>Me.decode(i)):[]}}}case"nsec":return{type:n,data:t};case"npub":case"note":return{type:n,data:C(t)};default:throw new Error(`unknown prefix ${n}`)}}function Ye(e){let n={},r=e;for(;r.length>0;){let t=r[0],s=r[1],i=r.slice(2,2+s);if(r=r.slice(2+s),i.length<s)throw new Error(`not enough data to read on TLV ${t}`);n[t]=n[t]||[],n[t].push(i)}return n}function ms(e,n,r){return e&n^~e&r}function gs(e,n,r){return e&n^e&r^n&r}class hs{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(n,r,t,s){this.blockLen=n,this.outputLen=r,this.padOffset=t,this.isLE=s,this.buffer=new Uint8Array(n),this.view=Ze(this.buffer)}update(n){Pn(this),L(n);const{view:r,buffer:t,blockLen:s}=this,i=n.length;for(let o=0;o<i;){const l=Math.min(s-this.pos,i-o);if(l===s){const a=Ze(n);for(;s<=i-o;o+=s)this.process(a,o);continue}t.set(n.subarray(o,o+l),this.pos),this.pos+=l,o+=l,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=n.length,this.roundClean(),this}digestInto(n){Pn(this),ns(n,this),this.finished=!0;const{buffer:r,view:t,blockLen:s,isLE:i}=this;let{pos:o}=this;r[o++]=128,on(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(t,0),o=0);for(let p=o;p<s;p++)r[p]=0;t.setBigUint64(s-8,BigInt(this.length*8),i),this.process(t,0);const l=Ze(n),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const d=a/4,h=this.get();if(d>h.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<d;p++)l.setUint32(4*p,h[p],i)}digest(){const{buffer:n,outputLen:r}=this;this.digestInto(n);const t=n.slice(0,r);return this.destroy(),t}_cloneInto(n){n||=new this.constructor,n.set(...this.get());const{blockLen:r,buffer:t,length:s,finished:i,destroyed:o,pos:l}=this;return n.destroyed=o,n.finished=i,n.length=s,n.pos=l,s%r&&n.buffer.set(t),n}clone(){return this._cloneInto()}}const ee=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ys=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ne=new Uint32Array(64);class bs extends hs{constructor(n){super(64,n,8,!1)}get(){const{A:n,B:r,C:t,D:s,E:i,F:o,G:l,H:a}=this;return[n,r,t,s,i,o,l,a]}set(n,r,t,s,i,o,l,a){this.A=n|0,this.B=r|0,this.C=t|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=l|0,this.H=a|0}process(n,r){for(let p=0;p<16;p++,r+=4)ne[p]=n.getUint32(r,!1);for(let p=16;p<64;p++){const c=ne[p-15],m=ne[p-2],y=K(c,7)^K(c,18)^c>>>3,w=K(m,17)^K(m,19)^m>>>10;ne[p]=w+ne[p-7]+y+ne[p-16]|0}let{A:t,B:s,C:i,D:o,E:l,F:a,G:d,H:h}=this;for(let p=0;p<64;p++){const c=K(l,6)^K(l,11)^K(l,25),m=h+c+ms(l,a,d)+ys[p]+ne[p]|0,w=(K(t,2)^K(t,13)^K(t,22))+gs(t,s,i)|0;h=d,d=a,a=l,l=o+m|0,o=i,i=s,s=t,t=m+w|0}t=t+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,l=l+this.E|0,a=a+this.F|0,d=d+this.G|0,h=h+this.H|0,this.set(t,s,i,o,l,a,d,h)}roundClean(){on(ne)}destroy(){this.set(0,0,0,0,0,0,0,0),on(this.buffer)}}class vs extends bs{A=ee[0]|0;B=ee[1]|0;C=ee[2]|0;D=ee[3]|0;E=ee[4]|0;F=ee[5]|0;G=ee[6]|0;H=ee[7]|0;constructor(){super(32)}}const He=rs(()=>new vs,ss(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const yn=BigInt(0),cn=BigInt(1);function Hn(e,n=""){if(typeof e!="boolean"){const r=n&&`"${n}" `;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function ws(e){if(typeof e=="bigint"){if(!Ts(e))throw new Error("positive bigint expected, got "+e)}else hn(e);return e}function mt(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?yn:BigInt("0x"+e)}function bn(e){return mt(C(e))}function gt(e){return mt(C(Es(L(e)).reverse()))}function vn(e,n){hn(n),e=ws(e);const r=Y(e.toString(16).padStart(n*2,"0"));if(r.length!==n)throw new Error("number too large");return r}function ht(e,n){return vn(e,n).reverse()}function Es(e){return Uint8Array.from(e)}function Ss(e){return Uint8Array.from(e,(n,r)=>{const t=n.charCodeAt(0);if(n.length!==1||t>127)throw new Error(`string contains non-ASCII character "${e[r]}" with code ${t} at position ${r}`);return t})}const Ts=e=>typeof e=="bigint"&&yn<=e;function _s(e){let n;for(n=0;e>yn;e>>=cn,n+=1);return n}const yt=e=>(cn<<BigInt(e))-cn;function bt(e,n={},r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function t(i,o,l){const a=e[i];if(l&&a===void 0)return;const d=typeof a;if(d!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${d}`)}const s=(i,o)=>Object.entries(i).forEach(([l,a])=>t(l,a,o));s(n,!1),s(r,!0)}function Dn(e){const n=new WeakMap;return(r,...t)=>{const s=n.get(r);if(s!==void 0)return s;const i=e(r,...t);return n.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const B=BigInt(0),N=BigInt(1),ie=BigInt(2),vt=BigInt(3),wt=BigInt(4),Et=BigInt(5),Rs=BigInt(7),St=BigInt(8),Is=BigInt(9),Tt=BigInt(16);function V(e,n){const r=e%n;return r>=B?r:n+r}function F(e,n,r){let t=e;for(;n-- >B;)t*=t,t%=r;return t}function Nn(e,n){if(e===B)throw new Error("invert: expected non-zero number");if(n<=B)throw new Error("invert: expected positive modulus, got "+n);let r=V(e,n),t=n,s=B,i=N;for(;r!==B;){const l=t/r,a=t%r,d=s-i*l;t=r,r=a,s=i,i=d}if(t!==N)throw new Error("invert: does not exist");return V(s,n)}function wn(e,n,r){if(!e.eql(e.sqr(n),r))throw new Error("Cannot find square root")}function _t(e,n){const r=(e.ORDER+N)/wt,t=e.pow(n,r);return wn(e,t,n),t}function xs(e,n){const r=(e.ORDER-Et)/St,t=e.mul(n,ie),s=e.pow(t,r),i=e.mul(n,s),o=e.mul(e.mul(i,ie),s),l=e.mul(i,e.sub(o,e.ONE));return wn(e,l,n),l}function ks(e){const n=We(e),r=Rt(e),t=r(n,n.neg(n.ONE)),s=r(n,t),i=r(n,n.neg(t)),o=(e+Rs)/Tt;return(l,a)=>{let d=l.pow(a,o),h=l.mul(d,t);const p=l.mul(d,s),c=l.mul(d,i),m=l.eql(l.sqr(h),a),y=l.eql(l.sqr(p),a);d=l.cmov(d,h,m),h=l.cmov(c,p,y);const w=l.eql(l.sqr(h),a),P=l.cmov(d,h,w);return wn(l,P,a),P}}function Rt(e){if(e<vt)throw new Error("sqrt is not defined for small field");let n=e-N,r=0;for(;n%ie===B;)n/=ie,r++;let t=ie;const s=We(e);for(;Bn(s,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return _t;let i=s.pow(t,n);const o=(n+N)/ie;return function(a,d){if(a.is0(d))return d;if(Bn(a,d)!==1)throw new Error("Cannot find square root");let h=r,p=a.mul(a.ONE,i),c=a.pow(d,n),m=a.pow(d,o);for(;!a.eql(c,a.ONE);){if(a.is0(c))return a.ZERO;let y=1,w=a.sqr(c);for(;!a.eql(w,a.ONE);)if(y++,w=a.sqr(w),y===h)throw new Error("Cannot find square root");const P=N<<BigInt(h-y-1),q=a.pow(p,P);h=y,p=a.sqr(q),c=a.mul(c,p),m=a.mul(m,q)}return m}}function Ms(e){return e%wt===vt?_t:e%St===Et?xs:e%Tt===Is?ks(e):Rt(e)}const Us=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ps(e){const n={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Us.reduce((t,s)=>(t[s]="function",t),n);return bt(e,r),e}function As(e,n,r){if(r<B)throw new Error("invalid exponent, negatives unsupported");if(r===B)return e.ONE;if(r===N)return n;let t=e.ONE,s=n;for(;r>B;)r&N&&(t=e.mul(t,s)),s=e.sqr(s),r>>=N;return t}function It(e,n,r=!1){const t=new Array(n.length).fill(r?e.ZERO:void 0),s=n.reduce((o,l,a)=>e.is0(l)?o:(t[a]=o,e.mul(o,l)),e.ONE),i=e.inv(s);return n.reduceRight((o,l,a)=>e.is0(l)?o:(t[a]=e.mul(o,t[a]),e.mul(o,l)),i),t}function Bn(e,n){const r=(e.ORDER-N)/ie,t=e.pow(n,r),s=e.eql(t,e.ONE),i=e.eql(t,e.ZERO),o=e.eql(t,e.neg(e.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function js(e,n){n!==void 0&&hn(n);const r=n!==void 0?n:e.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class qs{ORDER;BITS;BYTES;isLE;ZERO=B;ONE=N;_lengths;_sqrt;_mod;constructor(n,r={}){if(n<=B)throw new Error("invalid field: expected ORDER > 0, got "+n);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:s,nByteLength:i}=js(n,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=n,this.BITS=s,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(n){return V(n,this.ORDER)}isValid(n){if(typeof n!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof n);return B<=n&&n<this.ORDER}is0(n){return n===B}isValidNot0(n){return!this.is0(n)&&this.isValid(n)}isOdd(n){return(n&N)===N}neg(n){return V(-n,this.ORDER)}eql(n,r){return n===r}sqr(n){return V(n*n,this.ORDER)}add(n,r){return V(n+r,this.ORDER)}sub(n,r){return V(n-r,this.ORDER)}mul(n,r){return V(n*r,this.ORDER)}pow(n,r){return As(this,n,r)}div(n,r){return V(n*Nn(r,this.ORDER),this.ORDER)}sqrN(n){return n*n}addN(n,r){return n+r}subN(n,r){return n-r}mulN(n,r){return n*r}inv(n){return Nn(n,this.ORDER)}sqrt(n){return this._sqrt||(this._sqrt=Ms(this.ORDER)),this._sqrt(this,n)}toBytes(n){return this.isLE?ht(n,this.BYTES):vn(n,this.BYTES)}fromBytes(n,r=!1){L(n);const{_lengths:t,BYTES:s,isLE:i,ORDER:o,_mod:l}=this;if(t){if(!t.includes(n.length)||n.length>s)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+n.length);const d=new Uint8Array(s);d.set(n,i?0:d.length-n.length),n=d}if(n.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+n.length);let a=i?gt(n):bn(n);if(l&&(a=V(a,o)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(n){return It(this,n)}cmov(n,r,t){return t?r:n}}function We(e,n={}){return new qs(e,n)}function xt(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const n=e.toString(2).length;return Math.ceil(n/8)}function Os(e){const n=xt(e);return n+Math.ceil(n/2)}function Cs(e,n,r=!1){L(e);const t=e.length,s=xt(n),i=Os(n);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?gt(e):bn(e),l=V(o,n-N)+N;return r?ht(l,s):vn(l,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ue=BigInt(0),oe=BigInt(1);function De(e,n){const r=n.negate();return e?r:n}function Ln(e,n){const r=It(e.Fp,n.map(t=>t.Z));return n.map((t,s)=>e.fromAffine(t.toAffine(r[s])))}function kt(e,n){if(!Number.isSafeInteger(e)||e<=0||e>n)throw new Error("invalid window size, expected [1.."+n+"], got W="+e)}function Xe(e,n){kt(e,n);const r=Math.ceil(n/e)+1,t=2**(e-1),s=2**e,i=yt(e),o=BigInt(e);return{windows:r,windowSize:t,mask:i,maxNumber:s,shiftBy:o}}function $n(e,n,r){const{windowSize:t,mask:s,maxNumber:i,shiftBy:o}=r;let l=Number(e&s),a=e>>o;l>t&&(l-=i,a+=oe);const d=n*t,h=d+Math.abs(l)-1,p=l===0,c=l<0,m=n%2!==0;return{nextN:a,offset:h,isZero:p,isNeg:c,isNegF:m,offsetF:d}}const Je=new WeakMap,Mt=new WeakMap;function en(e){return Mt.get(e)||1}function Fn(e){if(e!==ue)throw new Error("invalid wNAF")}class Hs{BASE;ZERO;Fn;bits;constructor(n,r){this.BASE=n.BASE,this.ZERO=n.ZERO,this.Fn=n.Fn,this.bits=r}_unsafeLadder(n,r,t=this.ZERO){let s=n;for(;r>ue;)r&oe&&(t=t.add(s)),s=s.double(),r>>=oe;return t}precomputeWindow(n,r){const{windows:t,windowSize:s}=Xe(r,this.bits),i=[];let o=n,l=o;for(let a=0;a<t;a++){l=o,i.push(l);for(let d=1;d<s;d++)l=l.add(o),i.push(l);o=l.double()}return i}wNAF(n,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let s=this.ZERO,i=this.BASE;const o=Xe(n,this.bits);for(let l=0;l<o.windows;l++){const{nextN:a,offset:d,isZero:h,isNeg:p,isNegF:c,offsetF:m}=$n(t,l,o);t=a,h?i=i.add(De(c,r[m])):s=s.add(De(p,r[d]))}return Fn(t),{p:s,f:i}}wNAFUnsafe(n,r,t,s=this.ZERO){const i=Xe(n,this.bits);for(let o=0;o<i.windows&&t!==ue;o++){const{nextN:l,offset:a,isZero:d,isNeg:h}=$n(t,o,i);if(t=l,!d){const p=r[a];s=s.add(h?p.negate():p)}}return Fn(t),s}getPrecomputes(n,r,t){let s=Je.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&(typeof t=="function"&&(s=t(s)),Je.set(r,s))),s}cached(n,r,t){const s=en(n);return this.wNAF(s,this.getPrecomputes(s,n,t),r)}unsafe(n,r,t,s){const i=en(n);return i===1?this._unsafeLadder(n,r,s):this.wNAFUnsafe(i,this.getPrecomputes(i,n,t),r,s)}createCache(n,r){kt(r,this.bits),Mt.set(n,r),Je.delete(n)}hasCache(n){return en(n)!==1}}function Ds(e,n,r,t){let s=n,i=e.ZERO,o=e.ZERO;for(;r>ue||t>ue;)r&oe&&(i=i.add(s)),t&oe&&(o=o.add(s)),s=s.double(),r>>=oe,t>>=oe;return{p1:i,p2:o}}function Gn(e,n,r){if(n){if(n.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ps(n),n}else return We(e,{isLE:r})}function Ns(e,n,r={},t){if(t===void 0&&(t=e==="edwards"),!n||typeof n!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const d=n[a];if(!(typeof d=="bigint"&&d>ue))throw new Error(`CURVE.${a} must be positive bigint`)}const s=Gn(n.p,r.Fp,t),i=Gn(n.n,r.Fn,t),l=["Gx","Gy","a","b"];for(const a of l)if(!s.isValid(n[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return n=Object.freeze(Object.assign({},n)),{CURVE:n,Fp:s,Fn:i}}function Bs(e,n){return function(t){const s=e(t);return{secretKey:s,publicKey:n(s)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wn=(e,n)=>(e+(e>=0?n:-n)/$s)/n;function Ls(e,n,r){const[[t,s],[i,o]]=n,l=Wn(o*e,r),a=Wn(-s*e,r);let d=e-l*t-a*i,h=-l*s-a*o;const p=d<he,c=h<he;p&&(d=-d),c&&(h=-h);const m=yt(Math.ceil(_s(r)/2))+je;if(d<he||d>=m||h<he||h>=m)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:p,k1:d,k2neg:c,k2:h}}const he=BigInt(0),je=BigInt(1),$s=BigInt(2),Ue=BigInt(3),Fs=BigInt(4);function Gs(e,n={}){const r=Ns("weierstrass",e,n),{Fp:t,Fn:s}=r;let i=r.CURVE;const{h:o,n:l}=i;bt(n,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:a}=n;if(a&&(!t.is0(i.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const d=Vs(t,s);function h(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(x,g,b){const{x:E,y:S}=g.toAffine(),k=t.toBytes(E);if(Hn(b,"isCompressed"),b){h();const R=!t.isOdd(S);return Oe(Ws(R),k)}else return Oe(Uint8Array.of(4),k,t.toBytes(S))}function c(x){L(x,void 0,"Point");const{publicKey:g,publicKeyUncompressed:b}=d,E=x.length,S=x[0],k=x.subarray(1);if(E===g&&(S===2||S===3)){const R=t.fromBytes(k);if(!t.isValid(R))throw new Error("bad point: is not on curve, wrong x");const T=w(R);let v;try{v=t.sqrt(T)}catch($){const O=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+O)}h();const _=t.isOdd(v);return(S&1)===1!==_&&(v=t.neg(v)),{x:R,y:v}}else if(E===b&&S===4){const R=t.BYTES,T=t.fromBytes(k.subarray(0,R)),v=t.fromBytes(k.subarray(R,R*2));if(!P(T,v))throw new Error("bad point: is not on curve");return{x:T,y:v}}else throw new Error(`bad point: got length ${E}, expected compressed=${g} or uncompressed=${b}`)}const m=n.toBytes||p,y=n.fromBytes||c;function w(x){const g=t.sqr(x),b=t.mul(g,x);return t.add(t.add(b,t.mul(x,i.a)),i.b)}function P(x,g){const b=t.sqr(g),E=w(x);return t.eql(b,E)}if(!P(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const q=t.mul(t.pow(i.a,Ue),Fs),z=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(q,z)))throw new Error("bad curve params: a or b");function J(x,g,b=!1){if(!t.isValid(g)||b&&t.is0(g))throw new Error(`bad point coordinate ${x}`);return g}function Re(x){if(!(x instanceof U))throw new Error("Weierstrass Point expected")}function Ie(x){if(!a||!a.basises)throw new Error("no endo");return Ls(x,a.basises,s.ORDER)}const xe=Dn((x,g)=>{const{X:b,Y:E,Z:S}=x;if(t.eql(S,t.ONE))return{x:b,y:E};const k=x.is0();g==null&&(g=k?t.ONE:t.inv(S));const R=t.mul(b,g),T=t.mul(E,g),v=t.mul(S,g);if(k)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:R,y:T}}),Ht=Dn(x=>{if(x.is0()){if(n.allowInfinityPoint&&!t.is0(x.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:b}=x.toAffine();if(!t.isValid(g)||!t.isValid(b))throw new Error("bad point: x or y not field elements");if(!P(g,b))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Tn(x,g,b,E,S){return b=new U(t.mul(b.X,x),b.Y,b.Z),g=De(E,g),b=De(S,b),g.add(b)}class U{static BASE=new U(i.Gx,i.Gy,t.ONE);static ZERO=new U(t.ZERO,t.ONE,t.ZERO);static Fp=t;static Fn=s;X;Y;Z;constructor(g,b,E){this.X=J("x",g),this.Y=J("y",b,!0),this.Z=J("z",E),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){const{x:b,y:E}=g||{};if(!g||!t.isValid(b)||!t.isValid(E))throw new Error("invalid affine point");if(g instanceof U)throw new Error("projective point not allowed");return t.is0(b)&&t.is0(E)?U.ZERO:new U(b,E,t.ONE)}static fromBytes(g){const b=U.fromAffine(y(L(g,void 0,"point")));return b.assertValidity(),b}static fromHex(g){return U.fromBytes(Y(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){return fe.createCache(this,g),b||this.multiply(Ue),this}assertValidity(){Ht(this)}hasEvenY(){const{y:g}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(g)}equals(g){Re(g);const{X:b,Y:E,Z:S}=this,{X:k,Y:R,Z:T}=g,v=t.eql(t.mul(b,T),t.mul(k,S)),_=t.eql(t.mul(E,T),t.mul(R,S));return v&&_}negate(){return new U(this.X,t.neg(this.Y),this.Z)}double(){const{a:g,b}=i,E=t.mul(b,Ue),{X:S,Y:k,Z:R}=this;let T=t.ZERO,v=t.ZERO,_=t.ZERO,I=t.mul(S,S),$=t.mul(k,k),O=t.mul(R,R),M=t.mul(S,k);return M=t.add(M,M),_=t.mul(S,R),_=t.add(_,_),T=t.mul(g,_),v=t.mul(E,O),v=t.add(T,v),T=t.sub($,v),v=t.add($,v),v=t.mul(T,v),T=t.mul(M,T),_=t.mul(E,_),O=t.mul(g,O),M=t.sub(I,O),M=t.mul(g,M),M=t.add(M,_),_=t.add(I,I),I=t.add(_,I),I=t.add(I,O),I=t.mul(I,M),v=t.add(v,I),O=t.mul(k,R),O=t.add(O,O),I=t.mul(O,M),T=t.sub(T,I),_=t.mul(O,$),_=t.add(_,_),_=t.add(_,_),new U(T,v,_)}add(g){Re(g);const{X:b,Y:E,Z:S}=this,{X:k,Y:R,Z:T}=g;let v=t.ZERO,_=t.ZERO,I=t.ZERO;const $=i.a,O=t.mul(i.b,Ue);let M=t.mul(b,k),G=t.mul(E,R),W=t.mul(S,T),ae=t.add(b,E),D=t.add(k,R);ae=t.mul(ae,D),D=t.add(M,G),ae=t.sub(ae,D),D=t.add(b,S);let Q=t.add(k,T);return D=t.mul(D,Q),Q=t.add(M,W),D=t.sub(D,Q),Q=t.add(E,S),v=t.add(R,T),Q=t.mul(Q,v),v=t.add(G,W),Q=t.sub(Q,v),I=t.mul($,D),v=t.mul(O,W),I=t.add(v,I),v=t.sub(G,I),I=t.add(G,I),_=t.mul(v,I),G=t.add(M,M),G=t.add(G,M),W=t.mul($,W),D=t.mul(O,D),G=t.add(G,W),W=t.sub(M,W),W=t.mul($,W),D=t.add(D,W),M=t.mul(G,D),_=t.add(_,M),M=t.mul(Q,D),v=t.mul(ae,v),v=t.sub(v,M),M=t.mul(ae,G),I=t.mul(Q,I),I=t.add(I,M),new U(v,_,I)}subtract(g){return this.add(g.negate())}is0(){return this.equals(U.ZERO)}multiply(g){const{endo:b}=n;if(!s.isValidNot0(g))throw new Error("invalid scalar: out of range");let E,S;const k=R=>fe.cached(this,R,T=>Ln(U,T));if(b){const{k1neg:R,k1:T,k2neg:v,k2:_}=Ie(g),{p:I,f:$}=k(T),{p:O,f:M}=k(_);S=$.add(M),E=Tn(b.beta,I,O,R,v)}else{const{p:R,f:T}=k(g);E=R,S=T}return Ln(U,[E,S])[0]}multiplyUnsafe(g){const{endo:b}=n,E=this;if(!s.isValid(g))throw new Error("invalid scalar: out of range");if(g===he||E.is0())return U.ZERO;if(g===je)return E;if(fe.hasCache(this))return this.multiply(g);if(b){const{k1neg:S,k1:k,k2neg:R,k2:T}=Ie(g),{p1:v,p2:_}=Ds(U,E,k,T);return Tn(b.beta,v,_,S,R)}else return fe.unsafe(E,g)}toAffine(g){return xe(this,g)}isTorsionFree(){const{isTorsionFree:g}=n;return o===je?!0:g?g(U,this):fe.unsafe(this,l).is0()}clearCofactor(){const{clearCofactor:g}=n;return o===je?this:g?g(U,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(g=!0){return Hn(g,"isCompressed"),this.assertValidity(),m(U,this,g)}toHex(g=!0){return C(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const _n=s.BITS,fe=new Hs(U,n.endo?Math.ceil(_n/2):_n);return U.BASE.precompute(8),U}function Ws(e){return Uint8Array.of(e?2:3)}function Vs(e,n){return{secretKey:n.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*n.BYTES}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ve={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zs={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Qs=BigInt(0),un=BigInt(2);function Ks(e){const n=Ve.p,r=BigInt(3),t=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),l=BigInt(44),a=BigInt(88),d=e*e*e%n,h=d*d*e%n,p=F(h,r,n)*h%n,c=F(p,r,n)*h%n,m=F(c,un,n)*d%n,y=F(m,s,n)*m%n,w=F(y,i,n)*y%n,P=F(w,l,n)*w%n,q=F(P,a,n)*P%n,z=F(q,l,n)*w%n,J=F(z,r,n)*h%n,Re=F(J,o,n)*y%n,Ie=F(Re,t,n)*d%n,xe=F(Ie,un,n);if(!Ne.eql(Ne.sqr(xe),e))throw new Error("Cannot find square root");return xe}const Ne=We(Ve.p,{sqrt:Ks}),pe=Gs(Ve,{Fp:Ne,endo:zs}),Vn={};function Be(e,...n){let r=Vn[e];if(r===void 0){const t=He(Ss(e));r=Oe(t,t),Vn[e]=r}return He(Oe(r,...n))}const En=e=>e.toBytes(!0).slice(1),Sn=e=>e%un===Qs;function pn(e){const{Fn:n,BASE:r}=pe,t=n.fromBytes(e),s=r.multiply(t);return{scalar:Sn(s.y)?t:n.neg(t),bytes:En(s)}}function Ut(e){const n=Ne;if(!n.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const r=n.create(e*e),t=n.create(r*e+BigInt(7));let s=n.sqrt(t);Sn(s)||(s=n.neg(s));const i=pe.fromAffine({x:e,y:s});return i.assertValidity(),i}const ve=bn;function Pt(...e){return pe.Fn.create(ve(Be("BIP0340/challenge",...e)))}function zn(e){return pn(e).bytes}function Zs(e,n,r=at(32)){const{Fn:t}=pe,s=L(e,void 0,"message"),{bytes:i,scalar:o}=pn(n),l=L(r,32,"auxRand"),a=t.toBytes(o^ve(Be("BIP0340/aux",l))),d=Be("BIP0340/nonce",a,i,s),{bytes:h,scalar:p}=pn(d),c=Pt(h,i,s),m=new Uint8Array(64);if(m.set(h,0),m.set(t.toBytes(t.create(p+c*o)),32),!At(m,s,i))throw new Error("sign: Invalid signature produced");return m}function At(e,n,r){const{Fp:t,Fn:s,BASE:i}=pe,o=L(e,64,"signature"),l=L(n,void 0,"message"),a=L(r,32,"publicKey");try{const d=Ut(ve(a)),h=ve(o.subarray(0,32));if(!t.isValidNot0(h))return!1;const p=ve(o.subarray(32,64));if(!s.isValidNot0(p))return!1;const c=Pt(s.toBytes(h),En(d),l),m=i.multiplyUnsafe(p).add(d.multiplyUnsafe(s.neg(c))),{x:y,y:w}=m.toAffine();return!(m.is0()||!Sn(w)||y!==h)}catch{return!1}}const Z=(()=>{const r=(t=at(48))=>Cs(t,Ve.n);return{keygen:Bs(r,zn),getPublicKey:zn,sign:Zs,verify:At,Point:pe,utils:{randomSecretKey:r,taggedHash:Be,lift_x:Ut,pointToBytes:En},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var se=Symbol("verified"),Ys=e=>e instanceof Object;function Xs(e){if(!Ys(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let n=0;n<e.tags.length;n++){let r=e.tags[n];if(!Array.isArray(r))return!1;for(let t=0;t<r.length;t++)if(typeof r[t]!="string")return!1}return!0}new TextDecoder("utf-8");var Js=new TextEncoder;function ye(e){try{e.indexOf("://")===-1&&(e="wss://"+e);let n=new URL(e);return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),n.pathname=n.pathname.replace(/\/+/g,"/"),n.pathname.endsWith("/")&&(n.pathname=n.pathname.slice(0,-1)),(n.port==="80"&&n.protocol==="ws:"||n.port==="443"&&n.protocol==="wss:")&&(n.port=""),n.searchParams.sort(),n.hash="",n.toString()}catch{throw new Error(`Invalid URL: ${e}`)}}var ei=class{generateSecretKey(){return Z.utils.randomSecretKey()}getPublicKey(n){return C(Z.getPublicKey(n))}finalizeEvent(n,r){const t=n;return t.pubkey=C(Z.getPublicKey(r)),t.id=nn(t),t.sig=C(Z.sign(Y(nn(t)),r)),t[se]=!0,t}verifyEvent(n){if(typeof n[se]=="boolean")return n[se];try{const r=nn(n);if(r!==n.id)return n[se]=!1,!1;const t=Z.verify(Y(n.sig),Y(r),Y(n.pubkey));return n[se]=t,t}catch{return n[se]=!1,!1}}};function ni(e){if(!Xs(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function nn(e){let n=He(Js.encode(ni(e)));return C(n)}var ze=new ei;ze.generateSecretKey;ze.getPublicKey;ze.finalizeEvent;var ti=ze.verifyEvent,ri=22242;function si(e,n){if(e.ids&&e.ids.indexOf(n.id)===-1||e.kinds&&e.kinds.indexOf(n.kind)===-1||e.authors&&e.authors.indexOf(n.pubkey)===-1)return!1;for(let r in e)if(r[0]==="#"){let t=r.slice(1),s=e[`#${t}`];if(s&&!n.tags.find(([i,o])=>i===r.slice(1)&&s.indexOf(o)!==-1))return!1}return!(e.since&&n.created_at<e.since||e.until&&n.created_at>e.until)}function ii(e,n){for(let r=0;r<e.length;r++)if(si(e[r],n))return!0;return!1}function oi(e,n){let r=n.length+3,t=e.indexOf(`"${n}":`)+r,s=e.slice(t).indexOf('"')+t+1;return e.slice(s,s+64)}function ai(e){let n=e.slice(0,22).indexOf('"EVENT"');if(n===-1)return null;let r=e.slice(n+7+1).indexOf('"');if(r===-1)return null;let t=n+7+1+r,s=e.slice(t+1,80).indexOf('"');if(s===-1)return null;let i=t+1+s;return e.slice(t+1,i)}function li(e,n){return{kind:ri,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",n]],content:""}}var jt=class extends Error{constructor(e,n){super(`Tried to send message '${e} on a closed connection to ${n}.`),this.name="SendingOnClosedConnection"}},qt=class{url;_connected=!1;onclose=null;onnotice=e=>console.debug(`NOTICE from ${this.url}: ${e}`);onauth;baseEoseTimeout=4400;publishTimeout=4400;pingFrequency=29e3;pingTimeout=2e4;resubscribeBackoff=[1e4,1e4,1e4,2e4,2e4,3e4,6e4];openSubs=new Map;enablePing;enableReconnect;idleSince=Date.now();ongoingOperations=0;reconnectTimeoutHandle;pingIntervalHandle;reconnectAttempts=0;skipReconnection=!1;connectionPromise;openCountRequests=new Map;openEventPublishes=new Map;ws;challenge;authPromise;serial=0;verifyEvent;_WebSocket;constructor(e,n){this.url=ye(e),this.verifyEvent=n.verifyEvent,this._WebSocket=n.websocketImplementation||WebSocket,this.enablePing=n.enablePing,this.enableReconnect=n.enableReconnect||!1}static async connect(e,n){const r=new qt(e,n);return await r.connect(n),r}closeAllSubscriptions(e){for(let[n,r]of this.openSubs)r.close(e);this.openSubs.clear();for(let[n,r]of this.openEventPublishes)r.reject(new Error(e));this.openEventPublishes.clear();for(let[n,r]of this.openCountRequests)r.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){const e=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},e)}handleHardClose(e){this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(e))}async connect(e){let n;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((r,t)=>{e?.timeout&&(n=setTimeout(()=>{t("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection timed out")},e.timeout)),e?.abort&&(e.abort.onabort=t);try{this.ws=new this._WebSocket(this.url)}catch(s){clearTimeout(n),t(s);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(n),this._connected=!0;const s=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const i of this.openSubs.values()){if(i.eosed=!1,s)for(let o=0;o<i.filters.length;o++)i.lastEmitted&&(i.filters[o].since=i.lastEmitted+1);i.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),r()},this.ws.onerror=()=>{clearTimeout(n),t("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection failed")},this.ws.onclose=s=>{clearTimeout(n),t(s.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(e=>{this.ws.once("pong",()=>e(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((e,n)=>{if(!this.connectionPromise)return n(new Error(`no connection to ${this.url}, can't ping`));try{const r=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),r.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(r){n(r)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(n=>setTimeout(()=>n(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(e){if(!this.connectionPromise)throw new jt(e,this.url);this.connectionPromise.then(()=>{this.ws?.send(e)})}async auth(e){const n=this.challenge;if(!n)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(r,t)=>{try{let s=await e(li(this.url,n)),i=setTimeout(()=>{let o=this.openEventPublishes.get(s.id);o&&(o.reject(new Error("auth timed out")),this.openEventPublishes.delete(s.id))},this.publishTimeout);this.openEventPublishes.set(s.id,{resolve:r,reject:t,timeout:i}),this.send('["AUTH",'+JSON.stringify(s)+"]")}catch(s){console.warn("subscribe auth function failed:",s)}}),this.authPromise)}async publish(e){this.idleSince=void 0,this.ongoingOperations++;const n=new Promise((r,t)=>{const s=setTimeout(()=>{const i=this.openEventPublishes.get(e.id);i&&(i.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:r,reject:t,timeout:s})});return this.send('["EVENT",'+JSON.stringify(e)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),n}async count(e,n){this.serial++;const r=n?.id||"count:"+this.serial,t=new Promise((s,i)=>{this.openCountRequests.set(r,{resolve:s,reject:i})});return this.send('["COUNT","'+r+'",'+JSON.stringify(e).substring(1)),t}subscribe(e,n){n.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);const r=this.prepareSubscription(e,n);return r.fire(),n.abort&&(n.abort.onabort=()=>r.close(String(n.abort.reason||"<aborted>"))),r}prepareSubscription(e,n){this.serial++;const r=n.id||(n.label?n.label+":":"sub:")+this.serial,t=new di(this,r,e,n);return this.openSubs.set(r,t),t}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,this.onclose?.(),this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}_onmessage(e){const n=e.data;if(!n)return;const r=ai(n);if(r){const t=this.openSubs.get(r);if(!t)return;const s=oi(n,"id"),i=t.alreadyHaveEvent?.(s);if(t.receivedEvent?.(this,s),i)return}try{let t=JSON.parse(n);switch(t[0]){case"EVENT":{const s=this.openSubs.get(t[1]),i=t[2];this.verifyEvent(i)&&ii(s.filters,i)?s.onevent(i):s.oninvalidevent?.(i),(!s.lastEmitted||s.lastEmitted<i.created_at)&&(s.lastEmitted=i.created_at);return}case"COUNT":{const s=t[1],i=t[2],o=this.openCountRequests.get(s);o&&(o.resolve(i.count),this.openCountRequests.delete(s));return}case"EOSE":{const s=this.openSubs.get(t[1]);if(!s)return;s.receivedEose();return}case"OK":{const s=t[1],i=t[2],o=t[3],l=this.openEventPublishes.get(s);l&&(clearTimeout(l.timeout),i?l.resolve(o):l.reject(new Error(o)),this.openEventPublishes.delete(s));return}case"CLOSED":{const s=t[1],i=this.openSubs.get(s);if(!i)return;i.closed=!0,i.close(t[2]);return}case"NOTICE":{this.onnotice(t[1]);return}case"AUTH":{this.challenge=t[1],this.onauth&&this.auth(this.onauth);return}default:{this.openSubs.get(t[1])?.oncustom?.(t);return}}}catch(t){try{const[s,i,o]=JSON.parse(n);console.warn(`[nostr] relay ${this.url} error processing message:`,t,o)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,t)}return}}},di=class{relay;id;lastEmitted;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oninvalidevent;oneose;onclose;oncustom;eoseTimeout;eoseTimeoutHandle;constructor(e,n,r,t){if(r.length===0)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=r,this.id=n,this.alreadyHaveEvent=t.alreadyHaveEvent,this.receivedEvent=t.receivedEvent,this.eoseTimeout=t.eoseTimeout||e.baseEoseTimeout,this.oneose=t.oneose,this.onclose=t.onclose,this.oninvalidevent=t.oninvalidevent,this.onevent=t.onevent||(s=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,s)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(e="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(n){if(!(n instanceof jt))throw n}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),this.onclose?.(e)}},ci=e=>(e[se]=!0,!0),ui=class{relays=new Map;seenOn=new Map;trackRelays=!1;verifyEvent;enablePing;enableReconnect;automaticallyAuth;trustedRelayURLs=new Set;onRelayConnectionFailure;onRelayConnectionSuccess;allowConnectingToRelay;maxWaitForConnection;_WebSocket;constructor(e){this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1,this.automaticallyAuth=e.automaticallyAuth,this.onRelayConnectionFailure=e.onRelayConnectionFailure,this.onRelayConnectionSuccess=e.onRelayConnectionSuccess,this.allowConnectingToRelay=e.allowConnectingToRelay,this.maxWaitForConnection=e.maxWaitForConnection||3e3}async ensureRelay(e,n){e=ye(e);let r=this.relays.get(e);if(r||(r=new qt(e,{verifyEvent:this.trustedRelayURLs.has(e)?ci:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),r.onclose=()=>{this.relays.delete(e)},this.relays.set(e,r)),this.automaticallyAuth){const t=this.automaticallyAuth(e);t&&(r.onauth=t)}try{await r.connect({timeout:n?.connectionTimeout,abort:n?.abort})}catch(t){throw this.relays.delete(e),t}return r}close(e){e.map(ye).forEach(n=>{this.relays.get(n)?.close(),this.relays.delete(n)})}subscribe(e,n,r){const t=[],s=[];for(let i=0;i<e.length;i++){const o=ye(e[i]);t.find(l=>l.url===o)||s.indexOf(o)===-1&&(s.push(o),t.push({url:o,filter:n}))}return this.subscribeMap(t,r)}subscribeMany(e,n,r){return this.subscribe(e,n,r)}subscribeMap(e,n){const r=new Map;for(const c of e){const{url:m,filter:y}=c;r.has(m)||r.set(m,[]),r.get(m).push(y)}const t=Array.from(r.entries()).map(([c,m])=>({url:c,filters:m}));this.trackRelays&&(n.receivedEvent=(c,m)=>{let y=this.seenOn.get(m);y||(y=new Set,this.seenOn.set(m,y)),y.add(c)});const s=new Set,i=[],o=[];let l=c=>{o[c]||(o[c]=!0,o.filter(m=>m).length===t.length&&(n.oneose?.(),l=()=>{}))};const a=[];let d=(c,m)=>{a[c]||(l(c),a[c]=m,a.filter(y=>y).length===t.length&&(n.onclose?.(a),d=()=>{}))};const h=c=>{if(n.alreadyHaveEvent?.(c))return!0;const m=s.has(c);return s.add(c),m},p=Promise.all(t.map(async({url:c,filters:m},y)=>{if(this.allowConnectingToRelay?.(c,["read",m])===!1){d(y,"connection skipped by allowConnectingToRelay");return}let w;try{w=await this.ensureRelay(c,{connectionTimeout:this.maxWaitForConnection<(n.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n.abort})}catch(q){this.onRelayConnectionFailure?.(c),d(y,q?.message||String(q));return}this.onRelayConnectionSuccess?.(c);let P=w.subscribe(m,{...n,oneose:()=>l(y),onclose:q=>{q.startsWith("auth-required: ")&&n.onauth?w.auth(n.onauth).then(()=>{w.subscribe(m,{...n,oneose:()=>l(y),onclose:z=>{d(y,z)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort})}).catch(z=>{d(y,`auth was required and attempted, but failed with: ${z}`)}):d(y,q)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort});i.push(P)}));return{async close(c){await p,i.forEach(m=>{m.close(c)})}}}subscribeEose(e,n,r){let t;return t=this.subscribe(e,n,{...r,oneose(){const s="closed automatically on eose";t?t.close(s):r.onclose?.(e.map(i=>s))}}),t}subscribeManyEose(e,n,r){return this.subscribeEose(e,n,r)}async querySync(e,n,r){return new Promise(async t=>{const s=[];this.subscribeEose(e,n,{...r,onevent(i){s.push(i)},onclose(i){t(s)}})})}async get(e,n,r){n.limit=1;const t=await this.querySync(e,n,r);return t.sort((s,i)=>i.created_at-s.created_at),t[0]||null}publish(e,n,r){return e.map(ye).map(async(t,s,i)=>{if(i.indexOf(t)!==s)return Promise.reject("duplicate url");if(this.allowConnectingToRelay?.(t,["write",n])===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let o;try{o=await this.ensureRelay(t,{connectionTimeout:this.maxWaitForConnection<(r?.maxWait||0)?Math.max(r.maxWait*.8,r.maxWait-1e3):this.maxWaitForConnection,abort:r?.abort})}catch(l){return this.onRelayConnectionFailure?.(t),"connection failure: "+String(l)}return o.publish(n).catch(async l=>{if(l instanceof Error&&l.message.startsWith("auth-required: ")&&r?.onauth)return await o.auth(r.onauth),o.publish(n);throw l}).then(l=>{if(this.trackRelays){let a=this.seenOn.get(n.id);a||(a=new Set,this.seenOn.set(n.id,a)),a.add(o)}return l})})}listConnectionStatus(){const e=new Map;return this.relays.forEach((n,r)=>e.set(r,n.connected)),e}destroy(){this.relays.forEach(e=>e.close()),this.relays=new Map}pruneIdleRelays(e=1e4){const n=[];for(const[r,t]of this.relays)t.idleSince&&Date.now()-t.idleSince>=e&&(this.relays.delete(r),n.push(r),t.close());return n}},Ot;try{Ot=WebSocket}catch{}var pi=class extends ui{constructor(e){super({verifyEvent:ti,websocketImplementation:Ot,maxWaitForConnection:3e3,...e})}},le=Symbol("verified"),fi=e=>e instanceof Object;function mi(e){if(!fi(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let n=0;n<e.tags.length;n++){let r=e.tags[n];if(!Array.isArray(r))return!1;for(let t=0;t<r.length;t++)if(typeof r[t]!="string")return!1}return!0}new TextDecoder("utf-8");var gi=new TextEncoder,hi=class{generateSecretKey(){return Z.utils.randomSecretKey()}getPublicKey(e){return C(Z.getPublicKey(e))}finalizeEvent(e,n){const r=e;return r.pubkey=C(Z.getPublicKey(n)),r.id=tn(r),r.sig=C(Z.sign(Y(tn(r)),n)),r[le]=!0,r}verifyEvent(e){if(typeof e[le]=="boolean")return e[le];try{const n=tn(e);if(n!==e.id)return e[le]=!1,!1;const r=Z.verify(Y(e.sig),Y(n),Y(e.pubkey));return e[le]=r,r}catch{return e[le]=!1,!1}}};function yi(e){if(!mi(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function tn(e){let n=He(gi.encode(yi(e)));return C(n)}var Qe=new hi;Qe.generateSecretKey;Qe.getPublicKey;Qe.finalizeEvent;var bi=Qe.verifyEvent;const vi=8e3;function wi(e){return typeof e=="number"&&gn.includes(e)}function Ei(e){try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function Si(e){const n=[];for(const r of e??[])try{const t=new URL(r);if(t.protocol!=="ws:"&&t.protocol!=="wss:")continue;n.push(t.href)}catch{}return[...new Set(n)]}function Ti(e){const n=ps(e.trim());if(n.type!=="nevent"&&n.type!=="naddr")throw new Error("Enter a NIP-19 nevent or naddr for a NIP-5D napplet manifest event");const r=Si(n.data.relays);if(r.length===0)throw new Error("The pointer does not include relay hints; include at least one relay in the nevent/naddr");if(n.type==="nevent"){if(n.data.kind!==void 0&&!wi(n.data.kind))throw new Error(`nevent points at kind ${n.data.kind}, not a NIP-5D napplet manifest kind`);return{type:"nevent",relays:r,filter:{ids:[n.data.id],kinds:n.data.kind===void 0?[...gn]:[n.data.kind],authors:n.data.author?[n.data.author]:void 0,limit:1}}}if(n.data.kind!==ce)throw new Error(`naddr kind ${n.data.kind} is not the named napplet kind ${ce}`);return{type:"naddr",relays:r,filter:{kinds:[ce],authors:[n.data.pubkey],"#d":[n.data.identifier],limit:1}}}function _i(e){return{id:e.id,pubkey:e.pubkey,kind:e.kind,tags:e.tags,content:e.content}}async function Ri(e){const n=typeof e=="string"?new TextEncoder().encode(e):e,r=new Uint8Array(n.byteLength);r.set(n);const t=await crypto.subtle.digest("SHA-256",r.buffer);return[...new Uint8Array(t)].map(s=>s.toString(16).padStart(2,"0")).join("")}function Ii(e){const n=[];for(const r of e.tags)if(!(r[0]!=="server"||!r[1]))try{const t=new URL(r[1]);(t.protocol==="http:"||t.protocol==="https:")&&n.push(t.href)}catch{}return[...new Set(n)]}function xi(e,n){const r=e.endsWith("/")?e:`${e}/`;return new URL(n,r).href}async function ki(e,n=fetch){const r=Ge(e);if(!r.ok)throw new Error(r.errors.map(o=>o.message).join("; "));const t=e.tags.find(o=>o[0]==="x")[1],s=Ii(e);if(s.length===0)throw new Error("Manifest does not include any usable Blossom server hints");const i=[];for(const o of s){const l=xi(o,t);try{const a=await n(l,{mode:"cors"});if(!a.ok){i.push(`${l}: HTTP ${a.status}`);continue}const d=new Uint8Array(await a.arrayBuffer()),h=await Ri(d);if(h!==t){i.push(`${l}: sha256 ${h} did not match manifest ${t}`);continue}return new TextDecoder().decode(d)}catch(a){i.push(`${l}: ${a instanceof Error?a.message:String(a)}`)}}throw new Error(`Unable to fetch verified /index.html from Blossom servers: ${i.join("; ")}`)}async function Mi(e,n){try{const t=await(await n(e,{mode:"cors"})).text();return{source:"url",input:e,label:e,bootUrl:e,html:t,fetched:!0,manifestEvent:null}}catch{return{source:"url",input:e,label:e,bootUrl:e,html:"",fetched:!1,manifestEvent:null}}}async function Ui(e,n){const r=Ti(e),t=!n.pool,s=n.pool??new pi;try{const i=await s.get(r.relays,{...r.filter},{maxWait:n.maxRelayWaitMs??vi});if(!i)throw new Error("No matching napplet manifest event was found on the pointer relay hints");if(!bi(i))throw new Error("Resolved manifest event signature is invalid");const o=_i(i),l=Ge(o);if(!l.ok)throw new Error(`Resolved event is not a valid NIP-5D napplet manifest: ${l.errors[0]?.message}`);const a=await ki(o,n.fetcher??fetch),d=(n.createObjectUrl??URL.createObjectURL)(new Blob([a],{type:"text/html;charset=utf-8"})),h=()=>(n.revokeObjectUrl??URL.revokeObjectURL)(d);return{source:"nostr",input:e,label:o.id??e,bootUrl:d,html:a,fetched:!0,manifestEvent:o,revoke:h}}finally{t&&s.destroy()}}async function Pi(e,n={}){const r=e.trim();if(!r)throw new Error("Enter a NIP-19 nevent/naddr, or an HTTP URL for local dev");return Ei(r)?Mi(r,n.fetcher??fetch):Ui(r,n)}const Ai=`"use strict";
|
|
10
|
+
${s}`}function Bs(e,n,s,t){const r=`<base href="${Ns(n)}">`,i=Ds(s,t).replace(/<\/script/gi,"<\\/script"),o=`<script>${Hs()}<\/script><script>${i}<\/script>`,l=/<head(?:\s[^>]*)?>/i.exec(e);if(l){const a=l.index+l[0].length;return`${e.slice(0,a)}${r}${o}${e.slice(a)}`}return`${r}${o}${e}`}function Ls(e){if(!e.startsWith("data:"))return null;const n=e.indexOf(",");if(n<0)return"";const s=e.slice(0,n),t=e.slice(n+1);return s.endsWith(";base64")?atob(t):decodeURIComponent(t)}async function $s(e){if(e==="about:blank")return"<!doctype html><html><head></head><body></body></html>";const n=Ls(e);if(n!==null)return n;const s=await fetch(e);if(!s.ok)throw new Error(`Failed to fetch napplet HTML: ${s.status} ${s.statusText}`);return s.text()}async function An(e,n,s,t){const r=Os({domains:e}),i=s.createElement("iframe");i.setAttribute("sandbox",n.allowSameOrigin?"allow-scripts allow-same-origin":"allow-scripts"),i.setAttribute("allow","gamepad 'none'"),i.setAttribute("aria-hidden","true"),i.style.position="absolute",i.style.width="1px",i.style.height="1px",i.style.left="-9999px";let o=null,l=!1;const a=p=>{if(p.source!==i.contentWindow)return;const d=p.data;if(d&&typeof d=="object"&&d.type===ot){l=d.installed===!0;return}if(d&&typeof d=="object"&&d.type===it){o=`napplet boot error: ${String(d.reason??"unknown error")}`;return}const f=r.handle(p.data),y=p.source;for(const w of f)y?.postMessage(w,"*")};let c=!1;const h=new Promise(p=>{i.addEventListener("load",()=>{c=!0,p()},{once:!0})});t.addEventListener("message",a);try{const p=n.html??await $s(n.url);i.srcdoc=Bs(p,n.url,e,n.runtimePreludeSource),(s.body??s.documentElement).appendChild(i)}catch(p){o=p instanceof Error?p.message:String(p)}if(!o){const p=Symbol("timeout");await Promise.race([h.then(()=>"loaded"),Un(n.readyTimeoutMs).then(()=>p)])===p||!c?o=`napplet did not boot (iframe did not load within ${n.readyTimeoutMs}ms; a conformant napplet must run under sandbox="allow-scripts" without allow-same-origin)`:await Un(n.settleMs)}t.removeEventListener("message",a);try{i.remove()}catch{}return{installedGlobal:l,bootError:o,emitted:[...r.records]}}async function Fs(e){const n=e.document??document,s=e.window??window,t={url:e.url,html:e.html,readyTimeoutMs:e.readyTimeoutMs??5e3,settleMs:e.settleMs,allowSameOrigin:e.allowSameOrigin??!1,runtimePreludeSource:e.runtimePreludeSource},r=e.domains??$e,i=e.maturity?Bt({...e.maturity,candidates:r}).domains:r,o=await An(i,t,n,s);let l=null;{const a=await An([],t,n,s);l={bootError:a.bootError,emitted:a.emitted}}return{installedGlobal:o.installedGlobal,bootError:o.bootError,emitted:o.emitted,degraded:l}}var Ws=e=>({status:"pass",detail:e}),zs=(e,n)=>({status:"fail",detail:e,diagnostics:n}),Gs=e=>({status:"skip",detail:e}),P={pass:Ws,fail:zs,skip:Gs};function Vs(e,n){const s=ze(e.manifestEvent);return[...s.errors,...s.warnings].filter(t=>n.includes(t.code))}function fe(e,n,s,t="error"){return{id:e,area:"manifest",severity:t,title:n,run:r=>{if(!r.manifestEvent)return P.skip("No NIP-5D manifest event was resolved");const i=Vs(r,s);return i.length?P.fail(i[0].message,i):P.pass()}}}var Qs=[fe("manifest/event-kind","Resolved event is a NIP-5D napplet manifest",["invalid-napplet-kind","missing-d-tag","unexpected-d-tag"]),fe("manifest/index-html","Manifest declares a hashed /index.html",["invalid-artifact-hash","missing-description","invalid-metadata"]),fe("manifest/requires","R/O tags name bare NAP domains",["invalid-required-nap","invalid-optional-nap"]),fe("manifest/requires-known","R/O domains are in this toolchain registry (advisory)",["unknown-required-nap"],"warning"),fe("manifest/media-usable","Icon, screenshots, preview and source pins are usable (advisory)",["invalid-icon","invalid-presentation-media","unused-source-commit"],"warning"),{id:"boot/sandbox-allow-scripts",area:"boot",severity:"error",title:"Runs under allow-scripts without allow-same-origin",run:e=>e.sandbox.allowScripts?e.sandbox.allowSameOrigin?P.fail("Napplet relied on allow-same-origin, which a shell must not grant"):P.pass():P.fail("Napplet was not loaded with allow-scripts")},{id:"boot/installs-global",area:"boot",severity:"error",title:"Runs after runtime-injected window.napplet is installed",run:e=>e.installedGlobal?P.pass():P.fail("runtime did not inject window.napplet before load")},{id:"boot/no-boot-error",area:"boot",severity:"error",title:"Boots without an uncaught error",run:e=>e.bootError?P.fail(e.bootError):P.pass()},{id:"boot/no-forbidden-globals",area:"boot",severity:"error",title:"Does not access forbidden browser authority surfaces",run:e=>e.forbiddenGlobals.length?P.fail(`Accessed forbidden surface(s): ${e.forbiddenGlobals.join(", ")}`,e.forbiddenGlobals):P.pass()},{id:"wire/envelope-well-formed",area:"wire",severity:"error",title:"Every emitted envelope is well-formed",run:e=>{if(e.emitted.length===0)return P.skip("Napplet emitted no envelopes");const n=e.emitted.filter(t=>!t.verdict.ok);if(n.length===0)return P.pass(`${e.emitted.length} envelope(s) valid`);const s=n.map(t=>({envelope:t.envelope,errors:t.verdict.errors}));return P.fail(`${n.length}/${e.emitted.length} emitted envelope(s) invalid`,s)}},{id:"degrade/domain-absence",area:"degradation",severity:"error",title:"Does not crash when no NAP domains are injected",run:e=>e.degraded?e.degraded.bootError?P.fail(`Crashed with no injected domains: ${e.degraded.bootError}`):P.pass():P.skip("Host did not run the degraded (no-capabilities) pass")},{id:"lifecycle/clean-teardown",area:"lifecycle",severity:"warning",title:"Tears down listeners on unload",run:e=>e.lifecycle?e.lifecycle.listenerLeak?P.fail("Message listeners remained after unload"):P.pass():P.skip("Lifecycle not measured")}];function Ks(e,n={}){const s=n.now??(()=>Date.now()),t=n.checks??Qs,r=s(),i=t.map(a=>{const c=a.run(e);return{id:a.id,area:a.area,severity:a.severity,title:a.title,status:c.status,detail:c.detail,diagnostics:c.diagnostics}}),o={total:i.length,passed:i.filter(a=>a.status==="pass").length,failed:i.filter(a=>a.status==="fail").length,skipped:i.filter(a=>a.status==="skip").length,errors:i.filter(a=>a.status==="fail"&&a.severity==="error").length,warnings:i.filter(a=>a.status==="fail"&&a.severity==="warning").length};return{napplet:e.manifestEvent?tt(e.manifestEvent):void 0,startedAt:r,finishedAt:s(),checks:i,summary:o,ok:o.errors===0}}function Ys(e,n){const s=r=>e.tags.find(i=>i[0]===r)?.[1],t=e.tags.filter(r=>r[0]==="server").map(r=>r[1]).filter(Boolean);return[["event",e.id],["kind",e.kind],["d",s("d")],["name",tt(e)],["requires",n.requires.join(", ")],["optional",n.optional.join(", ")],["artifact hash (x)",s("x")],["servers",t.join(", ")]]}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Zs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function yn(e,n=""){if(!Number.isSafeInteger(e)||e<0){const s=n&&`"${n}" `;throw new Error(`${s}expected integer >= 0, got ${e}`)}}function L(e,n,s=""){const t=Zs(e),r=e?.length,i=n!==void 0;if(!t||i&&r!==n){const o=s&&`"${s}" `,l=i?` of length ${n}`:"",a=t?`length=${r}`:`type=${typeof e}`;throw new Error(o+"expected Uint8Array"+l+", got "+a)}return e}function Pn(e,n=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(n&&e.finished)throw new Error("Hash#digest() has already been called")}function Xs(e,n){L(e,void 0,"digestInto() output");const s=n.outputLen;if(e.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function an(...e){for(let n=0;n<e.length;n++)e[n].fill(0)}function Ze(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function K(e,n){return e<<32-n|e>>>n}const at=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Js=Array.from({length:256},(e,n)=>n.toString(16).padStart(2,"0"));function C(e){if(L(e),at)return e.toHex();let n="";for(let s=0;s<e.length;s++)n+=Js[e[s]];return n}const X={_0:48,_9:57,A:65,F:70,a:97,f:102};function jn(e){if(e>=X._0&&e<=X._9)return e-X._0;if(e>=X.A&&e<=X.F)return e-(X.A-10);if(e>=X.a&&e<=X.f)return e-(X.a-10)}function Z(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(at)return Uint8Array.fromHex(e);const n=e.length,s=n/2;if(n%2)throw new Error("hex string expected, got unpadded hex of length "+n);const t=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=jn(e.charCodeAt(i)),l=jn(e.charCodeAt(i+1));if(o===void 0||l===void 0){const a=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+i)}t[r]=o*16+l}return t}function Ce(...e){let n=0;for(let t=0;t<e.length;t++){const r=e[t];L(r),n+=r.length}const s=new Uint8Array(n);for(let t=0,r=0;t<e.length;t++){const i=e[t];s.set(i,r),r+=i.length}return s}function er(e,n={}){const s=(r,i)=>e(i).update(r).digest(),t=e(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=r=>e(r),Object.assign(s,n),Object.freeze(s)}function lt(e=32){const n=typeof globalThis=="object"?globalThis.crypto:null;if(typeof n?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return n.getRandomValues(new Uint8Array(e))}const nr=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function dt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ct(e,n){return Array.isArray(n)?n.length===0?!0:e?n.every(s=>typeof s=="string"):n.every(s=>Number.isSafeInteger(s)):!1}function tr(e){if(typeof e!="function")throw new Error("function expected");return!0}function Se(e,n){if(typeof n!="string")throw new Error(`${e}: string expected`);return!0}function ut(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function ln(e){if(!Array.isArray(e))throw new Error("array expected")}function pt(e,n){if(!ct(!0,n))throw new Error(`${e}: array of strings expected`)}function mt(e,n){if(!ct(!1,n))throw new Error(`${e}: array of numbers expected`)}function sr(...e){const n=i=>i,s=(i,o)=>l=>i(o(l)),t=e.map(i=>i.encode).reduceRight(s,n),r=e.map(i=>i.decode).reduce(s,n);return{encode:t,decode:r}}function rr(e){const n=typeof e=="string"?e.split(""):e,s=n.length;pt("alphabet",n);const t=new Map(n.map((r,i)=>[r,i]));return{encode:r=>(ln(r),r.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=s)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return n[i]})),decode:r=>(ln(r),r.map(i=>{Se("alphabet.decode",i);const o=t.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${e}`);return o}))}}function ir(e=""){return Se("join",e),{encode:n=>(pt("join.decode",n),n.join(e)),decode:n=>(Se("join.decode",n),n.split(e))}}const ft=(e,n)=>n===0?e:ft(n,e%n),Ne=(e,n)=>e+(n-ft(e,n)),Pe=(()=>{let e=[];for(let n=0;n<40;n++)e.push(2**n);return e})();function dn(e,n,s,t){if(ln(e),n<=0||n>32)throw new Error(`convertRadix2: wrong from=${n}`);if(s<=0||s>32)throw new Error(`convertRadix2: wrong to=${s}`);if(Ne(n,s)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${s} carryBits=${Ne(n,s)}`);let r=0,i=0;const o=Pe[n],l=Pe[s]-1,a=[];for(const c of e){if(ut(c),c>=o)throw new Error(`convertRadix2: invalid data word=${c} from=${n}`);if(r=r<<n|c,i+n>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${n}`);for(i+=n;i>=s;i-=s)a.push((r>>i-s&l)>>>0);const h=Pe[i];if(h===void 0)throw new Error("invalid carry");r&=h-1}if(r=r<<s-i&l,!t&&i>=n)throw new Error("Excess padding");if(!t&&r>0)throw new Error(`Non-zero padding: ${r}`);return t&&i>0&&a.push(r>>>0),a}function or(e,n=!1){if(ut(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Ne(8,e)>32||Ne(e,8)>32)throw new Error("radix2: carry overflow");return{encode:s=>{if(!dt(s))throw new Error("radix2.encode input should be Uint8Array");return dn(Array.from(s),8,e,!n)},decode:s=>(mt("radix2.decode",s),Uint8Array.from(dn(s,e,8,n)))}}function On(e){return tr(e),function(...n){try{return e.apply(null,n)}catch{}}}const cn=sr(rr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ir("")),qn=[996825010,642813549,513874426,1027748829,705979059];function ge(e){const n=e>>25;let s=(e&33554431)<<5;for(let t=0;t<qn.length;t++)(n>>t&1)===1&&(s^=qn[t]);return s}function Cn(e,n,s=1){const t=e.length;let r=1;for(let i=0;i<t;i++){const o=e.charCodeAt(i);if(o<33||o>126)throw new Error(`Invalid prefix (${e})`);r=ge(r)^o>>5}r=ge(r);for(let i=0;i<t;i++)r=ge(r)^e.charCodeAt(i)&31;for(let i of n)r=ge(r)^i;for(let i=0;i<6;i++)r=ge(r);return r^=s,cn.encode(dn([r%Pe[30]],30,5,!1))}function ar(e){const n=e==="bech32"?1:734539939,s=or(5),t=s.decode,r=s.encode,i=On(t);function o(p,d,f=90){Se("bech32.encode prefix",p),dt(d)&&(d=Array.from(d)),mt("bech32.encode",d);const y=p.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);const w=y+7+d.length;if(f!==!1&&w>f)throw new TypeError(`Length ${w} exceeds limit ${f}`);const A=p.toLowerCase(),O=Cn(A,d,n);return`${A}1${cn.encode(d)}${O}`}function l(p,d=90){Se("bech32.decode input",p);const f=p.length;if(f<8||d!==!1&&f>d)throw new TypeError(`invalid string length: ${f} (${p}). Expected (8..${d})`);const y=p.toLowerCase();if(p!==y&&p!==p.toUpperCase())throw new Error("String must be lowercase or uppercase");const w=y.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const A=y.slice(0,w),O=y.slice(w+1);if(O.length<6)throw new Error("Data must be at least 6 characters long");const V=cn.decode(O).slice(0,-6),J=Cn(A,V,n);if(!O.endsWith(J))throw new Error(`Invalid checksum in ${p}: expected "${J}"`);return{prefix:A,words:V}}const a=On(l);function c(p){const{prefix:d,words:f}=l(p,!1);return{prefix:d,words:f,bytes:t(f)}}function h(p,d){return o(p,r(d))}return{encode:o,decode:l,encodeFromBytes:h,decodeToBytes:c,decodeUnsafe:a,fromWords:t,fromWordsUnsafe:i,toWords:r}}const Nn=ar("bech32");var Me=new TextDecoder("utf-8");new TextEncoder;var lr=5e3;function dr(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),cr(e)}catch{return{type:"invalid",data:null}}}function cr(e){let{prefix:n,words:s}=Nn.decode(e,lr),t=new Uint8Array(Nn.fromWords(s));switch(n){case"nprofile":{let r=Xe(t);if(!r[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(r[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:C(r[0][0]),relays:r[1]?r[1].map(i=>Me.decode(i)):[]}}}case"nevent":{let r=Xe(t);if(!r[0]?.[0])throw new Error("missing TLV 0 for nevent");if(r[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(r[2]&&r[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(r[3]&&r[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:C(r[0][0]),relays:r[1]?r[1].map(i=>Me.decode(i)):[],author:r[2]?.[0]?C(r[2][0]):void 0,kind:r[3]?.[0]?parseInt(C(r[3][0]),16):void 0}}}case"naddr":{let r=Xe(t);if(!r[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!r[2]?.[0])throw new Error("missing TLV 2 for naddr");if(r[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!r[3]?.[0])throw new Error("missing TLV 3 for naddr");if(r[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Me.decode(r[0][0]),pubkey:C(r[2][0]),kind:parseInt(C(r[3][0]),16),relays:r[1]?r[1].map(i=>Me.decode(i)):[]}}}case"nsec":return{type:n,data:t};case"npub":case"note":return{type:n,data:C(t)};default:throw new Error(`unknown prefix ${n}`)}}function Xe(e){let n={},s=e;for(;s.length>0;){let t=s[0],r=s[1],i=s.slice(2,2+r);if(s=s.slice(2+r),i.length<r)throw new Error(`not enough data to read on TLV ${t}`);n[t]=n[t]||[],n[t].push(i)}return n}function ur(e,n,s){return e&n^~e&s}function pr(e,n,s){return e&n^e&s^n&s}class mr{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(n,s,t,r){this.blockLen=n,this.outputLen=s,this.padOffset=t,this.isLE=r,this.buffer=new Uint8Array(n),this.view=Ze(this.buffer)}update(n){Pn(this),L(n);const{view:s,buffer:t,blockLen:r}=this,i=n.length;for(let o=0;o<i;){const l=Math.min(r-this.pos,i-o);if(l===r){const a=Ze(n);for(;r<=i-o;o+=r)this.process(a,o);continue}t.set(n.subarray(o,o+l),this.pos),this.pos+=l,o+=l,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=n.length,this.roundClean(),this}digestInto(n){Pn(this),Xs(n,this),this.finished=!0;const{buffer:s,view:t,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,an(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(t,0),o=0);for(let p=o;p<r;p++)s[p]=0;t.setBigUint64(r-8,BigInt(this.length*8),i),this.process(t,0);const l=Ze(n),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const c=a/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<c;p++)l.setUint32(4*p,h[p],i)}digest(){const{buffer:n,outputLen:s}=this;this.digestInto(n);const t=n.slice(0,s);return this.destroy(),t}_cloneInto(n){n||=new this.constructor,n.set(...this.get());const{blockLen:s,buffer:t,length:r,finished:i,destroyed:o,pos:l}=this;return n.destroyed=o,n.finished=i,n.length=r,n.pos=l,r%s&&n.buffer.set(t),n}clone(){return this._cloneInto()}}const ee=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),fr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ne=new Uint32Array(64);class gr extends mr{constructor(n){super(64,n,8,!1)}get(){const{A:n,B:s,C:t,D:r,E:i,F:o,G:l,H:a}=this;return[n,s,t,r,i,o,l,a]}set(n,s,t,r,i,o,l,a){this.A=n|0,this.B=s|0,this.C=t|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=l|0,this.H=a|0}process(n,s){for(let p=0;p<16;p++,s+=4)ne[p]=n.getUint32(s,!1);for(let p=16;p<64;p++){const d=ne[p-15],f=ne[p-2],y=K(d,7)^K(d,18)^d>>>3,w=K(f,17)^K(f,19)^f>>>10;ne[p]=w+ne[p-7]+y+ne[p-16]|0}let{A:t,B:r,C:i,D:o,E:l,F:a,G:c,H:h}=this;for(let p=0;p<64;p++){const d=K(l,6)^K(l,11)^K(l,25),f=h+d+ur(l,a,c)+fr[p]+ne[p]|0,w=(K(t,2)^K(t,13)^K(t,22))+pr(t,r,i)|0;h=c,c=a,a=l,l=o+f|0,o=i,i=r,r=t,t=f+w|0}t=t+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,l=l+this.E|0,a=a+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(t,r,i,o,l,a,c,h)}roundClean(){an(ne)}destroy(){this.set(0,0,0,0,0,0,0,0),an(this.buffer)}}class hr extends gr{A=ee[0]|0;B=ee[1]|0;C=ee[2]|0;D=ee[3]|0;E=ee[4]|0;F=ee[5]|0;G=ee[6]|0;H=ee[7]|0;constructor(){super(32)}}const He=er(()=>new hr,nr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const bn=BigInt(0),un=BigInt(1);function Hn(e,n=""){if(typeof e!="boolean"){const s=n&&`"${n}" `;throw new Error(s+"expected boolean, got type="+typeof e)}return e}function yr(e){if(typeof e=="bigint"){if(!wr(e))throw new Error("positive bigint expected, got "+e)}else yn(e);return e}function gt(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?bn:BigInt("0x"+e)}function vn(e){return gt(C(e))}function ht(e){return gt(C(br(L(e)).reverse()))}function wn(e,n){yn(n),e=yr(e);const s=Z(e.toString(16).padStart(n*2,"0"));if(s.length!==n)throw new Error("number too large");return s}function yt(e,n){return wn(e,n).reverse()}function br(e){return Uint8Array.from(e)}function vr(e){return Uint8Array.from(e,(n,s)=>{const t=n.charCodeAt(0);if(n.length!==1||t>127)throw new Error(`string contains non-ASCII character "${e[s]}" with code ${t} at position ${s}`);return t})}const wr=e=>typeof e=="bigint"&&bn<=e;function Er(e){let n;for(n=0;e>bn;e>>=un,n+=1);return n}const bt=e=>(un<<BigInt(e))-un;function vt(e,n={},s={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function t(i,o,l){const a=e[i];if(l&&a===void 0)return;const c=typeof a;if(c!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}const r=(i,o)=>Object.entries(i).forEach(([l,a])=>t(l,a,o));r(n,!1),r(s,!0)}function Dn(e){const n=new WeakMap;return(s,...t)=>{const r=n.get(s);if(r!==void 0)return r;const i=e(s,...t);return n.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const B=BigInt(0),D=BigInt(1),ie=BigInt(2),wt=BigInt(3),Et=BigInt(4),St=BigInt(5),Sr=BigInt(7),Rt=BigInt(8),Rr=BigInt(9),Tt=BigInt(16);function G(e,n){const s=e%n;return s>=B?s:n+s}function F(e,n,s){let t=e;for(;n-- >B;)t*=t,t%=s;return t}function Bn(e,n){if(e===B)throw new Error("invert: expected non-zero number");if(n<=B)throw new Error("invert: expected positive modulus, got "+n);let s=G(e,n),t=n,r=B,i=D;for(;s!==B;){const l=t/s,a=t%s,c=r-i*l;t=s,s=a,r=i,i=c}if(t!==D)throw new Error("invert: does not exist");return G(r,n)}function En(e,n,s){if(!e.eql(e.sqr(n),s))throw new Error("Cannot find square root")}function _t(e,n){const s=(e.ORDER+D)/Et,t=e.pow(n,s);return En(e,t,n),t}function Tr(e,n){const s=(e.ORDER-St)/Rt,t=e.mul(n,ie),r=e.pow(t,s),i=e.mul(n,r),o=e.mul(e.mul(i,ie),r),l=e.mul(i,e.sub(o,e.ONE));return En(e,l,n),l}function _r(e){const n=Ge(e),s=kt(e),t=s(n,n.neg(n.ONE)),r=s(n,t),i=s(n,n.neg(t)),o=(e+Sr)/Tt;return(l,a)=>{let c=l.pow(a,o),h=l.mul(c,t);const p=l.mul(c,r),d=l.mul(c,i),f=l.eql(l.sqr(h),a),y=l.eql(l.sqr(p),a);c=l.cmov(c,h,f),h=l.cmov(d,p,y);const w=l.eql(l.sqr(h),a),A=l.cmov(c,h,w);return En(l,A,a),A}}function kt(e){if(e<wt)throw new Error("sqrt is not defined for small field");let n=e-D,s=0;for(;n%ie===B;)n/=ie,s++;let t=ie;const r=Ge(e);for(;Ln(r,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return _t;let i=r.pow(t,n);const o=(n+D)/ie;return function(a,c){if(a.is0(c))return c;if(Ln(a,c)!==1)throw new Error("Cannot find square root");let h=s,p=a.mul(a.ONE,i),d=a.pow(c,n),f=a.pow(c,o);for(;!a.eql(d,a.ONE);){if(a.is0(d))return a.ZERO;let y=1,w=a.sqr(d);for(;!a.eql(w,a.ONE);)if(y++,w=a.sqr(w),y===h)throw new Error("Cannot find square root");const A=D<<BigInt(h-y-1),O=a.pow(p,A);h=y,p=a.sqr(O),d=a.mul(d,p),f=a.mul(f,O)}return f}}function kr(e){return e%Et===wt?_t:e%Rt===St?Tr:e%Tt===Rr?_r(e):kt(e)}const Ir=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xr(e){const n={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Ir.reduce((t,r)=>(t[r]="function",t),n);return vt(e,s),e}function Mr(e,n,s){if(s<B)throw new Error("invalid exponent, negatives unsupported");if(s===B)return e.ONE;if(s===D)return n;let t=e.ONE,r=n;for(;s>B;)s&D&&(t=e.mul(t,r)),r=e.sqr(r),s>>=D;return t}function It(e,n,s=!1){const t=new Array(n.length).fill(s?e.ZERO:void 0),r=n.reduce((o,l,a)=>e.is0(l)?o:(t[a]=o,e.mul(o,l)),e.ONE),i=e.inv(r);return n.reduceRight((o,l,a)=>e.is0(l)?o:(t[a]=e.mul(o,t[a]),e.mul(o,l)),i),t}function Ln(e,n){const s=(e.ORDER-D)/ie,t=e.pow(n,s),r=e.eql(t,e.ONE),i=e.eql(t,e.ZERO),o=e.eql(t,e.neg(e.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function Ur(e,n){n!==void 0&&yn(n);const s=n!==void 0?n:e.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ar{ORDER;BITS;BYTES;isLE;ZERO=B;ONE=D;_lengths;_sqrt;_mod;constructor(n,s={}){if(n<=B)throw new Error("invalid field: expected ORDER > 0, got "+n);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=s.allowedLengths?.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:r,nByteLength:i}=Ur(n,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=n,this.BITS=r,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(n){return G(n,this.ORDER)}isValid(n){if(typeof n!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof n);return B<=n&&n<this.ORDER}is0(n){return n===B}isValidNot0(n){return!this.is0(n)&&this.isValid(n)}isOdd(n){return(n&D)===D}neg(n){return G(-n,this.ORDER)}eql(n,s){return n===s}sqr(n){return G(n*n,this.ORDER)}add(n,s){return G(n+s,this.ORDER)}sub(n,s){return G(n-s,this.ORDER)}mul(n,s){return G(n*s,this.ORDER)}pow(n,s){return Mr(this,n,s)}div(n,s){return G(n*Bn(s,this.ORDER),this.ORDER)}sqrN(n){return n*n}addN(n,s){return n+s}subN(n,s){return n-s}mulN(n,s){return n*s}inv(n){return Bn(n,this.ORDER)}sqrt(n){return this._sqrt||(this._sqrt=kr(this.ORDER)),this._sqrt(this,n)}toBytes(n){return this.isLE?yt(n,this.BYTES):wn(n,this.BYTES)}fromBytes(n,s=!1){L(n);const{_lengths:t,BYTES:r,isLE:i,ORDER:o,_mod:l}=this;if(t){if(!t.includes(n.length)||n.length>r)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+n.length);const c=new Uint8Array(r);c.set(n,i?0:c.length-n.length),n=c}if(n.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+n.length);let a=i?ht(n):vn(n);if(l&&(a=G(a,o)),!s&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(n){return It(this,n)}cmov(n,s,t){return t?s:n}}function Ge(e,n={}){return new Ar(e,n)}function xt(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const n=e.toString(2).length;return Math.ceil(n/8)}function Pr(e){const n=xt(e);return n+Math.ceil(n/2)}function jr(e,n,s=!1){L(e);const t=e.length,r=xt(n),i=Pr(n);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?ht(e):vn(e),l=G(o,n-D)+D;return s?yt(l,r):wn(l,r)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ue=BigInt(0),oe=BigInt(1);function De(e,n){const s=n.negate();return e?s:n}function $n(e,n){const s=It(e.Fp,n.map(t=>t.Z));return n.map((t,r)=>e.fromAffine(t.toAffine(s[r])))}function Mt(e,n){if(!Number.isSafeInteger(e)||e<=0||e>n)throw new Error("invalid window size, expected [1.."+n+"], got W="+e)}function Je(e,n){Mt(e,n);const s=Math.ceil(n/e)+1,t=2**(e-1),r=2**e,i=bt(e),o=BigInt(e);return{windows:s,windowSize:t,mask:i,maxNumber:r,shiftBy:o}}function Fn(e,n,s){const{windowSize:t,mask:r,maxNumber:i,shiftBy:o}=s;let l=Number(e&r),a=e>>o;l>t&&(l-=i,a+=oe);const c=n*t,h=c+Math.abs(l)-1,p=l===0,d=l<0,f=n%2!==0;return{nextN:a,offset:h,isZero:p,isNeg:d,isNegF:f,offsetF:c}}const en=new WeakMap,Ut=new WeakMap;function nn(e){return Ut.get(e)||1}function Wn(e){if(e!==ue)throw new Error("invalid wNAF")}class Or{BASE;ZERO;Fn;bits;constructor(n,s){this.BASE=n.BASE,this.ZERO=n.ZERO,this.Fn=n.Fn,this.bits=s}_unsafeLadder(n,s,t=this.ZERO){let r=n;for(;s>ue;)s&oe&&(t=t.add(r)),r=r.double(),s>>=oe;return t}precomputeWindow(n,s){const{windows:t,windowSize:r}=Je(s,this.bits),i=[];let o=n,l=o;for(let a=0;a<t;a++){l=o,i.push(l);for(let c=1;c<r;c++)l=l.add(o),i.push(l);o=l.double()}return i}wNAF(n,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=Je(n,this.bits);for(let l=0;l<o.windows;l++){const{nextN:a,offset:c,isZero:h,isNeg:p,isNegF:d,offsetF:f}=Fn(t,l,o);t=a,h?i=i.add(De(d,s[f])):r=r.add(De(p,s[c]))}return Wn(t),{p:r,f:i}}wNAFUnsafe(n,s,t,r=this.ZERO){const i=Je(n,this.bits);for(let o=0;o<i.windows&&t!==ue;o++){const{nextN:l,offset:a,isZero:c,isNeg:h}=Fn(t,o,i);if(t=l,!c){const p=s[a];r=r.add(h?p.negate():p)}}return Wn(t),r}getPrecomputes(n,s,t){let r=en.get(s);return r||(r=this.precomputeWindow(s,n),n!==1&&(typeof t=="function"&&(r=t(r)),en.set(s,r))),r}cached(n,s,t){const r=nn(n);return this.wNAF(r,this.getPrecomputes(r,n,t),s)}unsafe(n,s,t,r){const i=nn(n);return i===1?this._unsafeLadder(n,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,n,t),s,r)}createCache(n,s){Mt(s,this.bits),Ut.set(n,s),en.delete(n)}hasCache(n){return nn(n)!==1}}function qr(e,n,s,t){let r=n,i=e.ZERO,o=e.ZERO;for(;s>ue||t>ue;)s&oe&&(i=i.add(r)),t&oe&&(o=o.add(r)),r=r.double(),s>>=oe,t>>=oe;return{p1:i,p2:o}}function zn(e,n,s){if(n){if(n.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return xr(n),n}else return Ge(e,{isLE:s})}function Cr(e,n,s={},t){if(t===void 0&&(t=e==="edwards"),!n||typeof n!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const c=n[a];if(!(typeof c=="bigint"&&c>ue))throw new Error(`CURVE.${a} must be positive bigint`)}const r=zn(n.p,s.Fp,t),i=zn(n.n,s.Fn,t),l=["Gx","Gy","a","b"];for(const a of l)if(!r.isValid(n[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return n=Object.freeze(Object.assign({},n)),{CURVE:n,Fp:r,Fn:i}}function Nr(e,n){return function(t){const r=e(t);return{secretKey:r,publicKey:n(r)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Gn=(e,n)=>(e+(e>=0?n:-n)/Dr)/n;function Hr(e,n,s){const[[t,r],[i,o]]=n,l=Gn(o*e,s),a=Gn(-r*e,s);let c=e-l*t-a*i,h=-l*r-a*o;const p=c<he,d=h<he;p&&(c=-c),d&&(h=-h);const f=bt(Math.ceil(Er(s)/2))+je;if(c<he||c>=f||h<he||h>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:p,k1:c,k2neg:d,k2:h}}const he=BigInt(0),je=BigInt(1),Dr=BigInt(2),Ue=BigInt(3),Br=BigInt(4);function Lr(e,n={}){const s=Cr("weierstrass",e,n),{Fp:t,Fn:r}=s;let i=s.CURVE;const{h:o,n:l}=i;vt(n,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:a}=n;if(a&&(!t.is0(i.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const c=Fr(t,r);function h(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(I,g,b){const{x:E,y:S}=g.toAffine(),x=t.toBytes(E);if(Hn(b,"isCompressed"),b){h();const _=!t.isOdd(S);return Ce($r(_),x)}else return Ce(Uint8Array.of(4),x,t.toBytes(S))}function d(I){L(I,void 0,"Point");const{publicKey:g,publicKeyUncompressed:b}=c,E=I.length,S=I[0],x=I.subarray(1);if(E===g&&(S===2||S===3)){const _=t.fromBytes(x);if(!t.isValid(_))throw new Error("bad point: is not on curve, wrong x");const R=w(_);let v;try{v=t.sqrt(R)}catch($){const q=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}h();const T=t.isOdd(v);return(S&1)===1!==T&&(v=t.neg(v)),{x:_,y:v}}else if(E===b&&S===4){const _=t.BYTES,R=t.fromBytes(x.subarray(0,_)),v=t.fromBytes(x.subarray(_,_*2));if(!A(R,v))throw new Error("bad point: is not on curve");return{x:R,y:v}}else throw new Error(`bad point: got length ${E}, expected compressed=${g} or uncompressed=${b}`)}const f=n.toBytes||p,y=n.fromBytes||d;function w(I){const g=t.sqr(I),b=t.mul(g,I);return t.add(t.add(b,t.mul(I,i.a)),i.b)}function A(I,g){const b=t.sqr(g),E=w(I);return t.eql(b,E)}if(!A(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const O=t.mul(t.pow(i.a,Ue),Br),V=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(O,V)))throw new Error("bad curve params: a or b");function J(I,g,b=!1){if(!t.isValid(g)||b&&t.is0(g))throw new Error(`bad point coordinate ${I}`);return g}function _e(I){if(!(I instanceof U))throw new Error("Weierstrass Point expected")}function ke(I){if(!a||!a.basises)throw new Error("no endo");return Hr(I,a.basises,r.ORDER)}const Ie=Dn((I,g)=>{const{X:b,Y:E,Z:S}=I;if(t.eql(S,t.ONE))return{x:b,y:E};const x=I.is0();g==null&&(g=x?t.ONE:t.inv(S));const _=t.mul(b,g),R=t.mul(E,g),v=t.mul(S,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:_,y:R}}),Ht=Dn(I=>{if(I.is0()){if(n.allowInfinityPoint&&!t.is0(I.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:b}=I.toAffine();if(!t.isValid(g)||!t.isValid(b))throw new Error("bad point: x or y not field elements");if(!A(g,b))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Tn(I,g,b,E,S){return b=new U(t.mul(b.X,I),b.Y,b.Z),g=De(E,g),b=De(S,b),g.add(b)}class U{static BASE=new U(i.Gx,i.Gy,t.ONE);static ZERO=new U(t.ZERO,t.ONE,t.ZERO);static Fp=t;static Fn=r;X;Y;Z;constructor(g,b,E){this.X=J("x",g),this.Y=J("y",b,!0),this.Z=J("z",E),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){const{x:b,y:E}=g||{};if(!g||!t.isValid(b)||!t.isValid(E))throw new Error("invalid affine point");if(g instanceof U)throw new Error("projective point not allowed");return t.is0(b)&&t.is0(E)?U.ZERO:new U(b,E,t.ONE)}static fromBytes(g){const b=U.fromAffine(y(L(g,void 0,"point")));return b.assertValidity(),b}static fromHex(g){return U.fromBytes(Z(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){return me.createCache(this,g),b||this.multiply(Ue),this}assertValidity(){Ht(this)}hasEvenY(){const{y:g}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(g)}equals(g){_e(g);const{X:b,Y:E,Z:S}=this,{X:x,Y:_,Z:R}=g,v=t.eql(t.mul(b,R),t.mul(x,S)),T=t.eql(t.mul(E,R),t.mul(_,S));return v&&T}negate(){return new U(this.X,t.neg(this.Y),this.Z)}double(){const{a:g,b}=i,E=t.mul(b,Ue),{X:S,Y:x,Z:_}=this;let R=t.ZERO,v=t.ZERO,T=t.ZERO,k=t.mul(S,S),$=t.mul(x,x),q=t.mul(_,_),M=t.mul(S,x);return M=t.add(M,M),T=t.mul(S,_),T=t.add(T,T),R=t.mul(g,T),v=t.mul(E,q),v=t.add(R,v),R=t.sub($,v),v=t.add($,v),v=t.mul(R,v),R=t.mul(M,R),T=t.mul(E,T),q=t.mul(g,q),M=t.sub(k,q),M=t.mul(g,M),M=t.add(M,T),T=t.add(k,k),k=t.add(T,k),k=t.add(k,q),k=t.mul(k,M),v=t.add(v,k),q=t.mul(x,_),q=t.add(q,q),k=t.mul(q,M),R=t.sub(R,k),T=t.mul(q,$),T=t.add(T,T),T=t.add(T,T),new U(R,v,T)}add(g){_e(g);const{X:b,Y:E,Z:S}=this,{X:x,Y:_,Z:R}=g;let v=t.ZERO,T=t.ZERO,k=t.ZERO;const $=i.a,q=t.mul(i.b,Ue);let M=t.mul(b,x),W=t.mul(E,_),z=t.mul(S,R),ae=t.add(b,E),H=t.add(x,_);ae=t.mul(ae,H),H=t.add(M,W),ae=t.sub(ae,H),H=t.add(b,S);let Q=t.add(x,R);return H=t.mul(H,Q),Q=t.add(M,z),H=t.sub(H,Q),Q=t.add(E,S),v=t.add(_,R),Q=t.mul(Q,v),v=t.add(W,z),Q=t.sub(Q,v),k=t.mul($,H),v=t.mul(q,z),k=t.add(v,k),v=t.sub(W,k),k=t.add(W,k),T=t.mul(v,k),W=t.add(M,M),W=t.add(W,M),z=t.mul($,z),H=t.mul(q,H),W=t.add(W,z),z=t.sub(M,z),z=t.mul($,z),H=t.add(H,z),M=t.mul(W,H),T=t.add(T,M),M=t.mul(Q,H),v=t.mul(ae,v),v=t.sub(v,M),M=t.mul(ae,W),k=t.mul(Q,k),k=t.add(k,M),new U(v,T,k)}subtract(g){return this.add(g.negate())}is0(){return this.equals(U.ZERO)}multiply(g){const{endo:b}=n;if(!r.isValidNot0(g))throw new Error("invalid scalar: out of range");let E,S;const x=_=>me.cached(this,_,R=>$n(U,R));if(b){const{k1neg:_,k1:R,k2neg:v,k2:T}=ke(g),{p:k,f:$}=x(R),{p:q,f:M}=x(T);S=$.add(M),E=Tn(b.beta,k,q,_,v)}else{const{p:_,f:R}=x(g);E=_,S=R}return $n(U,[E,S])[0]}multiplyUnsafe(g){const{endo:b}=n,E=this;if(!r.isValid(g))throw new Error("invalid scalar: out of range");if(g===he||E.is0())return U.ZERO;if(g===je)return E;if(me.hasCache(this))return this.multiply(g);if(b){const{k1neg:S,k1:x,k2neg:_,k2:R}=ke(g),{p1:v,p2:T}=qr(U,E,x,R);return Tn(b.beta,v,T,S,_)}else return me.unsafe(E,g)}toAffine(g){return Ie(this,g)}isTorsionFree(){const{isTorsionFree:g}=n;return o===je?!0:g?g(U,this):me.unsafe(this,l).is0()}clearCofactor(){const{clearCofactor:g}=n;return o===je?this:g?g(U,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(g=!0){return Hn(g,"isCompressed"),this.assertValidity(),f(U,this,g)}toHex(g=!0){return C(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const _n=r.BITS,me=new Or(U,n.endo?Math.ceil(_n/2):_n);return U.BASE.precompute(8),U}function $r(e){return Uint8Array.of(e?2:3)}function Fr(e,n){return{secretKey:n.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*n.BYTES}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ve={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Wr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},zr=BigInt(0),pn=BigInt(2);function Gr(e){const n=Ve.p,s=BigInt(3),t=BigInt(6),r=BigInt(11),i=BigInt(22),o=BigInt(23),l=BigInt(44),a=BigInt(88),c=e*e*e%n,h=c*c*e%n,p=F(h,s,n)*h%n,d=F(p,s,n)*h%n,f=F(d,pn,n)*c%n,y=F(f,r,n)*f%n,w=F(y,i,n)*y%n,A=F(w,l,n)*w%n,O=F(A,a,n)*A%n,V=F(O,l,n)*w%n,J=F(V,s,n)*h%n,_e=F(J,o,n)*y%n,ke=F(_e,t,n)*c%n,Ie=F(ke,pn,n);if(!Be.eql(Be.sqr(Ie),e))throw new Error("Cannot find square root");return Ie}const Be=Ge(Ve.p,{sqrt:Gr}),pe=Lr(Ve,{Fp:Be,endo:Wr}),Vn={};function Le(e,...n){let s=Vn[e];if(s===void 0){const t=He(vr(e));s=Ce(t,t),Vn[e]=s}return He(Ce(s,...n))}const Sn=e=>e.toBytes(!0).slice(1),Rn=e=>e%pn===zr;function mn(e){const{Fn:n,BASE:s}=pe,t=n.fromBytes(e),r=s.multiply(t);return{scalar:Rn(r.y)?t:n.neg(t),bytes:Sn(r)}}function At(e){const n=Be;if(!n.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const s=n.create(e*e),t=n.create(s*e+BigInt(7));let r=n.sqrt(t);Rn(r)||(r=n.neg(r));const i=pe.fromAffine({x:e,y:r});return i.assertValidity(),i}const ve=vn;function Pt(...e){return pe.Fn.create(ve(Le("BIP0340/challenge",...e)))}function Qn(e){return mn(e).bytes}function Vr(e,n,s=lt(32)){const{Fn:t}=pe,r=L(e,void 0,"message"),{bytes:i,scalar:o}=mn(n),l=L(s,32,"auxRand"),a=t.toBytes(o^ve(Le("BIP0340/aux",l))),c=Le("BIP0340/nonce",a,i,r),{bytes:h,scalar:p}=mn(c),d=Pt(h,i,r),f=new Uint8Array(64);if(f.set(h,0),f.set(t.toBytes(t.create(p+d*o)),32),!jt(f,r,i))throw new Error("sign: Invalid signature produced");return f}function jt(e,n,s){const{Fp:t,Fn:r,BASE:i}=pe,o=L(e,64,"signature"),l=L(n,void 0,"message"),a=L(s,32,"publicKey");try{const c=At(ve(a)),h=ve(o.subarray(0,32));if(!t.isValidNot0(h))return!1;const p=ve(o.subarray(32,64));if(!r.isValidNot0(p))return!1;const d=Pt(r.toBytes(h),Sn(c),l),f=i.multiplyUnsafe(p).add(c.multiplyUnsafe(r.neg(d))),{x:y,y:w}=f.toAffine();return!(f.is0()||!Rn(w)||y!==h)}catch{return!1}}const Y=(()=>{const s=(t=lt(48))=>jr(t,Ve.n);return{keygen:Nr(s,Qn),getPublicKey:Qn,sign:Vr,verify:jt,Point:pe,utils:{randomSecretKey:s,taggedHash:Le,lift_x:At,pointToBytes:Sn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var re=Symbol("verified"),Qr=e=>e instanceof Object;function Kr(e){if(!Qr(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let n=0;n<e.tags.length;n++){let s=e.tags[n];if(!Array.isArray(s))return!1;for(let t=0;t<s.length;t++)if(typeof s[t]!="string")return!1}return!0}new TextDecoder("utf-8");var Yr=new TextEncoder;function ye(e){try{e.indexOf("://")===-1&&(e="wss://"+e);let n=new URL(e);return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),n.pathname=n.pathname.replace(/\/+/g,"/"),n.pathname.endsWith("/")&&(n.pathname=n.pathname.slice(0,-1)),(n.port==="80"&&n.protocol==="ws:"||n.port==="443"&&n.protocol==="wss:")&&(n.port=""),n.searchParams.sort(),n.hash="",n.toString()}catch{throw new Error(`Invalid URL: ${e}`)}}var Zr=class{generateSecretKey(){return Y.utils.randomSecretKey()}getPublicKey(n){return C(Y.getPublicKey(n))}finalizeEvent(n,s){const t=n;return t.pubkey=C(Y.getPublicKey(s)),t.id=tn(t),t.sig=C(Y.sign(Z(tn(t)),s)),t[re]=!0,t}verifyEvent(n){if(typeof n[re]=="boolean")return n[re];try{const s=tn(n);if(s!==n.id)return n[re]=!1,!1;const t=Y.verify(Z(n.sig),Z(s),Z(n.pubkey));return n[re]=t,t}catch{return n[re]=!1,!1}}};function Xr(e){if(!Kr(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function tn(e){let n=He(Yr.encode(Xr(e)));return C(n)}var Qe=new Zr;Qe.generateSecretKey;Qe.getPublicKey;Qe.finalizeEvent;var Jr=Qe.verifyEvent,ei=22242;function ni(e,n){if(e.ids&&e.ids.indexOf(n.id)===-1||e.kinds&&e.kinds.indexOf(n.kind)===-1||e.authors&&e.authors.indexOf(n.pubkey)===-1)return!1;for(let s in e)if(s[0]==="#"){let t=s.slice(1),r=e[`#${t}`];if(r&&!n.tags.find(([i,o])=>i===s.slice(1)&&r.indexOf(o)!==-1))return!1}return!(e.since&&n.created_at<e.since||e.until&&n.created_at>e.until)}function ti(e,n){for(let s=0;s<e.length;s++)if(ni(e[s],n))return!0;return!1}function si(e,n){let s=n.length+3,t=e.indexOf(`"${n}":`)+s,r=e.slice(t).indexOf('"')+t+1;return e.slice(r,r+64)}function ri(e){let n=e.slice(0,22).indexOf('"EVENT"');if(n===-1)return null;let s=e.slice(n+7+1).indexOf('"');if(s===-1)return null;let t=n+7+1+s,r=e.slice(t+1,80).indexOf('"');if(r===-1)return null;let i=t+1+r;return e.slice(t+1,i)}function ii(e,n){return{kind:ei,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",n]],content:""}}var Ot=class extends Error{constructor(e,n){super(`Tried to send message '${e} on a closed connection to ${n}.`),this.name="SendingOnClosedConnection"}},qt=class{url;_connected=!1;onclose=null;onnotice=e=>console.debug(`NOTICE from ${this.url}: ${e}`);onauth;baseEoseTimeout=4400;publishTimeout=4400;pingFrequency=29e3;pingTimeout=2e4;resubscribeBackoff=[1e4,1e4,1e4,2e4,2e4,3e4,6e4];openSubs=new Map;enablePing;enableReconnect;idleSince=Date.now();ongoingOperations=0;reconnectTimeoutHandle;pingIntervalHandle;reconnectAttempts=0;skipReconnection=!1;connectionPromise;openCountRequests=new Map;openEventPublishes=new Map;ws;challenge;authPromise;serial=0;verifyEvent;_WebSocket;constructor(e,n){this.url=ye(e),this.verifyEvent=n.verifyEvent,this._WebSocket=n.websocketImplementation||WebSocket,this.enablePing=n.enablePing,this.enableReconnect=n.enableReconnect||!1}static async connect(e,n){const s=new qt(e,n);return await s.connect(n),s}closeAllSubscriptions(e){for(let[n,s]of this.openSubs)s.close(e);this.openSubs.clear();for(let[n,s]of this.openEventPublishes)s.reject(new Error(e));this.openEventPublishes.clear();for(let[n,s]of this.openCountRequests)s.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){const e=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},e)}handleHardClose(e){this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(e))}async connect(e){let n;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((s,t)=>{e?.timeout&&(n=setTimeout(()=>{t("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection timed out")},e.timeout)),e?.abort&&(e.abort.onabort=t);try{this.ws=new this._WebSocket(this.url)}catch(r){clearTimeout(n),t(r);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(n),this._connected=!0;const r=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const i of this.openSubs.values()){if(i.eosed=!1,r)for(let o=0;o<i.filters.length;o++)i.lastEmitted&&(i.filters[o].since=i.lastEmitted+1);i.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),s()},this.ws.onerror=()=>{clearTimeout(n),t("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection failed")},this.ws.onclose=r=>{clearTimeout(n),t(r.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(e=>{this.ws.once("pong",()=>e(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((e,n)=>{if(!this.connectionPromise)return n(new Error(`no connection to ${this.url}, can't ping`));try{const s=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),s.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(s){n(s)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(n=>setTimeout(()=>n(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(e){if(!this.connectionPromise)throw new Ot(e,this.url);this.connectionPromise.then(()=>{this.ws?.send(e)})}async auth(e){const n=this.challenge;if(!n)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(s,t)=>{try{let r=await e(ii(this.url,n)),i=setTimeout(()=>{let o=this.openEventPublishes.get(r.id);o&&(o.reject(new Error("auth timed out")),this.openEventPublishes.delete(r.id))},this.publishTimeout);this.openEventPublishes.set(r.id,{resolve:s,reject:t,timeout:i}),this.send('["AUTH",'+JSON.stringify(r)+"]")}catch(r){console.warn("subscribe auth function failed:",r)}}),this.authPromise)}async publish(e){this.idleSince=void 0,this.ongoingOperations++;const n=new Promise((s,t)=>{const r=setTimeout(()=>{const i=this.openEventPublishes.get(e.id);i&&(i.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:s,reject:t,timeout:r})});return this.send('["EVENT",'+JSON.stringify(e)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),n}async count(e,n){this.serial++;const s=n?.id||"count:"+this.serial,t=new Promise((r,i)=>{this.openCountRequests.set(s,{resolve:r,reject:i})});return this.send('["COUNT","'+s+'",'+JSON.stringify(e).substring(1)),t}subscribe(e,n){n.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);const s=this.prepareSubscription(e,n);return s.fire(),n.abort&&(n.abort.onabort=()=>s.close(String(n.abort.reason||"<aborted>"))),s}prepareSubscription(e,n){this.serial++;const s=n.id||(n.label?n.label+":":"sub:")+this.serial,t=new oi(this,s,e,n);return this.openSubs.set(s,t),t}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,this.onclose?.(),this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}_onmessage(e){const n=e.data;if(!n)return;const s=ri(n);if(s){const t=this.openSubs.get(s);if(!t)return;const r=si(n,"id"),i=t.alreadyHaveEvent?.(r);if(t.receivedEvent?.(this,r),i)return}try{let t=JSON.parse(n);switch(t[0]){case"EVENT":{const r=this.openSubs.get(t[1]),i=t[2];this.verifyEvent(i)&&ti(r.filters,i)?r.onevent(i):r.oninvalidevent?.(i),(!r.lastEmitted||r.lastEmitted<i.created_at)&&(r.lastEmitted=i.created_at);return}case"COUNT":{const r=t[1],i=t[2],o=this.openCountRequests.get(r);o&&(o.resolve(i.count),this.openCountRequests.delete(r));return}case"EOSE":{const r=this.openSubs.get(t[1]);if(!r)return;r.receivedEose();return}case"OK":{const r=t[1],i=t[2],o=t[3],l=this.openEventPublishes.get(r);l&&(clearTimeout(l.timeout),i?l.resolve(o):l.reject(new Error(o)),this.openEventPublishes.delete(r));return}case"CLOSED":{const r=t[1],i=this.openSubs.get(r);if(!i)return;i.closed=!0,i.close(t[2]);return}case"NOTICE":{this.onnotice(t[1]);return}case"AUTH":{this.challenge=t[1],this.onauth&&this.auth(this.onauth);return}default:{this.openSubs.get(t[1])?.oncustom?.(t);return}}}catch(t){try{const[r,i,o]=JSON.parse(n);console.warn(`[nostr] relay ${this.url} error processing message:`,t,o)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,t)}return}}},oi=class{relay;id;lastEmitted;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oninvalidevent;oneose;onclose;oncustom;eoseTimeout;eoseTimeoutHandle;constructor(e,n,s,t){if(s.length===0)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=s,this.id=n,this.alreadyHaveEvent=t.alreadyHaveEvent,this.receivedEvent=t.receivedEvent,this.eoseTimeout=t.eoseTimeout||e.baseEoseTimeout,this.oneose=t.oneose,this.onclose=t.onclose,this.oninvalidevent=t.oninvalidevent,this.onevent=t.onevent||(r=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,r)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(e="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(n){if(!(n instanceof Ot))throw n}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),this.onclose?.(e)}},ai=e=>(e[re]=!0,!0),li=class{relays=new Map;seenOn=new Map;trackRelays=!1;verifyEvent;enablePing;enableReconnect;automaticallyAuth;trustedRelayURLs=new Set;onRelayConnectionFailure;onRelayConnectionSuccess;allowConnectingToRelay;maxWaitForConnection;_WebSocket;constructor(e){this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1,this.automaticallyAuth=e.automaticallyAuth,this.onRelayConnectionFailure=e.onRelayConnectionFailure,this.onRelayConnectionSuccess=e.onRelayConnectionSuccess,this.allowConnectingToRelay=e.allowConnectingToRelay,this.maxWaitForConnection=e.maxWaitForConnection||3e3}async ensureRelay(e,n){e=ye(e);let s=this.relays.get(e);if(s||(s=new qt(e,{verifyEvent:this.trustedRelayURLs.has(e)?ai:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),s.onclose=()=>{this.relays.delete(e)},this.relays.set(e,s)),this.automaticallyAuth){const t=this.automaticallyAuth(e);t&&(s.onauth=t)}try{await s.connect({timeout:n?.connectionTimeout,abort:n?.abort})}catch(t){throw this.relays.delete(e),t}return s}close(e){e.map(ye).forEach(n=>{this.relays.get(n)?.close(),this.relays.delete(n)})}subscribe(e,n,s){const t=[],r=[];for(let i=0;i<e.length;i++){const o=ye(e[i]);t.find(l=>l.url===o)||r.indexOf(o)===-1&&(r.push(o),t.push({url:o,filter:n}))}return this.subscribeMap(t,s)}subscribeMany(e,n,s){return this.subscribe(e,n,s)}subscribeMap(e,n){const s=new Map;for(const d of e){const{url:f,filter:y}=d;s.has(f)||s.set(f,[]),s.get(f).push(y)}const t=Array.from(s.entries()).map(([d,f])=>({url:d,filters:f}));this.trackRelays&&(n.receivedEvent=(d,f)=>{let y=this.seenOn.get(f);y||(y=new Set,this.seenOn.set(f,y)),y.add(d)});const r=new Set,i=[],o=[];let l=d=>{o[d]||(o[d]=!0,o.filter(f=>f).length===t.length&&(n.oneose?.(),l=()=>{}))};const a=[];let c=(d,f)=>{a[d]||(l(d),a[d]=f,a.filter(y=>y).length===t.length&&(n.onclose?.(a),c=()=>{}))};const h=d=>{if(n.alreadyHaveEvent?.(d))return!0;const f=r.has(d);return r.add(d),f},p=Promise.all(t.map(async({url:d,filters:f},y)=>{if(this.allowConnectingToRelay?.(d,["read",f])===!1){c(y,"connection skipped by allowConnectingToRelay");return}let w;try{w=await this.ensureRelay(d,{connectionTimeout:this.maxWaitForConnection<(n.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n.abort})}catch(O){this.onRelayConnectionFailure?.(d),c(y,O?.message||String(O));return}this.onRelayConnectionSuccess?.(d);let A=w.subscribe(f,{...n,oneose:()=>l(y),onclose:O=>{O.startsWith("auth-required: ")&&n.onauth?w.auth(n.onauth).then(()=>{w.subscribe(f,{...n,oneose:()=>l(y),onclose:V=>{c(y,V)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort})}).catch(V=>{c(y,`auth was required and attempted, but failed with: ${V}`)}):c(y,O)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort});i.push(A)}));return{async close(d){await p,i.forEach(f=>{f.close(d)})}}}subscribeEose(e,n,s){let t;return t=this.subscribe(e,n,{...s,oneose(){const r="closed automatically on eose";t?t.close(r):s.onclose?.(e.map(i=>r))}}),t}subscribeManyEose(e,n,s){return this.subscribeEose(e,n,s)}async querySync(e,n,s){return new Promise(async t=>{const r=[];this.subscribeEose(e,n,{...s,onevent(i){r.push(i)},onclose(i){t(r)}})})}async get(e,n,s){n.limit=1;const t=await this.querySync(e,n,s);return t.sort((r,i)=>i.created_at-r.created_at),t[0]||null}publish(e,n,s){return e.map(ye).map(async(t,r,i)=>{if(i.indexOf(t)!==r)return Promise.reject("duplicate url");if(this.allowConnectingToRelay?.(t,["write",n])===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let o;try{o=await this.ensureRelay(t,{connectionTimeout:this.maxWaitForConnection<(s?.maxWait||0)?Math.max(s.maxWait*.8,s.maxWait-1e3):this.maxWaitForConnection,abort:s?.abort})}catch(l){return this.onRelayConnectionFailure?.(t),"connection failure: "+String(l)}return o.publish(n).catch(async l=>{if(l instanceof Error&&l.message.startsWith("auth-required: ")&&s?.onauth)return await o.auth(s.onauth),o.publish(n);throw l}).then(l=>{if(this.trackRelays){let a=this.seenOn.get(n.id);a||(a=new Set,this.seenOn.set(n.id,a)),a.add(o)}return l})})}listConnectionStatus(){const e=new Map;return this.relays.forEach((n,s)=>e.set(s,n.connected)),e}destroy(){this.relays.forEach(e=>e.close()),this.relays=new Map}pruneIdleRelays(e=1e4){const n=[];for(const[s,t]of this.relays)t.idleSince&&Date.now()-t.idleSince>=e&&(this.relays.delete(s),n.push(s),t.close());return n}},Ct;try{Ct=WebSocket}catch{}var di=class extends li{constructor(e){super({verifyEvent:Jr,websocketImplementation:Ct,maxWaitForConnection:3e3,...e})}},le=Symbol("verified"),ci=e=>e instanceof Object;function ui(e){if(!ci(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let n=0;n<e.tags.length;n++){let s=e.tags[n];if(!Array.isArray(s))return!1;for(let t=0;t<s.length;t++)if(typeof s[t]!="string")return!1}return!0}new TextDecoder("utf-8");var pi=new TextEncoder,mi=class{generateSecretKey(){return Y.utils.randomSecretKey()}getPublicKey(e){return C(Y.getPublicKey(e))}finalizeEvent(e,n){const s=e;return s.pubkey=C(Y.getPublicKey(n)),s.id=sn(s),s.sig=C(Y.sign(Z(sn(s)),n)),s[le]=!0,s}verifyEvent(e){if(typeof e[le]=="boolean")return e[le];try{const n=sn(e);if(n!==e.id)return e[le]=!1,!1;const s=Y.verify(Z(e.sig),Z(n),Z(e.pubkey));return e[le]=s,s}catch{return e[le]=!1,!1}}};function fi(e){if(!ui(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function sn(e){let n=He(pi.encode(fi(e)));return C(n)}var Ke=new mi;Ke.generateSecretKey;Ke.getPublicKey;Ke.finalizeEvent;var gi=Ke.verifyEvent;const hi=8e3;function yi(e){return typeof e=="number"&&hn.includes(e)}function bi(e){try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function vi(e){const n=[];for(const s of e??[])try{const t=new URL(s);if(t.protocol!=="ws:"&&t.protocol!=="wss:")continue;n.push(t.href)}catch{}return[...new Set(n)]}function wi(e){const n=dr(e.trim());if(n.type!=="nevent"&&n.type!=="naddr")throw new Error("Enter a NIP-19 nevent or naddr for a NIP-5D napplet manifest event");const s=vi(n.data.relays);if(s.length===0)throw new Error("The pointer does not include relay hints; include at least one relay in the nevent/naddr");if(n.type==="nevent"){if(n.data.kind!==void 0&&!yi(n.data.kind))throw new Error(`nevent points at kind ${n.data.kind}, not a NIP-5D napplet manifest kind`);return{type:"nevent",relays:s,filter:{ids:[n.data.id],kinds:n.data.kind===void 0?[...hn]:[n.data.kind],authors:n.data.author?[n.data.author]:void 0,limit:1}}}if(n.data.kind!==ce)throw new Error(`naddr kind ${n.data.kind} is not the named napplet kind ${ce}`);return{type:"naddr",relays:s,filter:{kinds:[ce],authors:[n.data.pubkey],"#d":[n.data.identifier],limit:1}}}function Ei(e){return{id:e.id,pubkey:e.pubkey,kind:e.kind,tags:e.tags,content:e.content}}async function Si(e){const n=typeof e=="string"?new TextEncoder().encode(e):e,s=new Uint8Array(n.byteLength);s.set(n);const t=await crypto.subtle.digest("SHA-256",s.buffer);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}function Ri(e){const n=[];for(const s of e.tags)if(!(s[0]!=="server"||!s[1]))try{const t=new URL(s[1]);(t.protocol==="http:"||t.protocol==="https:")&&n.push(t.href)}catch{}return[...new Set(n)]}function Ti(e,n){const s=e.endsWith("/")?e:`${e}/`;return new URL(n,s).href}async function _i(e,n=fetch){const s=ze(e);if(!s.ok)throw new Error(s.errors.map(o=>o.message).join("; "));const t=e.tags.find(o=>o[0]==="x")[1],r=Ri(e);if(r.length===0)throw new Error("Manifest does not include any usable Blossom server hints");const i=[];for(const o of r){const l=Ti(o,t);try{const a=await n(l,{mode:"cors"});if(!a.ok){i.push(`${l}: HTTP ${a.status}`);continue}const c=new Uint8Array(await a.arrayBuffer()),h=await Si(c);if(h!==t){i.push(`${l}: sha256 ${h} did not match manifest ${t}`);continue}return new TextDecoder().decode(c)}catch(a){i.push(`${l}: ${a instanceof Error?a.message:String(a)}`)}}throw new Error(`Unable to fetch verified /index.html from Blossom servers: ${i.join("; ")}`)}async function ki(e,n){try{const t=await(await n(e,{mode:"cors"})).text();return{source:"url",input:e,label:e,bootUrl:e,html:t,fetched:!0,manifestEvent:null}}catch{return{source:"url",input:e,label:e,bootUrl:e,html:"",fetched:!1,manifestEvent:null}}}async function Ii(e,n){const s=wi(e),t=!n.pool,r=n.pool??new di;try{const i=await r.get(s.relays,{...s.filter},{maxWait:n.maxRelayWaitMs??hi});if(!i)throw new Error("No matching napplet manifest event was found on the pointer relay hints");if(!gi(i))throw new Error("Resolved manifest event signature is invalid");const o=Ei(i),l=ze(o);if(!l.ok)throw new Error(`Resolved event is not a valid NIP-5D napplet manifest: ${l.errors[0]?.message}`);const a=await _i(o,n.fetcher??fetch),c=(n.createObjectUrl??URL.createObjectURL)(new Blob([a],{type:"text/html;charset=utf-8"})),h=()=>(n.revokeObjectUrl??URL.revokeObjectURL)(c);return{source:"nostr",input:e,label:o.id??e,bootUrl:c,html:a,fetched:!0,manifestEvent:o,revoke:h}}finally{t&&r.destroy()}}async function xi(e,n={}){const s=e.trim();if(!s)throw new Error("Enter a NIP-19 nevent/naddr, or an HTTP URL for local dev");return bi(s)?ki(s,n.fetcher??fetch):Ii(s,n)}const Mi=`"use strict";
|
|
197
11
|
var NappletShimPrelude = (() => {
|
|
198
12
|
var __defProp = Object.defineProperty;
|
|
199
13
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -224,6 +38,197 @@ var NappletShimPrelude = (() => {
|
|
|
224
38
|
|
|
225
39
|
// ../core/dist/index.js
|
|
226
40
|
var NAP_DOMAINS = ["shell", "relay", "identity", "storage", "inc", "theme", "keys", "media", "notify", "config", "resource", "cvm", "outbox", "upload", "intent", "ble", "webrtc", "link", "count", "lists", "serial", "fs", "common", "dm", "gamepad", "llm"];
|
|
41
|
+
var NAP_IMPLEMENTATIONS = {
|
|
42
|
+
shell: {
|
|
43
|
+
proposal: { url: "https://github.com/napplet/naps/pull/101", status: "merged", checkedAt: "2026-10-31" },
|
|
44
|
+
maturity: "supported",
|
|
45
|
+
rationale: "Optional readiness and environment binding has focused shim and reference-runtime coverage.",
|
|
46
|
+
evidence: ["packages/nap/src/shell/shim.test.ts"]
|
|
47
|
+
},
|
|
48
|
+
relay: {
|
|
49
|
+
proposal: { url: "https://github.com/napplet/naps/pull/2", status: "in-review", checkedAt: "2026-10-31" },
|
|
50
|
+
maturity: "supported",
|
|
51
|
+
rationale: "Relay reads, publishing, and subscription lifecycle have maintained shim and integration tests; upstream naming remains under review.",
|
|
52
|
+
evidence: ["packages/nap/src/relay/shim.test.ts"],
|
|
53
|
+
implementationReference: { revision: "cb8f8eabb2d09439e9d174cb9eb6ef2caad0eca1", evidence: ".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md", scope: "RelayEventResult sidecar migration; subsequent changes are not covered." }
|
|
54
|
+
},
|
|
55
|
+
identity: {
|
|
56
|
+
proposal: { url: "https://github.com/napplet/naps/pull/102", status: "merged", checkedAt: "2026-10-31" },
|
|
57
|
+
maturity: "supported",
|
|
58
|
+
rationale: "Read-only identity queries and updates have focused binding and reference-runtime coverage.",
|
|
59
|
+
evidence: ["packages/nap/src/identity/shim.test.ts"]
|
|
60
|
+
},
|
|
61
|
+
storage: {
|
|
62
|
+
proposal: { url: "https://github.com/napplet/naps/pull/3", status: "in-review", checkedAt: "2026-10-31" },
|
|
63
|
+
maturity: "supported",
|
|
64
|
+
rationale: "Key-value binding has focused request/result tests and tutorial usage; host storage isolation remains the host responsibility.",
|
|
65
|
+
evidence: ["packages/nap/src/storage/shim.test.ts"]
|
|
66
|
+
},
|
|
67
|
+
inc: {
|
|
68
|
+
proposal: { url: "https://github.com/napplet/naps/pull/104", status: "merged", checkedAt: "2026-10-31" },
|
|
69
|
+
maturity: "supported",
|
|
70
|
+
rationale: "Topic and channel bindings have compatibility tests and authenticated-endpoint reference-runtime coverage.",
|
|
71
|
+
evidence: ["packages/nap/src/inc/shim.ts", "packages/conformance-cli/src/browser.test.ts"]
|
|
72
|
+
},
|
|
73
|
+
theme: {
|
|
74
|
+
proposal: { url: "https://github.com/napplet/naps/pull/103", status: "merged", checkedAt: "2026-10-31" },
|
|
75
|
+
maturity: "supported",
|
|
76
|
+
rationale: "Theme queries and pushed updates have focused binding and opaque-iframe integration coverage.",
|
|
77
|
+
evidence: ["packages/nap/src/theme/shim.test.ts", "packages/conformance-cli/src/browser.test.ts"]
|
|
78
|
+
},
|
|
79
|
+
keys: {
|
|
80
|
+
proposal: { url: "https://github.com/napplet/naps/pull/9", status: "in-review", checkedAt: "2026-10-31" },
|
|
81
|
+
maturity: "experimental",
|
|
82
|
+
rationale: "Keyboard binding ships, but dedicated domain regression coverage is limited; retain explicit evaluation opt-in.",
|
|
83
|
+
evidence: ["packages/nap/src/keys/shim.ts"]
|
|
84
|
+
},
|
|
85
|
+
media: {
|
|
86
|
+
proposal: { url: "https://github.com/napplet/naps/pull/10", status: "in-review", checkedAt: "2026-10-31" },
|
|
87
|
+
maturity: "supported",
|
|
88
|
+
rationale: "Session creation and playback binding have focused regression coverage; proposed torrent playback amendments are not implied.",
|
|
89
|
+
evidence: ["packages/nap/src/media/shim.test.ts"]
|
|
90
|
+
},
|
|
91
|
+
notify: {
|
|
92
|
+
proposal: { url: "https://github.com/napplet/naps/pull/11", status: "in-review", checkedAt: "2026-10-31" },
|
|
93
|
+
maturity: "experimental",
|
|
94
|
+
rationale: "Notification binding ships with limited dedicated domain regression evidence; broader host integration confidence is unverified.",
|
|
95
|
+
evidence: ["packages/nap/src/notify/shim.ts"]
|
|
96
|
+
},
|
|
97
|
+
config: {
|
|
98
|
+
proposal: { url: "https://github.com/napplet/naps/pull/14", status: "draft", checkedAt: "2026-10-31" },
|
|
99
|
+
maturity: "exploratory",
|
|
100
|
+
rationale: "Configuration binding is tested, but the upstream draft is marked MAY DEFER; use for design exploration.",
|
|
101
|
+
evidence: ["packages/nap/src/config/shim.test.ts"]
|
|
102
|
+
},
|
|
103
|
+
resource: {
|
|
104
|
+
proposal: { url: "https://github.com/napplet/naps/pull/80", status: "in-review", checkedAt: "2026-10-31" },
|
|
105
|
+
maturity: "supported",
|
|
106
|
+
rationale: "Resource fetching has focused shim and type tests; the reverted merge and reopened proposal do not change that implementation assessment.",
|
|
107
|
+
evidence: ["packages/nap/src/resource/shim.test.ts"],
|
|
108
|
+
implementationReference: { revision: "8e75eadf317d7fe809415e4755cd48f63cfb63f3", evidence: ".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md", scope: "Shared ResourceSidecarEntry types during the sidecar migration; subsequent resource changes are not covered." }
|
|
109
|
+
},
|
|
110
|
+
cvm: {
|
|
111
|
+
proposal: { url: "https://github.com/napplet/naps/pull/31", status: "in-review", checkedAt: "2026-10-31" },
|
|
112
|
+
maturity: "experimental",
|
|
113
|
+
rationale: "Session and registry bindings are tested; upstream explicitly marks the contract NEEDS WORK.",
|
|
114
|
+
evidence: ["packages/nap/src/cvm/shim.test.ts"]
|
|
115
|
+
},
|
|
116
|
+
outbox: {
|
|
117
|
+
proposal: { url: "https://github.com/napplet/naps/pull/32", status: "in-review", checkedAt: "2026-10-31" },
|
|
118
|
+
maturity: "supported",
|
|
119
|
+
rationale: "Routing and subscription bindings have focused tests and an integration regression for structured-clone boundaries.",
|
|
120
|
+
evidence: ["packages/nap/src/outbox/shim.test.ts", "packages/nap/src/boundary-integration.test.ts"],
|
|
121
|
+
implementationReference: { revision: "57db924bac022cc14c67d9fca1a4d92cf1bd4725", evidence: ".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md", scope: "RelayEventResult and stream lifecycle migration; subsequent changes are not covered." }
|
|
122
|
+
},
|
|
123
|
+
upload: {
|
|
124
|
+
proposal: { url: "https://github.com/napplet/naps/pull/33", status: "in-review", checkedAt: "2026-10-31" },
|
|
125
|
+
maturity: "supported",
|
|
126
|
+
rationale: "Upload binding has focused tests for request/result behavior; host rail support remains runtime-specific.",
|
|
127
|
+
evidence: ["packages/nap/src/upload/shim.test.ts"]
|
|
128
|
+
},
|
|
129
|
+
intent: {
|
|
130
|
+
proposal: { url: "https://github.com/napplet/naps/pull/91", status: "merged", checkedAt: "2026-10-31" },
|
|
131
|
+
maturity: "supported",
|
|
132
|
+
rationale: "Convention normalization and dispatch have focused binding and reference-runtime integration tests.",
|
|
133
|
+
evidence: ["packages/nap/src/intent/shim.test.ts"]
|
|
134
|
+
},
|
|
135
|
+
ble: {
|
|
136
|
+
proposal: { url: "https://github.com/napplet/naps/pull/62", status: "in-review", checkedAt: "2026-10-31" },
|
|
137
|
+
maturity: "experimental",
|
|
138
|
+
rationale: "GATT binding has unit coverage; real-device behavior across host backends is not established by these tests.",
|
|
139
|
+
evidence: ["packages/nap/src/ble/shim.test.ts"]
|
|
140
|
+
},
|
|
141
|
+
webrtc: {
|
|
142
|
+
proposal: { url: "https://github.com/napplet/naps/pull/59", status: "in-review", checkedAt: "2026-10-31" },
|
|
143
|
+
maturity: "experimental",
|
|
144
|
+
rationale: "Signaling and session binding have unit coverage; interoperable live peer sessions remain unverified here.",
|
|
145
|
+
evidence: ["packages/nap/src/webrtc/shim.test.ts"]
|
|
146
|
+
},
|
|
147
|
+
link: {
|
|
148
|
+
proposal: { url: "https://github.com/napplet/naps/pull/53", status: "in-review", checkedAt: "2026-10-31" },
|
|
149
|
+
maturity: "supported",
|
|
150
|
+
rationale: "The small link-opening binding has focused regression coverage; navigation authorization stays with the host.",
|
|
151
|
+
evidence: ["packages/nap/src/link/shim.test.ts"]
|
|
152
|
+
},
|
|
153
|
+
count: {
|
|
154
|
+
proposal: { url: "https://github.com/napplet/naps/pull/69", status: "in-review", checkedAt: "2026-10-31" },
|
|
155
|
+
maturity: "experimental",
|
|
156
|
+
rationale: "Count binding is tested, but accuracy and aggregation across real relay backends remain outside that evidence.",
|
|
157
|
+
evidence: ["packages/nap/src/count/shim.test.ts"]
|
|
158
|
+
},
|
|
159
|
+
lists: {
|
|
160
|
+
proposal: { url: "https://github.com/napplet/naps/pull/68", status: "in-review", checkedAt: "2026-10-31" },
|
|
161
|
+
maturity: "experimental",
|
|
162
|
+
rationale: "List mutation binding is tested; concurrent real-host mutation behavior is not established by binding tests.",
|
|
163
|
+
evidence: ["packages/nap/src/lists/shim.test.ts"]
|
|
164
|
+
},
|
|
165
|
+
serial: {
|
|
166
|
+
proposal: { url: "https://github.com/napplet/naps/pull/61", status: "in-review", checkedAt: "2026-10-31" },
|
|
167
|
+
maturity: "experimental",
|
|
168
|
+
rationale: "Serial binding has unit coverage; device and native-host integration evidence is limited.",
|
|
169
|
+
evidence: ["packages/nap/src/serial/shim.test.ts"]
|
|
170
|
+
},
|
|
171
|
+
fs: {
|
|
172
|
+
proposal: { url: "https://github.com/napplet/naps/pull/88", status: "in-review", checkedAt: "2026-10-31" },
|
|
173
|
+
maturity: "experimental",
|
|
174
|
+
rationale: "Filesystem binding has MVP coverage; portability and authorization across storage backends remain under evaluation.",
|
|
175
|
+
evidence: ["packages/nap/src/fs/shim.test.ts"]
|
|
176
|
+
},
|
|
177
|
+
common: {
|
|
178
|
+
proposal: { url: "https://github.com/napplet/naps/pull/67", status: "in-review", checkedAt: "2026-10-31" },
|
|
179
|
+
maturity: "experimental",
|
|
180
|
+
rationale: "Social action binding is tested; broader host integration and evolving action semantics warrant explicit opt-in.",
|
|
181
|
+
evidence: ["packages/nap/src/common/shim.test.ts"]
|
|
182
|
+
},
|
|
183
|
+
dm: {
|
|
184
|
+
proposal: { url: "https://github.com/napplet/naps/pull/74", status: "draft", checkedAt: "2026-10-31" },
|
|
185
|
+
maturity: "experimental",
|
|
186
|
+
rationale: "Direct-message binding has shim and type coverage; transport interoperability is not established by those tests.",
|
|
187
|
+
evidence: ["packages/nap/src/dm/shim.test.ts"]
|
|
188
|
+
},
|
|
189
|
+
gamepad: {
|
|
190
|
+
proposal: { url: "https://github.com/napplet/naps/pull/130", status: "in-review", checkedAt: "2026-10-31" },
|
|
191
|
+
maturity: "supported",
|
|
192
|
+
rationale: "Cross-repository delivery includes binding, security, runtime, and conformance verification; the reopened proposal is still subject to change.",
|
|
193
|
+
evidence: ["packages/nap/src/gamepad/shim.test.ts", ".planning/phases/163-nap-gamepad-across-repositories/163-VERIFICATION.md"],
|
|
194
|
+
implementationReference: { revision: "0b28f77e3dfa0f07dd7c0f9d61a7090ee99f3a5e", evidence: ".planning/phases/163-nap-gamepad-across-repositories/163-SECURITY.md", scope: "Phase 163 binding, runtime isolation, and conformance verification." }
|
|
195
|
+
},
|
|
196
|
+
llm: {
|
|
197
|
+
proposal: { url: "https://github.com/napplet/naps/pull/134", status: "draft", checkedAt: "2026-10-31" },
|
|
198
|
+
maturity: "exploratory",
|
|
199
|
+
rationale: "Early published draft has binding and mock-runtime tests; provider behavior and API design remain exploratory.",
|
|
200
|
+
evidence: ["packages/nap/src/llm/shim.test.ts", "packages/conformance-cli/src/browser.test.ts"]
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
for (const entry of Object.values(NAP_IMPLEMENTATIONS)) {
|
|
204
|
+
Object.freeze(entry.proposal);
|
|
205
|
+
Object.freeze(entry.evidence);
|
|
206
|
+
if (entry.implementationReference) Object.freeze(entry.implementationReference);
|
|
207
|
+
Object.freeze(entry);
|
|
208
|
+
}
|
|
209
|
+
Object.freeze(NAP_IMPLEMENTATIONS);
|
|
210
|
+
function getNapImplementation(domain) {
|
|
211
|
+
return Object.hasOwn(NAP_IMPLEMENTATIONS, domain) ? NAP_IMPLEMENTATIONS[domain] : void 0;
|
|
212
|
+
}
|
|
213
|
+
function selectNapDomains(options) {
|
|
214
|
+
const allowed = new Set(options.allowedMaturities ?? ["supported"]);
|
|
215
|
+
const optIn = new Set(options.optIn ?? []);
|
|
216
|
+
const domains = [];
|
|
217
|
+
const excluded = [];
|
|
218
|
+
for (const domain of new Set(options.candidates)) {
|
|
219
|
+
const metadata = getNapImplementation(domain);
|
|
220
|
+
if (!metadata) {
|
|
221
|
+
excluded.push({ domain, reason: "unknown-domain" });
|
|
222
|
+
} else if (!metadata.maturity || !["supported", "experimental", "exploratory"].includes(metadata.maturity)) {
|
|
223
|
+
excluded.push({ domain, reason: "unclassified" });
|
|
224
|
+
} else if (allowed.has(metadata.maturity) || optIn.has(domain)) {
|
|
225
|
+
domains.push(domain);
|
|
226
|
+
} else {
|
|
227
|
+
excluded.push({ domain, reason: "maturity-not-allowed", maturity: metadata.maturity });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return { domains, excluded };
|
|
231
|
+
}
|
|
227
232
|
function createDispatch() {
|
|
228
233
|
const handlers3 = /* @__PURE__ */ new Map();
|
|
229
234
|
function registerNap2(domain, handler) {
|
|
@@ -5583,6 +5588,9 @@ var NappletShimPrelude = (() => {
|
|
|
5583
5588
|
if (!options || !Array.isArray(options.domains)) {
|
|
5584
5589
|
throw new TypeError("Napplet runtime prelude requires an explicit domains array");
|
|
5585
5590
|
}
|
|
5591
|
+
if (options.maturity) {
|
|
5592
|
+
return [...selectNapDomains({ ...options.maturity, candidates: options.domains }).domains];
|
|
5593
|
+
}
|
|
5586
5594
|
return options.domains.filter((domain) => KNOWN_DOMAINS.has(domain));
|
|
5587
5595
|
}
|
|
5588
5596
|
function installNappletRuntimePrelude(options) {
|
|
@@ -5607,9 +5615,9 @@ var NappletShimPrelude = (() => {
|
|
|
5607
5615
|
@scure/base/index.js:
|
|
5608
5616
|
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
5609
5617
|
*/
|
|
5610
|
-
//# sourceMappingURL=prelude.global.js.map`,
|
|
5618
|
+
//# sourceMappingURL=prelude.global.js.map`,Ui=/\bwindow\s*\.\s*nostr\b|\bglobalThis\s*\.\s*nostr\b/,Ai="/__conformance__/events",fn=new URLSearchParams(location.search),Nt=fn.get("live")==="1";function te(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const se=document.getElementById("app");function Pi(){return se.innerHTML=`
|
|
5611
5619
|
<header class="masthead">
|
|
5612
|
-
<h1>napplet conformance ${
|
|
5620
|
+
<h1>napplet conformance ${Nt?'<span class="live-badge" id="live-badge">● live</span>':""}</h1>
|
|
5613
5621
|
<p>Load a napplet by <code>nevent</code> or <code>naddr</code> and run NAP protocol conformance live. Same engine as <code>napplet-conformance</code> CI.</p>
|
|
5614
5622
|
</header>
|
|
5615
5623
|
<form id="run-form" class="runbar">
|
|
@@ -5619,22 +5627,22 @@ var NappletShimPrelude = (() => {
|
|
|
5619
5627
|
</form>
|
|
5620
5628
|
<p id="status" class="status" role="status"></p>
|
|
5621
5629
|
<section id="output" class="output"></section>
|
|
5622
|
-
`,{targetInput:
|
|
5630
|
+
`,{targetInput:se.querySelector("#target"),runButton:se.querySelector("#run"),rerunButton:se.querySelector("#rerun"),liveBadge:se.querySelector("#live-badge")??document.createElement("span"),status:se.querySelector("#status"),output:se.querySelector("#output")}}const N=Pi();let Re="",gn=0;function Ae(e,n="info"){N.status.textContent=e,N.status.dataset.kind=n}function rn(e){return String(e).padStart(2,"0")}function ji(e){const n=new Date(e);return`${rn(n.getHours())}:${rn(n.getMinutes())}:${rn(n.getSeconds())}`}function Oi(e){const n=e.ok?"conformant":"non-conformant",t=[...new Set(e.checks.map(o=>o.area))].map(o=>{const l=e.checks.filter(a=>a.area===o).map(a=>{const c=a.severity==="warning"&&a.status==="fail"?' <span class="tag warn">warning</span>':"",h=a.detail?`<span class="detail">${te(a.detail)}</span>`:"";return`<li class="check ${a.status}"><span class="badge ${a.status}">${a.status}</span><span class="id">${te(a.id)}</span>${c}${h}</li>`}).join("");return`<div class="area"><h3>${te(o)}</h3><ul>${l}</ul></div>`}).join(""),r=e.summary,i=gn>1?`<span class="run-stamp">run #${gn} · ${ji(e.finishedAt)}</span>`:"";return`
|
|
5623
5631
|
<div class="verdict ${n}">
|
|
5624
5632
|
<span class="result">${e.ok?"CONFORMANT":"NON-CONFORMANT"}</span>
|
|
5625
|
-
<span class="counts">${
|
|
5633
|
+
<span class="counts">${r.passed} passed · ${r.failed} failed · ${r.skipped} skipped${r.warnings?` · ${r.warnings} warning(s)`:""}</span>
|
|
5626
5634
|
${i}
|
|
5627
5635
|
</div>
|
|
5628
5636
|
<div class="checks">${t}</div>
|
|
5629
|
-
`}function
|
|
5637
|
+
`}function qi(e){return e.length===0?'<p class="empty">No envelopes were emitted.</p>':`<ul class="envlog">${e.map(s=>{const t=s.verdict.ok?"ok":"bad",r=s.verdict.ok?"":`<div class="errs">${s.verdict.errors.map(i=>te(`${i.code}: ${i.message}`)).join("<br>")}</div>`;return`<li class="env ${t}"><code>${te(JSON.stringify(s.envelope))}</code>${r}</li>`}).join("")}</ul>`}function Ci(e){const n=(s,t)=>`<tr><th>${te(s)}</th><td>${t?te(String(t)):"<em>—</em>"}</td></tr>`;if(e.manifestEvent){const s=e.manifestEvent,t=ze(s);return`
|
|
5630
5638
|
<table class="manifest">
|
|
5631
|
-
${
|
|
5639
|
+
${Ys(s,t).map(([r,i])=>n(r,i)).join("")}
|
|
5632
5640
|
</table>
|
|
5633
|
-
${t.errors.length?`<div class="errs">${t.errors.map(
|
|
5634
|
-
`}return e.fetched?'<p class="empty">Local URL mode booted raw HTML. It does not include a signed NIP-5D manifest event, so manifest-event checks are skipped.</p>':`<p class="empty">Couldn't fetch the local URL HTML, likely because of CORS. Use a NIP-19 <code>nevent</code>/<code>naddr</code> for authoritative manifest checks, or use the CLI for local URL runs.</p>`}function
|
|
5635
|
-
${
|
|
5641
|
+
${t.errors.length?`<div class="errs">${t.errors.map(r=>te(`${r.code}: ${r.message}`)).join("<br>")}</div>`:""}
|
|
5642
|
+
`}return e.fetched?'<p class="empty">Local URL mode booted raw HTML. It does not include a signed NIP-5D manifest event, so manifest-event checks are skipped.</p>':`<p class="empty">Couldn't fetch the local URL HTML, likely because of CORS. Use a NIP-19 <code>nevent</code>/<code>naddr</code> for authoritative manifest checks, or use the CLI for local URL runs.</p>`}function Ni(e,n,s){N.output.innerHTML=`
|
|
5643
|
+
${Oi(e)}
|
|
5636
5644
|
<div class="panels">
|
|
5637
|
-
<section class="panel"><h2>Emitted envelopes (${n.length})</h2>${
|
|
5638
|
-
<section class="panel"><h2>Manifest</h2>${
|
|
5645
|
+
<section class="panel"><h2>Emitted envelopes (${n.length})</h2>${qi(n)}</section>
|
|
5646
|
+
<section class="panel"><h2>Manifest</h2>${Ci(s)}</section>
|
|
5639
5647
|
</div>
|
|
5640
|
-
`}async function
|
|
5648
|
+
`}async function Ye(e){Re=e,N.runButton.disabled=!0,N.rerunButton.disabled=!0;let n=null;try{Ae(`Resolving ${e} …`),n=await xi(e);const s=Ui.test(n.html)?["window.nostr"]:[];Ae("Booting napplet in a sandboxed iframe …");const t=await Fs({url:n.bootUrl,html:n.html,readyTimeoutMs:5e3,settleMs:800,runDegraded:!0,runtimePreludeSource:Mi}),r=Cs({manifestHtml:n.html,manifestEvent:n.manifestEvent,boot:t,forbiddenGlobals:s}),i=Ks(r);gn+=1,Ae(i.ok?"Done — conformant.":"Done — non-conformant.",i.ok?"info":"error"),Ni(i,t.emitted,n),N.rerunButton.hidden=!1}catch(s){Ae(`Error: ${s instanceof Error?s.message:String(s)}`,"error")}finally{n?.revoke?.(),N.runButton.disabled=!1,N.rerunButton.disabled=!1}}function Hi(){if(!Nt||typeof EventSource>"u")return;let e=!1;const n=new EventSource(Ai);n.addEventListener("rerun",()=>{!Re||e||(e=!0,setTimeout(()=>{e=!1,Ye(Re)},50))}),n.addEventListener("open",()=>{N.liveBadge&&(N.liveBadge.dataset.state="connected")}),n.addEventListener("error",()=>{N.liveBadge&&(N.liveBadge.dataset.state="disconnected")})}N.runButton.parentElement.addEventListener("submit",e=>{e.preventDefault();const n=N.targetInput.value.trim();if(n){const s=new URL(location.href);s.searchParams.set("target",n),s.searchParams.delete("url"),history.replaceState(null,"",s),Ye(n)}});N.rerunButton.addEventListener("click",()=>{Re&&Ye(Re)});Hi();const on=fn.get("target")??fn.get("url");on&&(N.targetInput.value=on,Ye(on));
|