@napplet/conformance-cli 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -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"],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"}},Bt=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),Nt=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 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 Qn=e=>n=>Array.isArray(n)&&n.length>0&&n.every(e),$t=_e({type:Ee("text"),text:Bt}),Lt=_e({type:Ee("image"),mimeType:Ee("image/png","image/jpeg","image/webp"),data:Nt}),Ft=e=>$t(e)||Lt(e),Wt=_e({role:Ee("system","user","assistant"),content:Qn(Ft)}),Gt=_e({},{model:we,images:Rn,json:Rn}),Vt=_e({handle:we,messages:Qn(Wt)},{format:Ee("text","json")}),zt={"llm.select":{optional:{requirements:Gt}},"llm.describe":{required:{handle:we}},"llm.generate":{required:{request:Vt}},"llm.cancel":{required:{requestId:we}}};function Qt(e,n,s){const t=zt[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 Le(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:Le(e)===n}function Zt(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&&Le(s.behavior)!=="object"&&n.push({code:"wrong-type",message:'Intent request field "behavior" must be an object',field:"request.behavior"}),s.handlerHint!==void 0&&Yt(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 Yt(e,n){if(Le(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 Kn(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 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[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&&Kn(i.servers,`${r}.servers`,n)}}}function es(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=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 s)||s[a]===void 0){n.push({code:"missing-field",message:`Required field "${a}" is missing`,field:a});continue}Kt(s[a],d)||n.push({code:"wrong-type",message:`Field "${a}" should be ${d} but is ${Le(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"&&Qt(t,s,n),t==="intent.invoke"&&Zt(s.request,n),t==="resource.bytes"&&Xt(s,n),t==="resource.bytesMany"&&Jt(s.requests,n),{ok:n.length===0,type:t,domain:i,direction:"out",errors:n}}var Zn=5129,ns=15129,ce=35129,gn=[Zn,ns,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(s=>s[0]===n)}function ts(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 ss(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 rs(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=c=>{n.push({code:"invalid-presentation-media",message:`Ignore ${s} tag: ${c} (NIP-5D §Presentation media)`})},r=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=r.get(y)??[];w!==void 0?P.push(w):P.push(""),r.set(y,P)}const i=r.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=r.get(c);if(y){if(y.length!==1||!m(y[0])){n.push({code:"invalid-presentation-media",message:`Ignore ${c} field on ${s} ${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(!(s==="preview"?a.toLowerCase().startsWith("video/"):Yn.includes(a.toLowerCase())))return t(`${a} cannot match a decodable ${s==="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)),s==="preview"){const c=l("duration",m=>/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/.test(m));c!==void 0&&(o.duration=Number(c))}const f=l("alt",c=>c.trim().length>0);return f!==void 0&&(o.alt=f),o}function We(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=et(e),r=ss(e);ts(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"}),is(e,n,s),os(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 is(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 os(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||!kn(i[1]))&&n.push({code:"invalid-metadata",message:"source must contain one HTTP(S), SSH, Git, SCP, or nostr repository location"});as(e,t.length===1&&t[0].length===2&&kn(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||!Fe(i[1])||!Yn.includes(i[2])))&&s.push({code:"invalid-icon",message:"Ignore invalid icon metadata and use generic artwork (NIP-5D §Icon)"}),s.push(...rs(e).warnings)}function as(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||!ls(o[1])||!Fe(o[2])||!Xn.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 ls(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 kn(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),ds={id:"reference-source-endpoint",catalogId:"reference-source"},cs="https://reference.invalid/blob",us=`named:${de}:reference-handler`,fs={kind:35129,pubkey:de,id:"0".repeat(64),tags:[["d","reference-handler"],["z","note"],["i","napplet:note/open","event"]]},ps="reference-subscriber",ms="napplet:note/open";function xe(e,n,s){return p({type:e,id:n,result:{entries:[s]}})}var p=e=>[e],j=()=>[];function xn(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,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 gs={"gamepad.subscribe":()=>p({type:"gamepad.state",available:!1,reason:"unavailable",focused:!1,pads:[]}),"gamepad.unsubscribe":j,"relay.subscribe":e=>p({type:"relay.eose",subId:e.subId}),"relay.close":j,"relay.publish":e=>p({type:"relay.publish.result",id:e.id,ok:!0,event:e.event}),"relay.publishEncrypted":e=>p({type:"relay.publishEncrypted.result",id:e.id,ok:!0,event:e.event}),"relay.query":e=>p({type:"relay.query.result",id:e.id,events:[]}),"identity.getPublicKey":e=>p({type:"identity.getPublicKey.result",id:e.id,pubkey:de}),"identity.getRelays":e=>p({type:"identity.getRelays.result",id:e.id,relays:{}}),"identity.getProfile":e=>p({type:"identity.getProfile.result",id:e.id,profile:null}),"identity.getFollows":e=>p({type:"identity.getFollows.result",id:e.id,pubkeys:[]}),"identity.getList":e=>p({type:"identity.getList.result",id:e.id,entries:[]}),"identity.getZaps":e=>p({type:"identity.getZaps.result",id:e.id,zaps:[]}),"identity.getMutes":e=>p({type:"identity.getMutes.result",id:e.id,pubkeys:[]}),"identity.getBlocked":e=>p({type:"identity.getBlocked.result",id:e.id,pubkeys:[]}),"identity.getBadges":e=>p({type:"identity.getBadges.result",id:e.id,badges:[]}),"storage.get":e=>p({type:"storage.get.result",id:e.id,value:null}),"storage.set":e=>p({type:"storage.set.result",id:e.id}),"storage.remove":e=>p({type:"storage.remove.result",id:e.id}),"storage.keys":e=>p({type:"storage.keys.result",id:e.id,keys:[]}),"inc.emit":j,"inc.subscribe":e=>p({type:"inc.subscribe.result",id:e.id}),"inc.unsubscribe":j,"inc.channel.open":e=>p({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=>p({type:"inc.channel.list.result",id:e.id,channels:[]}),"inc.channel.close":j,"theme.get":e=>p({type:"theme.get.result",id:e.id,theme:{colors:{background:"#000000",text:"#ffffff",primary:"#663399"}}}),"keys.forward":j,"keys.registerAction":e=>p({type:"keys.registerAction.result",id:e.id,actionId:`action-${String(e.id)}`}),"keys.unregisterAction":j,"media.session.create":e=>p({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=>p({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=>p({type:"notify.permission.result",id:e.id,granted:!0}),"config.registerSchema":e=>p({type:"config.registerSchema.result",id:e.id,ok:!0}),"config.get":e=>p({type:"config.values",id:e.id,values:{}}),"config.subscribe":()=>p({type:"config.values",values:{}}),"config.unsubscribe":j,"config.openSettings":j,"resource.bytes":e=>{const n=xn(e.url);return p(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=>p({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=xn(s);return{url:typeof s=="string"?s:"",ok:!0,blob:t?.blob??new Blob([]),mime:t?.mime??"application/octet-stream"}}):[]}),"resource.info":e=>p({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=>p({type:"cvm.discover.result",id:e.id,servers:[]}),"cvm.request":e=>p({type:"cvm.request.result",id:e.id,message:{}}),"cvm.close":e=>p({type:"cvm.close.result",id:e.id}),"outbox.getEvent":e=>p({type:"outbox.getEvent.result",id:e.id}),"outbox.query":e=>p({type:"outbox.query.result",id:e.id,events:[]}),"outbox.subscribe":e=>p({type:"outbox.closed",subId:e.subId,reason:"reference shell complete"}),"outbox.close":j,"outbox.publish":e=>p({type:"outbox.publish.result",id:e.id,ok:!0}),"outbox.resolveRelays":e=>p({type:"outbox.resolveRelays.result",id:e.id,plan:{}}),"upload.info":e=>p({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=>p({type:"upload.upload.result",id:e.id,result:{url:cs}}),"upload.status":e=>p({type:"upload.status.result",id:e.id,status:{}}),"ble.open":e=>p({type:"ble.open.result",id:e.id,session:{id:"ble-reference",state:"open",device:{id:"reference-device",name:"Reference BLE"}}}),"ble.services":e=>p({type:"ble.services.result",id:e.id,services:[]}),"ble.read":e=>p({type:"ble.read.result",id:e.id,data:[]}),"ble.write":e=>p({type:"ble.write.result",id:e.id}),"ble.subscribe":e=>p({type:"ble.subscribe.result",id:e.id}),"ble.unsubscribe":e=>p({type:"ble.unsubscribe.result",id:e.id}),"ble.close":e=>p({type:"ble.close.result",id:e.id}),"common.encodeNip19":e=>p({type:"common.encodeNip19.result",id:e.id,ok:!0,value:"npub1reference",nip19Type:"npub"}),"common.decodeNip19":e=>p({type:"common.decodeNip19.result",id:e.id,ok:!0,nip19Type:"npub",hex:de}),"common.getProfile":e=>p({type:"common.getProfile.result",id:e.id,ok:!0,pubkey:de,profile:null}),"common.follows":e=>p({type:"common.follows.result",id:e.id,ok:!0,pubkeys:[]}),"common.follow":e=>p({type:"common.follow.result",id:e.id,ok:!0}),"common.unfollow":e=>p({type:"common.unfollow.result",id:e.id,ok:!0}),"common.react":e=>p({type:"common.react.result",id:e.id,ok:!0,eventId:"0".repeat(64)}),"common.report":e=>p({type:"common.report.result",id:e.id,ok:!0,eventId:"1".repeat(64)}),"webrtc.open":e=>p({type:"webrtc.open.result",id:e.id,session:{id:"webrtc-reference",scope:{type:"direct",pubkey:de},channel:"default",state:"connecting"}}),"webrtc.send":e=>p({type:"webrtc.send.result",id:e.id}),"webrtc.close":e=>p({type:"webrtc.close.result",id:e.id}),"link.open":e=>p({type:"link.open.result",id:e.id,status:"opened"}),"count.query":e=>p({type:"count.query.result",id:e.id,ok:!0,count:0}),"lists.supported":e=>p({type:"lists.supported.result",id:e.id,lists:[]}),"lists.add":e=>p({type:"lists.add.result",id:e.id,ok:!0,added:0,skipped:0}),"lists.remove":e=>p({type:"lists.remove.result",id:e.id,ok:!0,removed:0,skipped:0}),"serial.open":e=>p({type:"serial.open.result",id:e.id,session:{id:`serial-${String(e.id)}`,state:"open"}}),"serial.write":e=>p({type:"serial.write.result",id:e.id}),"serial.close":e=>p({type:"serial.close.result",id:e.id}),"fs.info":e=>p({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=>p({type:"fs.stat.result",id:e.id,metadata:{path:e.path,kind:"file",size:0}}),"fs.list":e=>p({type:"fs.list.result",id:e.id,entries:[]}),"fs.read":e=>p({type:"fs.read.result",id:e.id,result:{data:"",offset:0,bytesRead:0,eof:!0,size:0}}),"fs.write":e=>p({type:"fs.write.result",id:e.id,result:{bytesWritten:0,size:0}}),"fs.mkdir":e=>p({type:"fs.mkdir.result",id:e.id}),"fs.remove":e=>p({type:"fs.remove.result",id:e.id}),"fs.move":e=>p({type:"fs.move.result",id:e.id}),"fs.watch":e=>p({type:"fs.watch.result",id:e.id,watchId:`watch-${String(e.id)}`}),"fs.unwatch":e=>p({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 hs(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 st(e){return{handle:e,...tt}}function ys(e,n){const s=qe(n.requirements);if(s.model!==void 0&&s.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:st(t)}}function bs(e,n){const s=String(n.handle);return e.handles.has(s)?{model:st(s)}:be("selection-expired","Select a model again")}function vs(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 ws(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=vs(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 Es(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 Ss(e,n,s){const t=String(s.type),r=String(s.id),i=hs(e,n);switch(t){case"llm.select":return[{type:"llm.select.result",id:r,...ys(i,s)}];case"llm.describe":return[{type:"llm.describe.result",id:r,...bs(i,s)}];case"llm.generate":return structuredClone(ws(i,r,s));case"llm.cancel":return Es(i,r,s);default:return[{type:`${t}.result`,id:r,error:{code:"invalid-request",message:`Unknown operation ${t}`}}]}}function Ts(){const e=new Map;return{handle:(n,s)=>Ss(e,n,s),reset(){e.clear()}}}function _s(e){const n=new Set,s=Ts();return Object.assign((r,i)=>{const o=Rs(i),l=es(i);if(e.records.push({envelope:i,verdict:l,timestamp:e.now()}),!o||!l.ok)return[];const a=r.domains??$e;if(!a.includes(o.slice(0,o.indexOf("."))))return[];if(o==="shell.ready")return n.has(r.id)?[]:(n.add(r.id),p({type:"shell.init",capabilities:{domains:[...a]},services:[]}));const d=i;if(o.startsWith("llm."))return s.handle(r,d);if(o==="intent.invoke")return e.intents.handleInvoke(r,d);if(o==="intent.available")return p({type:"intent.available.result",id:d.id,availability:e.intents.availability(d.archetype)});if(o==="intent.handlers")return p({type:"intent.handlers.result",id:d.id,handlers:e.intents.handlers()});if(o==="inc.emit")return Is(r,d,e.queueDelivery);const h=gs[o];return h?h(d):[]},{reset(){s.reset()}})}function Rs(e){if(!e||typeof e!="object")return;const n=e.type;return typeof n=="string"?n:void 0}function Is(e,n,s){if(n.topic!==ms)return[];const t={type:"inc.event",topic:n.topic,sender:e.id};return"payload"in n&&(t.payload=n.payload),s(ps,t),[]}function ks(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 xs(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 Ms(e,n,s){const t=[];for(const r of e){const i=xs(r,n);if(!i.length)continue;const o=r.tags.find(a=>a[0]==="title")?.[1],l=ks(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 Us(e,n=[fs],s={note:us}){const t=r=>Ms(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(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 p({type:"intent.invoke.result",id:i.id,result:{ok:!1,error:"no handler"}});const{archetype:h,action:f,convention:c}=o;return e(d.id,structuredClone({type:"intent.deliver",delivery:{sender:r.catalogId,archetype:h,action:f,convention:c,..."payload"in o?{payload:o.payload}:{}}})),p({type:"intent.invoke.result",id:i.id,result:{ok:!0,archetype:h,action:f,convention:c,handler:d.id}})}}}function Ps(e={}){const n=[],s=As(),t=_s({now:e.now??Date.now,records:n,queueDelivery:s.queue,intents:Us(s.queue,e.manifests,e.defaults)});return{get records(){return n},handle:r=>t(ds,r),handleFrom:t,takeDeliveries:s.take,reset(){n.length=0,t.reset(),s.clear()}}}function As(){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 js(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 rt="__nappletConformance.error",it="__nappletConformance.installed";function Mn(e){return new Promise(n=>setTimeout(n,e))}function qs(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Os(){return`(() => {
|
|
78
2
|
const report = (reason) => {
|
|
79
|
-
try { window.parent.postMessage({ type: '${
|
|
3
|
+
try { window.parent.postMessage({ type: '${rt}', 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 Cs(e,n){const s=`window.parent.postMessage({ type: '${it}', 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 Hs(e,n,s,t){const r=`<base href="${qs(n)}">`,i=Cs(s,t).replace(/<\/script/gi,"<\\/script"),o=`<script>${Os()}<\/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 Ds(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 Bs(e){if(e==="about:blank")return"<!doctype html><html><head></head><body></body></html>";const n=Ds(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 Un(e,n,s,t){const r=Ps(),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=f=>{if(f.source!==i.contentWindow)return;const c=f.data;if(c&&typeof c=="object"&&c.type===it){l=c.installed===!0;return}if(c&&typeof c=="object"&&c.type===rt){o=`napplet boot error: ${String(c.reason??"unknown error")}`;return}const m=r.handle(f.data),y=f.source;for(const w of m)y?.postMessage(w,"*")};let d=!1;const h=new Promise(f=>{i.addEventListener("load",()=>{d=!0,f()},{once:!0})});t.addEventListener("message",a);try{const f=n.html??await Bs(n.url);i.srcdoc=Hs(f,n.url,e,n.runtimePreludeSource),(s.body??s.documentElement).appendChild(i)}catch(f){o=f instanceof Error?f.message:String(f)}if(!o){const f=Symbol("timeout");await Promise.race([h.then(()=>"loaded"),Mn(n.readyTimeoutMs).then(()=>f)])===f||!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:[...r.records]}}async function Ns(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=await Un($e,t,n,s);let i=null;{const o=await Un([],t,n,s);i={bootError:o.bootError,emitted:o.emitted}}return{installedGlobal:r.installedGlobal,bootError:r.bootError,emitted:r.emitted,degraded:i}}var $s=e=>({status:"pass",detail:e}),Ls=(e,n)=>({status:"fail",detail:e,diagnostics:n}),Fs=e=>({status:"skip",detail:e}),A={pass:$s,fail:Ls,skip:Fs};function Ws(e,n){const s=We(e.manifestEvent);return[...s.errors,...s.warnings].filter(t=>n.includes(t.code))}function me(e,n,s,t="error"){return{id:e,area:"manifest",severity:t,title:n,run:r=>{if(!r.manifestEvent)return A.skip("No NIP-5D manifest event was resolved");const i=Ws(r,s);return i.length?A.fail(i[0].message,i):A.pass()}}}var Gs=[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 s=n.map(t=>({envelope:t.envelope,errors:t.verdict.errors}));return A.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?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 Vs(e,n={}){const s=n.now??(()=>Date.now()),t=n.checks??Gs,r=s(),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:r,finishedAt:s(),checks:i,summary:o,ok:o.errors===0}}function zs(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",nt(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 Qs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function hn(e,n=""){if(!Number.isSafeInteger(e)||e<0){const s=n&&`"${n}" `;throw new Error(`${s}expected integer >= 0, got ${e}`)}}function $(e,n,s=""){const t=Qs(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 Ks(e,n){$(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 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",Zs=Array.from({length:256},(e,n)=>n.toString(16).padStart(2,"0"));function C(e){if($(e),ot)return e.toHex();let n="";for(let s=0;s<e.length;s++)n+=Zs[e[s]];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,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=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[r]=o*16+l}return t}function Oe(...e){let n=0;for(let t=0;t<e.length;t++){const r=e[t];$(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 Ys(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 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 Xs=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(s=>typeof s=="string"):n.every(s=>Number.isSafeInteger(s)):!1}function Js(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 ft(e,n){if(!dt(!1,n))throw new Error(`${e}: array of numbers expected`)}function er(...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 nr(e){const n=typeof e=="string"?e.split(""):e,s=n.length;ut("alphabet",n);const t=new Map(n.map((r,i)=>[r,i]));return{encode:r=>(an(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=>(an(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 tr(e=""){return Se("join",e),{encode:n=>(ut("join.decode",n),n.join(e)),decode:n=>(Se("join.decode",n),n.split(e))}}const pt=(e,n)=>n===0?e:pt(n,e%n),Ce=(e,n)=>e+(n-pt(e,n)),Ae=(()=>{let e=[];for(let n=0;n<40;n++)e.push(2**n);return e})();function ln(e,n,s,t){if(an(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(Ce(n,s)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${s} carryBits=${Ce(n,s)}`);let r=0,i=0;const o=Ae[n],l=Ae[s]-1,a=[];for(const d of e){if(ct(d),d>=o)throw new Error(`convertRadix2: invalid data word=${d} from=${n}`);if(r=r<<n|d,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=Ae[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 sr(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:s=>{if(!lt(s))throw new Error("radix2.encode input should be Uint8Array");return ln(Array.from(s),8,e,!n)},decode:s=>(ft("radix2.decode",s),Uint8Array.from(ln(s,e,8,n)))}}function jn(e){return Js(e),function(...n){try{return e.apply(null,n)}catch{}}}const dn=er(nr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),tr("")),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 On(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,dn.encode(ln([r%Ae[30]],30,5,!1))}function rr(e){const n=e==="bech32"?1:734539939,s=sr(5),t=s.decode,r=s.encode,i=jn(t);function o(f,c,m=90){Se("bech32.encode prefix",f),lt(c)&&(c=Array.from(c)),ft("bech32.encode",c);const y=f.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=f.toLowerCase(),q=On(P,c,n);return`${P}1${dn.encode(c)}${q}`}function l(f,c=90){Se("bech32.decode input",f);const m=f.length;if(m<8||c!==!1&&m>c)throw new TypeError(`invalid string length: ${m} (${f}). Expected (8..${c})`);const y=f.toLowerCase();if(f!==y&&f!==f.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 ${f}: expected "${J}"`);return{prefix:P,words:z}}const a=jn(l);function d(f){const{prefix:c,words:m}=l(f,!1);return{prefix:c,words:m,bytes:t(m)}}function h(f,c){return o(f,r(c))}return{encode:o,decode:l,encodeFromBytes:h,decodeToBytes:d,decodeUnsafe:a,fromWords:t,fromWordsUnsafe:i,toWords:r}}const Cn=rr("bech32");var Me=new TextDecoder("utf-8");new TextEncoder;var ir=5e3;function or(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),ar(e)}catch{return{type:"invalid",data:null}}}function ar(e){let{prefix:n,words:s}=Cn.decode(e,ir),t=new Uint8Array(Cn.fromWords(s));switch(n){case"nprofile":{let r=Ye(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=Ye(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=Ye(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 Ye(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 lr(e,n,s){return e&n^~e&s}function dr(e,n,s){return e&n^e&s^n&s}class cr{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),$(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),Ks(n,this),this.finished=!0;const{buffer:s,view:t,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,on(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(t,0),o=0);for(let f=o;f<r;f++)s[f]=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 d=a/4,h=this.get();if(d>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<d;f++)l.setUint32(4*f,h[f],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]),ur=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 fr extends cr{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 f=0;f<16;f++,s+=4)ne[f]=n.getUint32(s,!1);for(let f=16;f<64;f++){const c=ne[f-15],m=ne[f-2],y=K(c,7)^K(c,18)^c>>>3,w=K(m,17)^K(m,19)^m>>>10;ne[f]=w+ne[f-7]+y+ne[f-16]|0}let{A:t,B:r,C:i,D:o,E:l,F:a,G:d,H:h}=this;for(let f=0;f<64;f++){const c=K(l,6)^K(l,11)^K(l,25),m=h+c+lr(l,a,d)+ur[f]+ne[f]|0,w=(K(t,2)^K(t,13)^K(t,22))+dr(t,r,i)|0;h=d,d=a,a=l,l=o+m|0,o=i,i=r,r=t,t=m+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,d=d+this.G|0,h=h+this.H|0,this.set(t,r,i,o,l,a,d,h)}roundClean(){on(ne)}destroy(){this.set(0,0,0,0,0,0,0,0),on(this.buffer)}}class pr extends fr{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=Ys(()=>new pr,Xs(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 s=n&&`"${n}" `;throw new Error(s+"expected boolean, got type="+typeof e)}return e}function mr(e){if(typeof e=="bigint"){if(!yr(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(gr($(e)).reverse()))}function vn(e,n){hn(n),e=mr(e);const s=Y(e.toString(16).padStart(n*2,"0"));if(s.length!==n)throw new Error("number too large");return s}function ht(e,n){return vn(e,n).reverse()}function gr(e){return Uint8Array.from(e)}function hr(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 yr=e=>typeof e=="bigint"&&yn<=e;function br(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={},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 d=typeof a;if(d!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${d}`)}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 N=BigInt(0),B=BigInt(1),ie=BigInt(2),vt=BigInt(3),wt=BigInt(4),Et=BigInt(5),vr=BigInt(7),St=BigInt(8),wr=BigInt(9),Tt=BigInt(16);function V(e,n){const s=e%n;return s>=N?s:n+s}function F(e,n,s){let t=e;for(;n-- >N;)t*=t,t%=s;return t}function Bn(e,n){if(e===N)throw new Error("invert: expected non-zero number");if(n<=N)throw new Error("invert: expected positive modulus, got "+n);let s=V(e,n),t=n,r=N,i=B;for(;s!==N;){const l=t/s,a=t%s,d=r-i*l;t=s,s=a,r=i,i=d}if(t!==B)throw new Error("invert: does not exist");return V(r,n)}function wn(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+B)/wt,t=e.pow(n,s);return wn(e,t,n),t}function Er(e,n){const s=(e.ORDER-Et)/St,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 wn(e,l,n),l}function Sr(e){const n=Ge(e),s=Rt(e),t=s(n,n.neg(n.ONE)),r=s(n,t),i=s(n,n.neg(t)),o=(e+vr)/Tt;return(l,a)=>{let d=l.pow(a,o),h=l.mul(d,t);const f=l.mul(d,r),c=l.mul(d,i),m=l.eql(l.sqr(h),a),y=l.eql(l.sqr(f),a);d=l.cmov(d,h,m),h=l.cmov(c,f,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-B,s=0;for(;n%ie===N;)n/=ie,s++;let t=ie;const r=Ge(e);for(;Nn(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+B)/ie;return function(a,d){if(a.is0(d))return d;if(Nn(a,d)!==1)throw new Error("Cannot find square root");let h=s,f=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=B<<BigInt(h-y-1),q=a.pow(f,P);h=y,f=a.sqr(q),c=a.mul(c,f),m=a.mul(m,q)}return m}}function Tr(e){return e%wt===vt?_t:e%St===Et?Er:e%Tt===wr?Sr(e):Rt(e)}const _r=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rr(e){const n={ORDER:"bigint",BYTES:"number",BITS:"number"},s=_r.reduce((t,r)=>(t[r]="function",t),n);return bt(e,s),e}function Ir(e,n,s){if(s<N)throw new Error("invalid exponent, negatives unsupported");if(s===N)return e.ONE;if(s===B)return n;let t=e.ONE,r=n;for(;s>N;)s&B&&(t=e.mul(t,r)),r=e.sqr(r),s>>=B;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 Nn(e,n){const s=(e.ORDER-B)/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 kr(e,n){n!==void 0&&hn(n);const s=n!==void 0?n:e.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class xr{ORDER;BITS;BYTES;isLE;ZERO=N;ONE=B;_lengths;_sqrt;_mod;constructor(n,s={}){if(n<=N)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}=kr(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 V(n,this.ORDER)}isValid(n){if(typeof n!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof n);return N<=n&&n<this.ORDER}is0(n){return n===N}isValidNot0(n){return!this.is0(n)&&this.isValid(n)}isOdd(n){return(n&B)===B}neg(n){return V(-n,this.ORDER)}eql(n,s){return n===s}sqr(n){return V(n*n,this.ORDER)}add(n,s){return V(n+s,this.ORDER)}sub(n,s){return V(n-s,this.ORDER)}mul(n,s){return V(n*s,this.ORDER)}pow(n,s){return Ir(this,n,s)}div(n,s){return V(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=Tr(this.ORDER)),this._sqrt(this,n)}toBytes(n){return this.isLE?ht(n,this.BYTES):vn(n,this.BYTES)}fromBytes(n,s=!1){$(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 d=new Uint8Array(r);d.set(n,i?0:d.length-n.length),n=d}if(n.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+n.length);let a=i?gt(n):bn(n);if(l&&(a=V(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 xr(e,n)}function kt(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 Mr(e){const n=kt(e);return n+Math.ceil(n/2)}function Ur(e,n,s=!1){$(e);const t=e.length,r=kt(n),i=Mr(n);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?gt(e):bn(e),l=V(o,n-B)+B;return s?ht(l,r):vn(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 xt(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){xt(e,n);const s=Math.ceil(n/e)+1,t=2**(e-1),r=2**e,i=yt(e),o=BigInt(e);return{windows:s,windowSize:t,mask:i,maxNumber:r,shiftBy:o}}function Ln(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 d=n*t,h=d+Math.abs(l)-1,f=l===0,c=l<0,m=n%2!==0;return{nextN:a,offset:h,isZero:f,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 Pr{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}=Xe(s,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<r;d++)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=Xe(n,this.bits);for(let l=0;l<o.windows;l++){const{nextN:a,offset:d,isZero:h,isNeg:f,isNegF:c,offsetF:m}=Ln(t,l,o);t=a,h?i=i.add(De(c,s[m])):r=r.add(De(f,s[d]))}return Fn(t),{p:r,f:i}}wNAFUnsafe(n,s,t,r=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}=Ln(t,o,i);if(t=l,!d){const f=s[a];r=r.add(h?f.negate():f)}}return Fn(t),r}getPrecomputes(n,s,t){let r=Je.get(s);return r||(r=this.precomputeWindow(s,n),n!==1&&(typeof t=="function"&&(r=t(r)),Je.set(s,r))),r}cached(n,s,t){const r=en(n);return this.wNAF(r,this.getPrecomputes(r,n,t),s)}unsafe(n,s,t,r){const i=en(n);return i===1?this._unsafeLadder(n,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,n,t),s,r)}createCache(n,s){xt(s,this.bits),Mt.set(n,s),Je.delete(n)}hasCache(n){return en(n)!==1}}function Ar(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 Wn(e,n,s){if(n){if(n.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Rr(n),n}else return Ge(e,{isLE:s})}function jr(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 d=n[a];if(!(typeof d=="bigint"&&d>ue))throw new Error(`CURVE.${a} must be positive bigint`)}const r=Wn(n.p,s.Fp,t),i=Wn(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 qr(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)/Cr)/n;function Or(e,n,s){const[[t,r],[i,o]]=n,l=Gn(o*e,s),a=Gn(-r*e,s);let d=e-l*t-a*i,h=-l*r-a*o;const f=d<he,c=h<he;f&&(d=-d),c&&(h=-h);const m=yt(Math.ceil(br(s)/2))+je;if(d<he||d>=m||h<he||h>=m)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:d,k2neg:c,k2:h}}const he=BigInt(0),je=BigInt(1),Cr=BigInt(2),Ue=BigInt(3),Hr=BigInt(4);function Dr(e,n={}){const s=jr("weierstrass",e,n),{Fp:t,Fn:r}=s;let i=s.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=Nr(t,r);function h(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(k,g,b){const{x:E,y:S}=g.toAffine(),x=t.toBytes(E);if(Hn(b,"isCompressed"),b){h();const R=!t.isOdd(S);return Oe(Br(R),x)}else return Oe(Uint8Array.of(4),x,t.toBytes(S))}function c(k){$(k,void 0,"Point");const{publicKey:g,publicKeyUncompressed:b}=d,E=k.length,S=k[0],x=k.subarray(1);if(E===g&&(S===2||S===3)){const R=t.fromBytes(x);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(L){const O=L instanceof Error?": "+L.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(x.subarray(0,R)),v=t.fromBytes(x.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||f,y=n.fromBytes||c;function w(k){const g=t.sqr(k),b=t.mul(g,k);return t.add(t.add(b,t.mul(k,i.a)),i.b)}function P(k,g){const b=t.sqr(g),E=w(k);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),Hr),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(k,g,b=!1){if(!t.isValid(g)||b&&t.is0(g))throw new Error(`bad point coordinate ${k}`);return g}function Re(k){if(!(k instanceof U))throw new Error("Weierstrass Point expected")}function Ie(k){if(!a||!a.basises)throw new Error("no endo");return Or(k,a.basises,r.ORDER)}const ke=Dn((k,g)=>{const{X:b,Y:E,Z:S}=k;if(t.eql(S,t.ONE))return{x:b,y:E};const x=k.is0();g==null&&(g=x?t.ONE:t.inv(S));const R=t.mul(b,g),T=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:R,y:T}}),Ht=Dn(k=>{if(k.is0()){if(n.allowInfinityPoint&&!t.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:b}=k.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(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Tn(k,g,b,E,S){return b=new U(t.mul(b.X,k),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($(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 pe.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:x,Y:R,Z:T}=g,v=t.eql(t.mul(b,T),t.mul(x,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:x,Z:R}=this;let T=t.ZERO,v=t.ZERO,_=t.ZERO,I=t.mul(S,S),L=t.mul(x,x),O=t.mul(R,R),M=t.mul(S,x);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(L,v),v=t.add(L,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(x,R),O=t.add(O,O),I=t.mul(O,M),T=t.sub(T,I),_=t.mul(O,L),_=t.add(_,_),_=t.add(_,_),new U(T,v,_)}add(g){Re(g);const{X:b,Y:E,Z:S}=this,{X:x,Y:R,Z:T}=g;let v=t.ZERO,_=t.ZERO,I=t.ZERO;const L=i.a,O=t.mul(i.b,Ue);let M=t.mul(b,x),W=t.mul(E,R),G=t.mul(S,T),ae=t.add(b,E),D=t.add(x,R);ae=t.mul(ae,D),D=t.add(M,W),ae=t.sub(ae,D),D=t.add(b,S);let Q=t.add(x,T);return D=t.mul(D,Q),Q=t.add(M,G),D=t.sub(D,Q),Q=t.add(E,S),v=t.add(R,T),Q=t.mul(Q,v),v=t.add(W,G),Q=t.sub(Q,v),I=t.mul(L,D),v=t.mul(O,G),I=t.add(v,I),v=t.sub(W,I),I=t.add(W,I),_=t.mul(v,I),W=t.add(M,M),W=t.add(W,M),G=t.mul(L,G),D=t.mul(O,D),W=t.add(W,G),G=t.sub(M,G),G=t.mul(L,G),D=t.add(D,G),M=t.mul(W,D),_=t.add(_,M),M=t.mul(Q,D),v=t.mul(ae,v),v=t.sub(v,M),M=t.mul(ae,W),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(!r.isValidNot0(g))throw new Error("invalid scalar: out of range");let E,S;const x=R=>pe.cached(this,R,T=>$n(U,T));if(b){const{k1neg:R,k1:T,k2neg:v,k2:_}=Ie(g),{p:I,f:L}=x(T),{p:O,f:M}=x(_);S=L.add(M),E=Tn(b.beta,I,O,R,v)}else{const{p:R,f:T}=x(g);E=R,S=T}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(pe.hasCache(this))return this.multiply(g);if(b){const{k1neg:S,k1:x,k2neg:R,k2:T}=Ie(g),{p1:v,p2:_}=Ar(U,E,x,T);return Tn(b.beta,v,_,S,R)}else return pe.unsafe(E,g)}toAffine(g){return ke(this,g)}isTorsionFree(){const{isTorsionFree:g}=n;return o===je?!0:g?g(U,this):pe.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=r.BITS,pe=new Pr(U,n.endo?Math.ceil(_n/2):_n);return U.BASE.precompute(8),U}function Br(e){return Uint8Array.of(e?2:3)}function Nr(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")},$r={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Lr=BigInt(0),un=BigInt(2);function Fr(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),d=e*e*e%n,h=d*d*e%n,f=F(h,s,n)*h%n,c=F(f,s,n)*h%n,m=F(c,un,n)*d%n,y=F(m,r,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,s,n)*h%n,Re=F(J,o,n)*y%n,Ie=F(Re,t,n)*d%n,ke=F(Ie,un,n);if(!Be.eql(Be.sqr(ke),e))throw new Error("Cannot find square root");return ke}const Be=Ge(Ve.p,{sqrt:Fr}),fe=Dr(Ve,{Fp:Be,endo:$r}),Vn={};function Ne(e,...n){let s=Vn[e];if(s===void 0){const t=He(hr(e));s=Oe(t,t),Vn[e]=s}return He(Oe(s,...n))}const En=e=>e.toBytes(!0).slice(1),Sn=e=>e%un===Lr;function fn(e){const{Fn:n,BASE:s}=fe,t=n.fromBytes(e),r=s.multiply(t);return{scalar:Sn(r.y)?t:n.neg(t),bytes:En(r)}}function Ut(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);Sn(r)||(r=n.neg(r));const i=fe.fromAffine({x:e,y:r});return i.assertValidity(),i}const ve=bn;function Pt(...e){return fe.Fn.create(ve(Ne("BIP0340/challenge",...e)))}function zn(e){return fn(e).bytes}function Wr(e,n,s=at(32)){const{Fn:t}=fe,r=$(e,void 0,"message"),{bytes:i,scalar:o}=fn(n),l=$(s,32,"auxRand"),a=t.toBytes(o^ve(Ne("BIP0340/aux",l))),d=Ne("BIP0340/nonce",a,i,r),{bytes:h,scalar:f}=fn(d),c=Pt(h,i,r),m=new Uint8Array(64);if(m.set(h,0),m.set(t.toBytes(t.create(f+c*o)),32),!At(m,r,i))throw new Error("sign: Invalid signature produced");return m}function At(e,n,s){const{Fp:t,Fn:r,BASE:i}=fe,o=$(e,64,"signature"),l=$(n,void 0,"message"),a=$(s,32,"publicKey");try{const d=Ut(ve(a)),h=ve(o.subarray(0,32));if(!t.isValidNot0(h))return!1;const f=ve(o.subarray(32,64));if(!r.isValidNot0(f))return!1;const c=Pt(r.toBytes(h),En(d),l),m=i.multiplyUnsafe(f).add(d.multiplyUnsafe(r.neg(c))),{x:y,y:w}=m.toAffine();return!(m.is0()||!Sn(w)||y!==h)}catch{return!1}}const Z=(()=>{const s=(t=at(48))=>Ur(t,Ve.n);return{keygen:qr(s,zn),getPublicKey:zn,sign:Wr,verify:At,Point:fe,utils:{randomSecretKey:s,taggedHash:Ne,lift_x:Ut,pointToBytes:En},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var re=Symbol("verified"),Gr=e=>e instanceof Object;function Vr(e){if(!Gr(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 zr=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 Qr=class{generateSecretKey(){return Z.utils.randomSecretKey()}getPublicKey(n){return C(Z.getPublicKey(n))}finalizeEvent(n,s){const t=n;return t.pubkey=C(Z.getPublicKey(s)),t.id=nn(t),t.sig=C(Z.sign(Y(nn(t)),s)),t[re]=!0,t}verifyEvent(n){if(typeof n[re]=="boolean")return n[re];try{const s=nn(n);if(s!==n.id)return n[re]=!1,!1;const t=Z.verify(Y(n.sig),Y(s),Y(n.pubkey));return n[re]=t,t}catch{return n[re]=!1,!1}}};function Kr(e){if(!Vr(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(zr.encode(Kr(e)));return C(n)}var ze=new Qr;ze.generateSecretKey;ze.getPublicKey;ze.finalizeEvent;var Zr=ze.verifyEvent,Yr=22242;function Xr(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 Jr(e,n){for(let s=0;s<e.length;s++)if(Xr(e[s],n))return!0;return!1}function ei(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 ni(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 ti(e,n){return{kind:Yr,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 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 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(s,t)=>{try{let r=await e(ti(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 si(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=ni(n);if(s){const t=this.openSubs.get(s);if(!t)return;const r=ei(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)&&Jr(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}}},si=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 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)}},ri=e=>(e[re]=!0,!0),ii=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)?ri: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 c of e){const{url:m,filter:y}=c;s.has(m)||s.set(m,[]),s.get(m).push(y)}const t=Array.from(s.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 r=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=r.has(c);return r.add(c),m},f=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 f,i.forEach(m=>{m.close(c)})}}}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}},Ot;try{Ot=WebSocket}catch{}var oi=class extends ii{constructor(e){super({verifyEvent:Zr,websocketImplementation:Ot,maxWaitForConnection:3e3,...e})}},le=Symbol("verified"),ai=e=>e instanceof Object;function li(e){if(!ai(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 di=new TextEncoder,ci=class{generateSecretKey(){return Z.utils.randomSecretKey()}getPublicKey(e){return C(Z.getPublicKey(e))}finalizeEvent(e,n){const s=e;return s.pubkey=C(Z.getPublicKey(n)),s.id=tn(s),s.sig=C(Z.sign(Y(tn(s)),n)),s[le]=!0,s}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 s=Z.verify(Y(e.sig),Y(n),Y(e.pubkey));return e[le]=s,s}catch{return e[le]=!1,!1}}};function ui(e){if(!li(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(di.encode(ui(e)));return C(n)}var Qe=new ci;Qe.generateSecretKey;Qe.getPublicKey;Qe.finalizeEvent;var fi=Qe.verifyEvent;const pi=8e3;function mi(e){return typeof e=="number"&&gn.includes(e)}function gi(e){try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function hi(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 yi(e){const n=or(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=hi(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&&!mi(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?[...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:s,filter:{kinds:[ce],authors:[n.data.pubkey],"#d":[n.data.identifier],limit:1}}}function bi(e){return{id:e.id,pubkey:e.pubkey,kind:e.kind,tags:e.tags,content:e.content}}async function vi(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 wi(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 Ei(e,n){const s=e.endsWith("/")?e:`${e}/`;return new URL(n,s).href}async function Si(e,n=fetch){const s=We(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=wi(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=Ei(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 vi(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 Ti(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 _i(e,n){const s=yi(e),t=!n.pool,r=n.pool??new oi;try{const i=await r.get(s.relays,{...s.filter},{maxWait:n.maxRelayWaitMs??pi});if(!i)throw new Error("No matching napplet manifest event was found on the pointer relay hints");if(!fi(i))throw new Error("Resolved manifest event signature is invalid");const o=bi(i),l=We(o);if(!l.ok)throw new Error(`Resolved event is not a valid NIP-5D napplet manifest: ${l.errors[0]?.message}`);const a=await Si(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&&r.destroy()}}async function Ri(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 gi(s)?Ti(s,n.fetcher??fetch):_i(s,n)}const Ii=`"use strict";
|
|
197
11
|
var NappletShimPrelude = (() => {
|
|
198
12
|
var __defProp = Object.defineProperty;
|
|
199
13
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -5607,7 +5421,7 @@ var NappletShimPrelude = (() => {
|
|
|
5607
5421
|
@scure/base/index.js:
|
|
5608
5422
|
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
5609
5423
|
*/
|
|
5610
|
-
//# sourceMappingURL=prelude.global.js.map`,
|
|
5424
|
+
//# sourceMappingURL=prelude.global.js.map`,ki=/\bwindow\s*\.\s*nostr\b|\bglobalThis\s*\.\s*nostr\b/,xi="/__conformance__/events",pn=new URLSearchParams(location.search),Ct=pn.get("live")==="1";function te(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const se=document.getElementById("app");function Mi(){return se.innerHTML=`
|
|
5611
5425
|
<header class="masthead">
|
|
5612
5426
|
<h1>napplet conformance ${Ct?'<span class="live-badge" id="live-badge">● live</span>':""}</h1>
|
|
5613
5427
|
<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>
|
|
@@ -5619,22 +5433,22 @@ var NappletShimPrelude = (() => {
|
|
|
5619
5433
|
</form>
|
|
5620
5434
|
<p id="status" class="status" role="status"></p>
|
|
5621
5435
|
<section id="output" class="output"></section>
|
|
5622
|
-
`,{targetInput:
|
|
5436
|
+
`,{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 H=Mi();let Te="",mn=0;function Pe(e,n="info"){H.status.textContent=e,H.status.dataset.kind=n}function sn(e){return String(e).padStart(2,"0")}function Ui(e){const n=new Date(e);return`${sn(n.getHours())}:${sn(n.getMinutes())}:${sn(n.getSeconds())}`}function Pi(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 d=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>${d}${h}</li>`}).join("");return`<div class="area"><h3>${te(o)}</h3><ul>${l}</ul></div>`}).join(""),r=e.summary,i=mn>1?`<span class="run-stamp">run #${mn} · ${Ui(e.finishedAt)}</span>`:"";return`
|
|
5623
5437
|
<div class="verdict ${n}">
|
|
5624
5438
|
<span class="result">${e.ok?"CONFORMANT":"NON-CONFORMANT"}</span>
|
|
5625
|
-
<span class="counts">${
|
|
5439
|
+
<span class="counts">${r.passed} passed · ${r.failed} failed · ${r.skipped} skipped${r.warnings?` · ${r.warnings} warning(s)`:""}</span>
|
|
5626
5440
|
${i}
|
|
5627
5441
|
</div>
|
|
5628
5442
|
<div class="checks">${t}</div>
|
|
5629
|
-
`}function
|
|
5443
|
+
`}function Ai(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 ji(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=We(s);return`
|
|
5630
5444
|
<table class="manifest">
|
|
5631
|
-
${
|
|
5445
|
+
${zs(s,t).map(([r,i])=>n(r,i)).join("")}
|
|
5632
5446
|
</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
|
-
${
|
|
5447
|
+
${t.errors.length?`<div class="errs">${t.errors.map(r=>te(`${r.code}: ${r.message}`)).join("<br>")}</div>`:""}
|
|
5448
|
+
`}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 qi(e,n,s){H.output.innerHTML=`
|
|
5449
|
+
${Pi(e)}
|
|
5636
5450
|
<div class="panels">
|
|
5637
|
-
<section class="panel"><h2>Emitted envelopes (${n.length})</h2>${
|
|
5638
|
-
<section class="panel"><h2>Manifest</h2>${
|
|
5451
|
+
<section class="panel"><h2>Emitted envelopes (${n.length})</h2>${Ai(n)}</section>
|
|
5452
|
+
<section class="panel"><h2>Manifest</h2>${ji(s)}</section>
|
|
5639
5453
|
</div>
|
|
5640
|
-
`}async function Ke(e){Te=e,H.runButton.disabled=!0,H.rerunButton.disabled=!0;let n=null;try{Pe(`Resolving ${e} …`),n=await
|
|
5454
|
+
`}async function Ke(e){Te=e,H.runButton.disabled=!0,H.rerunButton.disabled=!0;let n=null;try{Pe(`Resolving ${e} …`),n=await Ri(e);const s=ki.test(n.html)?["window.nostr"]:[];Pe("Booting napplet in a sandboxed iframe …");const t=await Ns({url:n.bootUrl,html:n.html,readyTimeoutMs:5e3,settleMs:800,runDegraded:!0,runtimePreludeSource:Ii}),r=js({manifestHtml:n.html,manifestEvent:n.manifestEvent,boot:t,forbiddenGlobals:s}),i=Vs(r);mn+=1,Pe(i.ok?"Done — conformant.":"Done — non-conformant.",i.ok?"info":"error"),qi(i,t.emitted,n),H.rerunButton.hidden=!1}catch(s){Pe(`Error: ${s instanceof Error?s.message:String(s)}`,"error")}finally{n?.revoke?.(),H.runButton.disabled=!1,H.rerunButton.disabled=!1}}function Oi(){if(!Ct||typeof EventSource>"u")return;let e=!1;const n=new EventSource(xi);n.addEventListener("rerun",()=>{!Te||e||(e=!0,setTimeout(()=>{e=!1,Ke(Te)},50))}),n.addEventListener("open",()=>{H.liveBadge&&(H.liveBadge.dataset.state="connected")}),n.addEventListener("error",()=>{H.liveBadge&&(H.liveBadge.dataset.state="disconnected")})}H.runButton.parentElement.addEventListener("submit",e=>{e.preventDefault();const n=H.targetInput.value.trim();if(n){const s=new URL(location.href);s.searchParams.set("target",n),s.searchParams.delete("url"),history.replaceState(null,"",s),Ke(n)}});H.rerunButton.addEventListener("click",()=>{Te&&Ke(Te)});Oi();const rn=pn.get("target")??pn.get("url");rn&&(H.targetInput.value=rn,Ke(rn));
|