@vercel/cli-support 66.0.0 → 66.1.0-snapshot-2d6d3c32d821
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/add-6NUHCAMT.js +1 -1
- package/dist/chunks/add-GP25D55V.js +1 -1
- package/dist/chunks/{add-4BOS256T.js → add-KYJZONXY.js} +1 -1
- package/dist/chunks/{alerts-7YJBYDMI.js → alerts-MQ6Y3UFA.js} +1 -1
- package/dist/chunks/build-4VEEWVS5.js +1 -1
- package/dist/chunks/{chunk-PVLBQHWY.js → chunk-5PQVVJMD.js} +1 -1
- package/dist/chunks/chunk-MGZ3Z4PF.js +8 -0
- package/dist/chunks/chunk-PQSW6EAL.js +7 -0
- package/dist/chunks/{chunk-AOWC37HK.js → chunk-REKWV3XW.js} +1 -1
- package/dist/chunks/{chunk-ZJX3QG2F.js → chunk-TR4ENDFQ.js} +1 -1
- package/dist/chunks/chunk-UFCL2VBD.js +7 -0
- package/dist/chunks/chunk-WHL4PWDW.js +14 -0
- package/dist/chunks/{chunk-GQU7IE6F.js → chunk-XI7556MQ.js} +3 -3
- package/dist/chunks/{chunk-666NINFO.js → chunk-ZL3UMJMJ.js} +1 -1
- package/dist/chunks/clear-PLSWE5JH.js +1 -1
- package/dist/chunks/cli-embedded-KDIRH75G.js +81 -0
- package/dist/chunks/{config-KDYQYFS6.js → config-3LXTEKBJ.js} +1 -1
- package/dist/chunks/config-ORDPO5PD.js +1 -1
- package/dist/chunks/engine-I887QHnP-RUEEKCKH.js +18 -0
- package/dist/chunks/{image-5NJDI6SK.js → image-N5UWUO57.js} +1 -1
- package/dist/chunks/{inspect-MOJMM7QE.js → inspect-24Z5WVGT.js} +1 -1
- package/dist/chunks/inspect-33TQGRQI.js +1 -1
- package/dist/chunks/{inspect-QFX7W3LO.js → inspect-3TBVD5FW.js} +1 -1
- package/dist/chunks/inspect-GUVBQAGQ.js +1 -1
- package/dist/chunks/inspect-IVCRI5DD.js +1 -1
- package/dist/chunks/{list-ZAWJR23F.js → list-33O4PH2I.js} +1 -1
- package/dist/chunks/{list-3D4YRKNP.js → list-3ESADOVD.js} +1 -1
- package/dist/chunks/{list-VDUPJ44X.js → list-EZZOK7IM.js} +1 -1
- package/dist/chunks/login-2P4WOXB7.js +1 -1
- package/dist/chunks/ls-3VWIGXMW.js +1 -1
- package/dist/chunks/ls-76ADTPOK.js +1 -1
- package/dist/chunks/{ls-34MKKAM5.js → ls-H3VWUODQ.js} +1 -1
- package/dist/chunks/ls-KWYUFBK6.js +1 -1
- package/dist/chunks/ls-XBDD2PTU.js +1 -1
- package/dist/chunks/{notifications-AH37Q6MV.js → notifications-7R3WPEAA.js} +1 -1
- package/dist/chunks/{permissions-M2YMMWQ2.js → permissions-KNTBYUW6.js} +1 -1
- package/dist/chunks/push-PWMJ4P2K.js +1 -1
- package/dist/chunks/query-JNPBVPKH.js +1 -1
- package/dist/chunks/{raw-query-J5YDYUOK.js → raw-query-K2TZPPTU.js} +1 -1
- package/dist/chunks/rm-BYAPI3BU.js +1 -1
- package/dist/chunks/rm-CE52BWMX.js +1 -1
- package/dist/chunks/{rm-5K6VJI5E.js → rm-EFOCCDJP.js} +1 -1
- package/dist/chunks/rm-F2RNFFYF.js +1 -1
- package/dist/chunks/rule-inspect-BETOJVBA.js +1 -1
- package/dist/chunks/serving-Bulte-NO-VPBE6F4V.js +8 -0
- package/dist/chunks/update-5TDDKIDK.js +1 -1
- package/dist/commands/deploy/index.js +1 -1
- package/dist/commands/env/index.js +1 -1
- package/dist/commands/link/index.js +1 -1
- package/dist/commands/project/index.js +1 -1
- package/dist/commands-account.js +2 -2
- package/dist/commands-ai.js +74 -58
- package/dist/commands-blob.js +1 -1
- package/dist/commands-core.js +6 -6
- package/dist/commands-deployments.js +1 -1
- package/dist/commands-flags.js +1 -1
- package/dist/commands-integrations.js +1 -1
- package/dist/commands-observability.js +2 -2
- package/dist/commands-routing.js +1 -1
- package/dist/index.js +1 -1
- package/dist/package.json +3 -3
- package/dist/version.mjs +1 -1
- package/package.json +12 -12
- package/dist/chunks/chunk-BPQUJWX5.js +0 -11
- package/dist/chunks/chunk-MRCM5VF5.js +0 -8
- package/dist/chunks/chunk-SKYIWHB5.js +0 -7
- package/dist/chunks/chunk-TK7K6GCG.js +0 -7
- package/dist/chunks/cli-embedded-6SKYFUXJ.js +0 -65
- package/dist/chunks/engine-DkdkXQEy-VKQPUSSO.js +0 -17
- package/dist/chunks/serving-DKny38LK-WG5QDDEJ.js +0 -8
package/dist/version.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const version = "66.
|
|
1
|
+
export const version = "66.1.0-snapshot-2d6d3c32d821";
|
|
2
2
|
export const buildLabel = "";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vercel/cli-support",
|
|
3
|
-
"version": "66.
|
|
3
|
+
"version": "66.1.0-snapshot-2d6d3c32d821",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"description": "The JavaScript Vercel CLI, installed by vercel to run where its native binary can't",
|
|
@@ -33,29 +33,29 @@
|
|
|
33
33
|
"undici": "5.29.0",
|
|
34
34
|
"uuid": "14.0.1",
|
|
35
35
|
"zod": "4.6.7",
|
|
36
|
-
"@vercel/backends": "26.0.2",
|
|
37
36
|
"@vercel/build-utils": "15.4.2",
|
|
37
|
+
"@vercel/backends": "26.0.2",
|
|
38
38
|
"@vercel/cli-auth": "0.4.2",
|
|
39
39
|
"@vercel/container": "26.1.0",
|
|
40
40
|
"@vercel/cli-config": "0.4.0",
|
|
41
41
|
"@vercel/detect-agent": "1.2.7",
|
|
42
42
|
"@vercel/elysia": "26.0.2",
|
|
43
|
-
"@vercel/fastify": "26.0.2",
|
|
44
43
|
"@vercel/express": "26.0.2",
|
|
45
|
-
"@vercel/
|
|
44
|
+
"@vercel/fastify": "26.0.2",
|
|
46
45
|
"@vercel/go": "29.0.2",
|
|
47
|
-
"@vercel/hydrogen": "27.0.2",
|
|
48
|
-
"@vercel/koa": "26.0.2",
|
|
49
46
|
"@vercel/hono": "26.0.2",
|
|
47
|
+
"@vercel/koa": "26.0.2",
|
|
48
|
+
"@vercel/h3": "26.0.2",
|
|
49
|
+
"@vercel/hydrogen": "27.0.2",
|
|
50
50
|
"@vercel/nestjs": "26.0.2",
|
|
51
|
-
"@vercel/node": "31.0.2",
|
|
52
51
|
"@vercel/next": "30.1.0",
|
|
52
|
+
"@vercel/python": "32.1.0-snapshot-2d6d3c32d821",
|
|
53
53
|
"@vercel/python-analysis": "0.15.3",
|
|
54
|
-
"@vercel/
|
|
55
|
-
"@vercel/
|
|
54
|
+
"@vercel/node": "31.0.2",
|
|
55
|
+
"@vercel/remix-builder": "31.0.2",
|
|
56
56
|
"@vercel/ruby": "28.0.2",
|
|
57
|
+
"@vercel/redwood": "28.0.2",
|
|
57
58
|
"@vercel/rust": "27.0.2",
|
|
58
|
-
"@vercel/remix-builder": "31.0.2",
|
|
59
59
|
"@vercel/static-build": "28.0.2"
|
|
60
60
|
},
|
|
61
61
|
"builders": {
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
"@vercel/nestjs": "26.0.2",
|
|
73
73
|
"@vercel/next": "30.1.0",
|
|
74
74
|
"@vercel/node": "31.0.2",
|
|
75
|
-
"@vercel/python": "32.0
|
|
75
|
+
"@vercel/python": "32.1.0-snapshot-2d6d3c32d821",
|
|
76
76
|
"@vercel/redwood": "28.0.2",
|
|
77
77
|
"@vercel/remix-builder": "31.0.2",
|
|
78
78
|
"@vercel/ruby": "28.0.2",
|
|
@@ -80,7 +80,7 @@
|
|
|
80
80
|
"@vercel/static-build": "28.0.2"
|
|
81
81
|
},
|
|
82
82
|
"devDependencies": {
|
|
83
|
-
"@vercel-internals/cli-core": "66.
|
|
83
|
+
"@vercel-internals/cli-core": "66.1.0-snapshot-2d6d3c32d821"
|
|
84
84
|
},
|
|
85
85
|
"os": [
|
|
86
86
|
"aix",
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{HttpError,Labels,MESSAGE_TEXT_MAX,MessageId}from"./chunk-MRCM5VF5.js";import{external_exports}from"./chunk-2AMO2VMV.js";var ExternalTarget=external_exports.string().min(3).max(300),Origin=external_exports.object({channel:ExternalTarget.optional(),thread:ExternalTarget,subthread:ExternalTarget.nullable(),message:external_exports.string().min(1).max(300),context:external_exports.string().max(300).nullable()}),LinkSnapshot=external_exports.object({author:external_exports.string().min(1).max(256),text:external_exports.string().max(MESSAGE_TEXT_MAX),createdAt:external_exports.string().max(64).nullable(),files:external_exports.array(external_exports.object({name:external_exports.string().min(1).max(1e3),url:external_exports.string().max(4e3).nullable()})).max(20)}),Link=external_exports.object({url:external_exports.string().min(1).max(4e3),message:MessageId.nullable(),snapshot:LinkSnapshot.nullable(),unavailable:external_exports.string().max(300).nullable()}),ExternalAuthor=external_exports.object({id:external_exports.string().min(1),handle:external_exports.string().min(1),name:external_exports.string().min(1),avatar:external_exports.string().nullable(),isBot:external_exports.boolean()}),ExternalFile=external_exports.object({type:external_exports.enum(["image","file","video","audio"]),name:external_exports.string().max(1e3).optional(),mimeType:external_exports.string().max(255).optional(),size:external_exports.number().int().nonnegative().optional(),url:external_exports.string().max(4e3).optional(),fetchMetadata:external_exports.record(external_exports.string(),external_exports.string().max(4e3)).optional()}),ExternalLink=external_exports.object({url:external_exports.string().min(1).max(4e3),thread:ExternalTarget,message:external_exports.string().min(1).max(300),snapshot:LinkSnapshot.nullable()}),ExternalLocation=external_exports.object({channel:ExternalTarget,thread:ExternalTarget,subthread:ExternalTarget.nullable()}),ExternalEvent=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("message"),...ExternalLocation.shape,message:external_exports.string(),isRoot:external_exports.boolean(),text:external_exports.string(),context:external_exports.string().nullable(),author:ExternalAuthor,files:external_exports.array(ExternalFile).max(20).optional(),links:external_exports.array(ExternalLink).max(10).optional()}),external_exports.object({kind:external_exports.literal("edited"),...ExternalLocation.shape,message:external_exports.string(),text:external_exports.string(),author:ExternalAuthor,links:external_exports.array(ExternalLink).max(10).optional(),linksOnly:external_exports.boolean().optional()}),external_exports.object({kind:external_exports.literal("deleted"),...ExternalLocation.shape,message:external_exports.string()}),external_exports.object({kind:external_exports.literal("reaction"),...ExternalLocation.shape,message:external_exports.string(),emoji:external_exports.string(),added:external_exports.boolean(),author:ExternalAuthor}),external_exports.object({kind:external_exports.literal("lifecycle"),...ExternalLocation.omit({subthread:!0}).shape,type:external_exports.string(),title:external_exports.string(),url:external_exports.string().nullable(),body:external_exports.string().nullable().optional(),labels:external_exports.record(external_exports.string(),external_exports.string()),unset:external_exports.array(external_exports.string()),owns:external_exports.array(external_exports.string()).optional(),reply:external_exports.string().nullable(),createRoot:external_exports.boolean(),retitled:external_exports.boolean().optional(),author:ExternalAuthor})]),isThreadTarget=target=>target.slice(target.indexOf(":")+1).includes(":"),channelOf=externalThread=>{let at=externalThread.indexOf(":"),colon=externalThread.slice(at+1).indexOf(":");return colon===-1?externalThread:externalThread.slice(0,at+1+colon)},externalMessageKey=(thread,message)=>`${thread}|${message}`;var hex=bytes=>Array.from(bytes,byte=>byte.toString(16).padStart(2,"0")).join("");async function sha256(text){return hex(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(text))))}async function derivedId(...parts){let bytes=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(parts)))).slice(0,16);bytes[6]=bytes[6]&15|128,bytes[8]=bytes[8]&63|128;let text=hex(bytes);return`${text.slice(0,8)}-${text.slice(8,12)}-${text.slice(12,16)}-${text.slice(16,20)}-${text.slice(20,32)}`}var DERIVED_ID=/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,keyId=async(principal,derived)=>`key:${principal}:${(await sha256(`board-key${derived}`)).slice(0,32)}`;function waitUntil(task){try{Reflect.get(globalThis,Symbol.for("@vercel/request-context"))?.get?.()?.waitUntil?.(task)}catch{}}var FENCED_CODE=/```[\s\S]*?```/g,INLINE_CODE=/`[^`\n]*`/g,NAME="[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?",MENTION=new RegExp(`(?<![\\w@.-])@(${NAME}(?:/${NAME})?)(?!:|[a-z0-9_/-]|\\.(?=[a-z0-9]))`,"gi"),EXACT=/(?<![\w@.-])@\[([^\]\s]+)\]/g,proseOnly=text=>text.replace(FENCED_CODE,match=>" ".repeat(match.length)).replace(INLINE_CODE,match=>" ".repeat(match.length));function extractMentions(text){let prose=proseOnly(text),found=[];for(let match of prose.matchAll(EXACT)){let actor=match[1];actor!==void 0&&found.push({index:match.index,token:{kind:"actor",actor},key:`actor:${actor}`})}for(let match of prose.replace(EXACT,m=>" ".repeat(m.length)).matchAll(MENTION)){let handle=match[1]?.toLowerCase();handle!==void 0&&found.push({index:match.index,token:{kind:"handle",handle},key:`handle:${handle}`})}let seen=new Set;return found.sort((a,b)=>a.index-b.index).filter(({key})=>!seen.has(key)&&seen.add(key)).map(({token})=>token)}function replaceMentions(text,replace){let prose=proseOnly(text),found=[];for(let match of prose.matchAll(EXACT))found.push({index:match.index,length:match[0].length,token:{kind:"actor",actor:match[1]}});for(let match of prose.replace(EXACT,m=>" ".repeat(m.length)).matchAll(MENTION))found.push({index:match.index,length:match[0].length,token:{kind:"handle",handle:match[1].toLowerCase()}});let out="",at=0;for(let{index,length,token}of found.sort((a,b)=>a.index-b.index)){let written=text.slice(index,index+length);out+=text.slice(at,index)+(replace(token,written)??written),at=index+length}return out+text.slice(at)}var DroppedError=class extends HttpError{responses;constructor(responses){super(422,"dropped",responses.join(`
|
|
8
|
-
`)||"the board dropped this message"),this.responses=responses}},Patch=external_exports.object({text:external_exports.string().max(MESSAGE_TEXT_MAX).optional(),labels:Labels.optional()}).strict();async function runMiddleware(middleware,input,commit){let responses=[],committed=null,step=async(i,write)=>{if(i===middleware.length){if(write.text.trim()===""&&(write.kind==="edit"||write.attachments.length===0))return;committed={value:await commit(write)};return}let next=null;await middleware[i]({write:Object.freeze({...write}),author:Object.freeze({...input.author}),source:Object.freeze({...input.source}),board:input.board(),respond:async text=>{responses.push(text)},next:(patch={})=>{if(next)throw new Error("next() was already called");let{text,labels}=Patch.parse(patch);return next=step(i+1,{...write,...text!==void 0?{text}:{},...write.kind==="post"&&labels?{labels:{...write.labels,...labels}}:{}}),next}}),next&&await next};if(await step(0,input.write),!committed)throw new DroppedError(responses);return committed.value}var VERCEL_MARKER=/^\[vc\]: #\S*\r?\n/,LINK=/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,STATUS=/!\[([^\]]+)\]\(https:\/\/vercel\.com\/static\/status\/[^)]+\)\s*(?:\[[^\]]*\]\((https?:\/\/[^)\s]+)\))?/;function vercelDeployments(text){if(!VERCEL_MARKER.test(text))return null;let skippedAt=text.search(/<details><summary>\d+ Skipped Deployments?<\/summary>/),deployments=[],offset=0;for(let line of text.split(/\r?\n/)){let at=offset;if(offset=text.indexOf(`
|
|
9
|
-
`,offset)+1||text.length,!line.startsWith("|")||/^\|\s*(Project|Name)\s*\|/.test(line)||/^\|\s*:?-/.test(line))continue;let cells=line.split("|").slice(1,-1).map(cell=>cell.trim());if(cells.length<2)continue;let status=STATUS.exec(cells[1]);if(!status)continue;let projectLink=[...cells[0].matchAll(LINK)].at(-1),project=projectLink?.[1]??cells[0].replace(/<[^>]*>/g,"").trim();if(!project)continue;let preview=cells[2]?[...cells[2].matchAll(LINK)].find(link2=>/preview/i.test(link2[1])):void 0,updated=cells[3]?.match(/<relative-time[^>]*>([^<]+)<\/relative-time>/)?.[1]?.trim()??(cells[3]?.replace(/<[^>]*>/g,"").trim()||null);deployments.push({project,projectUrl:projectLink?.[2]??null,status:status[1].trim(),deploymentUrl:status[2]??null,previewUrl:preview?.[2]??null,updated,skipped:skippedAt!==-1&&at>skippedAt})}return deployments.length>0?deployments:null}var ICONS={ready:"\u2705",building:"\u23F3",queued:"\u23F3",initializing:"\u23F3",error:"\u274C",failed:"\u274C",canceled:"\u26AA",ignored:"\u26AA"},link=(label,url)=>url?`[${label}](${url})`:label;function formatVercelDeployments(deployments){return deployments.map(d=>`- ${[`${ICONS[d.status.toLowerCase()]??"\u25B2"} **${link(d.project,d.projectUrl)}**`,`${link(d.status,d.deploymentUrl)}${d.skipped?" (skipped)":""}`,...d.previewUrl?[link("Preview",d.previewUrl)]:[],...d.updated?[d.updated]:[]].join(" \xB7 ")}`).join(`
|
|
10
|
-
`)}function displayText(text,actor){let deployments=actor==="github:user:35613825"?vercelDeployments(text):null;return deployments?`**\u25B2 Vercel**
|
|
11
|
-
${formatVercelDeployments(deployments)}`:text}export{ExternalTarget,Origin,Link,ExternalAuthor,ExternalLocation,ExternalEvent,isThreadTarget,channelOf,externalMessageKey,sha256,derivedId,DERIVED_ID,keyId,waitUntil,extractMentions,replaceMentions,DroppedError,runMiddleware,displayText};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{ZodError,external_exports}from"./chunk-2AMO2VMV.js";function fileSize(bytes){return bytes<1024?`${bytes} B`:bytes<1048576?`${Math.round(bytes/1024)} KB`:`${(bytes/1024/1024).toFixed(1)} MB`}var TYPES={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".pdf":"application/pdf",".txt":"text/plain",".log":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".html":"text/html",".zip":"application/zip"};function typeOf(name){let dot=name.lastIndexOf(".");return dot>0&&TYPES[name.slice(dot).toLowerCase()]||"application/octet-stream"}var MESSAGE_TEXT_MAX=1e4,SCOPE_MAX=4e3;var segment="[a-z0-9][a-z0-9_-]*",ChannelPath=external_exports.string().max(80).regex(new RegExp(`^${segment}(?:/${segment})*$`),"invalid channel path"),storable=value=>!value.includes("\0")&&value.isWellFormed(),toStorable=value=>value.replaceAll("\0","").toWellFormed(),MessageText=external_exports.string().max(MESSAGE_TEXT_MAX).refine(text=>text.trim().length>0,"message text is empty").refine(storable,"message text has a NUL character or a lone surrogate"),MessageId=external_exports.number().int().positive(),INHERITED=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),notInherited=name=>!INHERITED.has(name),LabelKey=external_exports.string().max(64).regex(/^[a-z0-9][a-z0-9_.-]*$/,"invalid label key").refine(notInherited,"label key is a reserved name"),LabelValue=external_exports.string().max(256).refine(storable,"label value has a NUL character or a lone surrogate"),Labels=external_exports.record(LabelKey,LabelValue),Emoji=external_exports.string().max(64).regex(/^[a-z0-9_+-]+$/,"invalid emoji name").refine(notInherited,"emoji name is a reserved name"),ActorId=external_exports.string().min(1).max(256),ActorKind=external_exports.enum(["person","agent","deployment","workflow","external"]),SeenActorKind=external_exports.union([ActorKind,external_exports.literal("profile")]);var Handle=external_exports.string().min(1).max(128).refine(storable,"handle has a NUL character or a lone surrogate");function platformAvatar(avatar){if(avatar===null)return null;try{return new URL(avatar).protocol==="https:"?avatar:null}catch{return null}}var Author=external_exports.object({actor:ActorId,principal:external_exports.string().min(1),profile:external_exports.string().nullable(),session:external_exports.string().nullable()}),AttachmentId=external_exports.string().regex(/^(?:[A-Za-z0-9_-]{22}|att_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,"invalid attachment id"),Attachment=external_exports.object({id:AttachmentId,name:external_exports.string().min(1).max(255),type:external_exports.string().min(1).max(255),size:external_exports.number().int().nonnegative()}),RemoteWatcherId=external_exports.string().regex(/^[A-Za-z][A-Za-z0-9-]{0,31}$/,"ids start with a letter and use up to 32 letters, numbers, and hyphens");var EMOJI_TABLE={100:{characters:["\u{1F4AF}"],aliases:[]},thumbs_up:{characters:["\u{1F44D}"],aliases:["+1","thumbsup"]},thumbs_down:{characters:["\u{1F44E}"],aliases:["-1","thumbsdown"]},clap:{characters:["\u{1F44F}"],aliases:[]},wave:{characters:["\u{1F44B}"],aliases:[]},pray:{characters:["\u{1F64F}"],aliases:[]},muscle:{characters:["\u{1F4AA}"],aliases:[]},ok_hand:{characters:["\u{1F44C}"],aliases:[]},point_up:{characters:["\u{1F446}"],aliases:[]},point_down:{characters:["\u{1F447}"],aliases:[]},point_left:{characters:["\u{1F448}"],aliases:[]},point_right:{characters:["\u{1F449}"],aliases:[]},raised_hands:{characters:["\u{1F64C}"],aliases:[]},shrug:{characters:["\u{1F937}"],aliases:[]},facepalm:{characters:["\u{1F926}"],aliases:[]},heart:{characters:["\u2764\uFE0F","\u2764"],aliases:[]},smile:{characters:["\u{1F60A}"],aliases:["slightly_smiling_face"]},laugh:{characters:["\u{1F602}","\u{1F606}"],aliases:["laughing","satisfied","joy"]},thinking:{characters:["\u{1F914}"],aliases:["thinking_face"]},sad:{characters:["\u{1F622}"],aliases:["cry","white_frowning_face"]},cry:{characters:["\u{1F62D}"],aliases:["sob"]},angry:{characters:["\u{1F620}"],aliases:[]},love_eyes:{characters:["\u{1F60D}"],aliases:["heart_eyes"]},cool:{characters:["\u{1F60E}"],aliases:["sunglasses"]},wink:{characters:["\u{1F609}"],aliases:[]},surprised:{characters:["\u{1F62E}"],aliases:["open_mouth"]},worried:{characters:["\u{1F61F}"],aliases:[]},confused:{characters:["\u{1F615}"],aliases:[]},neutral:{characters:["\u{1F610}"],aliases:["neutral_face"]},sleeping:{characters:["\u{1F634}"],aliases:[]},sick:{characters:["\u{1F922}"],aliases:["nauseated_face"]},mind_blown:{characters:["\u{1F92F}"],aliases:["exploding_head"]},relieved:{characters:["\u{1F60C}"],aliases:[]},grimace:{characters:["\u{1F62C}"],aliases:["grimacing"]},rolling_eyes:{characters:["\u{1F644}"],aliases:[]},hug:{characters:["\u{1F917}"],aliases:["hugging_face"]},zany:{characters:["\u{1F92A}"],aliases:["zany_face"]},check:{characters:["\u2705","\u2714\uFE0F"],aliases:["white_check_mark","heavy_check_mark"]},x:{characters:["\u274C","\u2716\uFE0F"],aliases:["heavy_multiplication_x"]},question:{characters:["\u2753","?"],aliases:[]},exclamation:{characters:["\u2757"],aliases:[]},warning:{characters:["\u26A0\uFE0F"],aliases:[]},stop:{characters:["\u{1F6D1}"],aliases:["octagonal_sign"]},info:{characters:["\u2139\uFE0F"],aliases:["information_source"]},fire:{characters:["\u{1F525}"],aliases:[]},star:{characters:["\u2B50"],aliases:[]},sparkles:{characters:["\u2728"],aliases:[]},lightning:{characters:["\u26A1"],aliases:["zap"]},boom:{characters:["\u{1F4A5}"],aliases:[]},eyes:{characters:["\u{1F440}"],aliases:[]},green_circle:{characters:["\u{1F7E2}"],aliases:["large_green_circle"]},yellow_circle:{characters:["\u{1F7E1}"],aliases:["large_yellow_circle"]},red_circle:{characters:["\u{1F534}"],aliases:[]},blue_circle:{characters:["\u{1F535}"],aliases:["large_blue_circle"]},white_circle:{characters:["\u26AA"],aliases:[]},black_circle:{characters:["\u26AB"],aliases:[]},rocket:{characters:["\u{1F680}"],aliases:[]},party:{characters:["\u{1F389}","\u{1F973}"],aliases:["tada","partying_face"]},confetti:{characters:["\u{1F38A}"],aliases:["confetti_ball"]},balloon:{characters:["\u{1F388}"],aliases:[]},gift:{characters:["\u{1F381}"],aliases:[]},trophy:{characters:["\u{1F3C6}"],aliases:[]},medal:{characters:["\u{1F947}"],aliases:["first_place_medal"]},lightbulb:{characters:["\u{1F4A1}"],aliases:["bulb"]},gear:{characters:["\u2699\uFE0F"],aliases:[]},wrench:{characters:["\u{1F527}"],aliases:[]},hammer:{characters:["\u{1F528}"],aliases:[]},bug:{characters:["\u{1F41B}"],aliases:[]},link:{characters:["\u{1F517}"],aliases:[]},lock:{characters:["\u{1F512}"],aliases:[]},unlock:{characters:["\u{1F513}"],aliases:[]},key:{characters:["\u{1F511}"],aliases:[]},pin:{characters:["\u{1F4CC}"],aliases:["pushpin"]},memo:{characters:["\u{1F4DD}"],aliases:[]},clipboard:{characters:["\u{1F4CB}"],aliases:[]},calendar:{characters:["\u{1F4C5}"],aliases:[]},clock:{characters:["\u{1F550}"],aliases:["clock1"]},hourglass:{characters:["\u23F3"],aliases:[]},bell:{characters:["\u{1F514}"],aliases:[]},megaphone:{characters:["\u{1F4E2}"],aliases:["mega"]},speech_bubble:{characters:["\u{1F4AC}"],aliases:["speech_balloon"]},email:{characters:["\u{1F4E7}"],aliases:[]},inbox:{characters:["\u{1F4E5}"],aliases:["inbox_tray"]},outbox:{characters:["\u{1F4E4}"],aliases:["outbox_tray"]},package:{characters:["\u{1F4E6}"],aliases:[]},folder:{characters:["\u{1F4C1}"],aliases:["file_folder"]},file:{characters:["\u{1F4C4}"],aliases:["page_facing_up"]},chart_up:{characters:["\u{1F4C8}"],aliases:["chart_with_upwards_trend"]},chart_down:{characters:["\u{1F4C9}"],aliases:["chart_with_downwards_trend"]},coffee:{characters:["\u2615"],aliases:[]},pizza:{characters:["\u{1F355}"],aliases:[]},beer:{characters:["\u{1F37A}"],aliases:[]},arrow_up:{characters:["\u2B06\uFE0F"],aliases:[]},arrow_down:{characters:["\u2B07\uFE0F"],aliases:[]},arrow_left:{characters:["\u2B05\uFE0F"],aliases:[]},arrow_right:{characters:["\u27A1\uFE0F"],aliases:[]},refresh:{characters:["\u{1F504}"],aliases:["arrows_counterclockwise"]},sun:{characters:["\u2600\uFE0F"],aliases:["sunny"]},cloud:{characters:["\u2601\uFE0F"],aliases:[]},rain:{characters:["\u{1F327}\uFE0F"],aliases:["rain_cloud"]},snow:{characters:["\u2744\uFE0F"],aliases:["snowflake"]},rainbow:{characters:["\u{1F308}"],aliases:[]}},CANONICAL=new Map,SHOWN=new Map,BY_CHARACTER=new Map,bare=character=>character.replace(/️/g,"");function add(name,characters,aliases){CANONICAL.set(name,name);for(let alias of aliases)CANONICAL.has(alias)||CANONICAL.set(alias,name);characters[0]&&SHOWN.set(name,characters[0]);for(let character of characters)BY_CHARACTER.has(bare(character))||BY_CHARACTER.set(bare(character),name)}for(let[name,entry]of Object.entries(EMOJI_TABLE))add(name,entry.characters,entry.aliases);add("rotating_light",["\u{1F6A8}"],[]);add("ship",["\u{1F6A2}"],[]);var canonicalEmoji=name=>CANONICAL.get(name)??name;function normalizeEmoji(input){let trimmed=input.trim(),named=trimmed.match(/^:?([a-z0-9_+-]+):?$/i);if(named)return canonicalEmoji(named[1].toLowerCase());let name=BY_CHARACTER.get(bare(trimmed));if(name)return name;throw new Error(`unknown emoji: ${input} (use a short name like eyes or thumbs_up)`)}var displayEmoji=name=>SHOWN.get(canonicalEmoji(name))??`:${name}:`;async function*parseSse(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>void reader.cancel().catch(()=>{});signal?.addEventListener("abort",onAbort,{once:!0});try{for(;;){let{value,done}=await reader.read();if(done)return;buffer+=decoder.decode(value,{stream:!0});let boundary;for(;(boundary=buffer.search(/\r?\n\r?\n/))!==-1;){let block=buffer.slice(0,boundary);buffer=buffer.slice(boundary).replace(/^\r?\n\r?\n/,"");let message={},data=[];for(let line of block.split(/\r?\n/)){if(line===""||line.startsWith(":"))continue;let colon=line.indexOf(":"),field=colon===-1?line:line.slice(0,colon),value2=colon===-1?"":line.slice(colon+1).replace(/^ /,"");field==="data"?data.push(value2):field==="id"?message.id=value2:field==="event"&&(message.event=value2)}data.length>0&&(message.data=data.join(`
|
|
8
|
-
`)),(message.id!==void 0||message.data!==void 0)&&(yield message)}}}finally{signal?.removeEventListener("abort",onAbort),reader.releaseLock()}}var BoardError=class extends Error{code;status;hint;origin;constructor(code,message,status,options={}){super(message),this.name="BoardError",this.code=code,this.status=status,this.hint=options.hint,this.origin=options.origin??"handle"}},handleErrors=new WeakSet,resolve=async value=>typeof value=="function"?await value():value,scheduleBody=input=>{let{at,until,...rest}=messageBody(input);return{...rest,...at!==void 0?{at:at instanceof Date?at.toISOString():at}:{},...until!==void 0?{until:until instanceof Date?until.toISOString():until}:{}}},messageBody=input=>{if(typeof input=="string")return{text:input};let{attachments,...rest}=input;return attachments?.length?{...rest,attachments:attachments.map(a=>typeof a=="string"?a:a.id)}:rest},UNITS={ms:1,s:1e3,m:6e4,h:36e5,d:864e5};function duration(value){if(typeof value=="number")return value;let match=value.trim().match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)?$/);if(!match)throw new BoardError("invalid_duration",`${value} isn't a duration like 30s, 10m, or 1h.`,0);return Number(match[1])*UNITS[match[2]??"ms"]}var path=id=>encodeURIComponent(id);function queryString(query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))if(value!=null)if(key==="label"){let labels=Array.isArray(value)?value:typeof value=="object"?Object.entries(value).map(([k,v])=>`${k}=${String(v)}`):[value];for(let label of labels)params.append("label",String(label))}else params.set(key,String(value));let text=params.toString();return text?`?${text}`:""}var written=(value,unknownMentions)=>unknownMentions?.length?{...value,unknownMentions}:value;function createBoardClient(options){let base=options.url.replace(/\/+$/,""),doFetch=options.fetch??((input,init)=>globalThis.fetch(input,init)),storeFetch=options.storeFetch??((input,init)=>globalThis.fetch(input,init));async function headers(auth,as){let out={...options.headers?await resolve(options.headers):{}};if(!auth)return out;options.token!==void 0&&(out.authorization=`Bearer ${await resolve(options.token)}`);let profile=as!==void 0?as:options.profile===void 0?null:await resolve(options.profile);if(profile!==null){let{name,avatar}=typeof profile=="string"?{name:profile,avatar:void 0}:profile;out["x-board-profile"]=name,avatar&&(out["x-board-avatar"]=avatar)}else{let person=options.person===void 0?null:await resolve(options.person);person?.name&&(out["x-board-name"]=encodeURIComponent(person.name)),person?.avatar&&(out["x-board-avatar"]=person.avatar)}let session=as!==void 0||options.session===void 0?null:await resolve(options.session);session&&(out["x-board-session"]=session);let handle=options.handle===void 0?null:await resolve(options.handle);return handle&&(out["x-board-handle"]=handle),out}async function raw(method,path2,init={}){let response=await doFetch(`${base}${path2}`,{method,headers:{...await headers(init.auth??!0),...init.body===void 0?{}:{"content-type":"application/json"},...init.headers},...init.body===void 0?{}:{body:JSON.stringify(init.body)},...init.signal?{signal:init.signal}:{}});if(!response.ok)throw await toError(response);return response}async function call(method,path2,init){return await(await raw(method,path2,init)).json()}let filtersQuery=(filters={})=>filters;async function poll(query={},signal){return call("GET",`/events${queryString(query)}`,signal?{signal}:{})}return{url:base,request:async(path2,init={})=>doFetch(`${base}${path2}`,{method:init.method??"GET",headers:{...init.headers,...await headers(!0,init.as)},...init.body?{body:init.body}:{},...init.signal?{signal:init.signal}:{}}),discovery:()=>call("GET","/",{auth:!1}),me:()=>call("GET","/me"),channels:async()=>(await call("GET","/channels")).channels,actors:async()=>(await call("GET","/actors")).actors,identity:()=>call("GET","/identity"),unlinkAccount:account=>call("POST","/identity/unlink",{body:{actor:account}}),messages:(query={})=>call("GET",`/messages${queryString(query)}`),thread:id=>call("GET",`/messages/${path(id)}`),posted:async id=>(await call("GET",`/posts/${path(id)}`)).message,threads:(query={})=>call("GET",`/threads${queryString(query)}`),async post(channel,input){let{message,unknownMentions}=await call("POST","/messages",{body:{channel,...messageBody(input)}});return written(message,unknownMentions)},async reply(id,input){let{message,unknownMentions}=await call("POST","/messages",{body:{re:id,...messageBody(input)}});return written(message,unknownMentions)},async schedule(target,input){let{schedule,unknownMentions}=await call("POST","/schedules",{body:{...typeof target=="string"?{channel:target}:{re:target.re},...scheduleBody(input)}});return written(schedule,unknownMentions)},schedules:async(query={})=>(await call("GET",`/schedules${queryString(query)}`)).schedules,cancelSchedule:id=>call("POST",`/schedules/${path(id)}/cancel`,{body:{}}),async upload(input){let type=input.type||(input.data instanceof Blob?input.data.type:"")||typeOf(input.name),size=input.data instanceof Blob?input.data.size:input.data.byteLength;if(size>4194304){if(size>104857600)throw new BoardError("too_large",`Attachments are at most ${104857600/1024/1024} MB.`,413);let bytes=input.data instanceof Blob?await input.data.arrayBuffer():input.data,sha256=btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest("SHA-256",bytes)))),ticket=await call("POST","/attachments/uploads",{body:{name:input.name,type,size,sha256}}).catch(error=>{throw error instanceof BoardError&&error.status===404&&error.code==="not_found"?new BoardError("too_large",`This board takes files of at most ${4194304/1024/1024} MB.`,413):error}),put=await storeFetch(ticket.url,{method:"PUT",headers:ticket.headers,body:input.data});if(!put.ok)throw new BoardError("upload_failed",`The blob store refused the file: ${put.status} ${(await put.text().catch(()=>"")).slice(0,300)||put.statusText}`,put.status);return(await call("POST",`/attachments/uploads/${encodeURIComponent(ticket.id)}`,{body:{}})).attachment}let response=await doFetch(`${base}/attachments`,{method:"POST",headers:{...await headers(!0),"content-type":type,"x-board-filename":encodeURIComponent(input.name)},body:input.data});if(!response.ok)throw await toError(response);return(await response.json()).attachment},download:(id,opts={})=>raw("GET",`/attachments/${encodeURIComponent(id)}`,opts.signal?{signal:opts.signal}:{}),edit:(id,text,opts={})=>call("POST",`/messages/${path(id)}/edit`,{body:{text,...opts}}),delete:(id,opts={})=>call("POST",`/messages/${path(id)}/delete`,{body:{...opts}}),react:(id,emoji,opts={})=>call("POST",`/messages/${path(id)}/reactions`,{body:{emoji:normalizeEmoji(emoji),...opts}}),label:(id,change)=>call("POST",`/messages/${path(id)}/labels`,{body:change}),typing:async(id,status)=>(await call("POST",`/messages/${path(id)}/typing`,{body:status?{status}:{}})).targets,sync:(id,target)=>target===void 0?call("GET",`/messages/${path(id)}/sync`):call("POST",`/messages/${path(id)}/sync`,{body:{target}}),linked:url=>call("GET",`/links${queryString({url})}`),inbox:async(key,opts={})=>(await call("GET",`/inbox/${key}${queryString(opts)}`)).events,register:input=>call("POST","/watchers",{body:input}),watchers:async()=>(await call("GET","/watchers")).watchers,matches:async(opts={})=>{let{signal,...query}=opts;return(await call("GET",`/watchers/matches${queryString(query)}`,signal?{signal}:{})).matches},ack:(id,body)=>call("POST",`/watchers/matches/${encodeURIComponent(id)}/ack`,{body}),readSource:(key,target,opts={})=>call("GET",`/sources/${key}/read${queryString({target,...opts})}`),joinSource:(key,target)=>call("POST",`/sources/${key}/join`,{body:{target}}),poll,syncImport:body=>call("POST","/sync/imports",{body}),syncReceipt:body=>call("POST","/sync/receipts",{body}),syncThread:thread=>call("GET",`/sync/threads/${path(thread)}`),syncFind:(query,opts={})=>call("GET",`/sync/find${queryString(query)}`,opts.signal?{signal:opts.signal}:{}),syncCopies:async messages=>(await call("GET",`/sync/copies?${messages.map(id=>`message=${encodeURIComponent(id)}`).join("&")}`)).copies,syncRoots:async(by,since)=>(await call("GET",`/sync/roots${queryString({by,since:since instanceof Date?since.getTime():since})}`)).roots,inboxPush:(key,events)=>call("POST",`/inbox/${path(key)}`,{body:{events}}),inboxNext:async(key,opts={})=>(await call("GET",`/inbox/${path(key)}/next${queryString(opts)}`)).items,inboxAck:(key,id,body)=>call("POST",`/inbox/${path(key)}/${path(id)}/ack`,{body}),syncCode:sync=>call("POST","/sync/codes",{body:{sync}}),syncAccount:body=>call("POST","/sync/accounts",{body}),syncUnlink:account=>call("POST","/sync/accounts/unlink",{body:{account}}),async*events(query={},opts={}){let after=query.after,failures=0;for(;!opts.signal?.aborted;){let response;try{response=await raw("GET",`/events${queryString({...filtersQuery(query),after})}`,{headers:{accept:"text/event-stream"},...opts.signal?{signal:opts.signal}:{}})}catch(error){if(opts.signal?.aborted)return;if(error instanceof BoardError&&error.status>=400&&error.status<500)throw error;await new Promise(r=>setTimeout(r,Math.min(3e4,500*2**failures++)));continue}failures=0;try{for await(let message of parseSse(response.body,opts.signal))message.id!==void 0&&(after=message.id),message.event==="board"&&message.data&&(yield JSON.parse(message.data))}catch{if(opts.signal?.aborted)return;await new Promise(r=>setTimeout(r,Math.min(3e4,500*2**failures++)))}}},async wait(query={},opts={}){let deadline=Date.now()+duration(opts.timeout??"30m"),after=query.after??(await poll({...query,after:void 0,wait:0},opts.signal)).cursor;for(;Date.now()<deadline&&!opts.signal?.aborted;){let wait=Math.max(0,Math.min(25,Math.ceil((deadline-Date.now())/1e3))),page=await poll({...query,after,wait},opts.signal);if(page.events.length>0)return page.events[0];after=page.cursor}return null}}}async function toError(response){try{let body=await response.json();if(body.error?.message)return new BoardError(body.error.code??"error",body.error.message,response.status,{...typeof body.error.hint=="string"?{hint:body.error.hint}:{},origin:handleErrors.has(response)?"handle":"board"})}catch{}return new BoardError("http_error",`The board answered ${`${response.status} ${response.statusText}`.trim()}.`,response.status)}var HttpError=class extends Error{status;code;hint;origin;constructor(status,code,message,options={}){super(message),this.status=status,this.code=code,this.hint=options.hint,this.origin=options.origin??"board"}},RejectedError=class extends HttpError{response;constructor(response){super(response.status,"rejected",`rejected with ${response.status}`),this.response=response}},badRequest=(message,code="invalid_request")=>new HttpError(400,code,message),unauthorized=message=>new HttpError(401,"unauthorized",message),forbidden=message=>new HttpError(403,"forbidden",message),notFound=(message,code="not_found")=>new HttpError(404,code,message),duplicateId=()=>new HttpError(409,"duplicate_id","that id was already used for a different write"),json=(body,status=200,headers)=>new Response(JSON.stringify(body),{status,headers:{"content-type":"application/json",...headers}});function reported(issue){if(issue.code!=="invalid_union"||issue.errors.length===0)return issue;let first=issue.errors.reduce((best,option)=>option.length<best.length?option:best)[0];return first?reported({...first,path:[...issue.path,...first.path]}):issue}function toErrorResponse(error){if(error instanceof RejectedError)return error.response;if(error instanceof HttpError){let response=json({error:{code:error.code,message:error.message,...error.hint!==void 0?{hint:error.hint}:{}}},error.status);return error.origin==="handle"&&handleErrors.add(response),response}if(error instanceof ZodError){let issue=error.issues[0]&&reported(error.issues[0]),path2=issue?.path.length?`${issue.path.join(".")}: `:"";return json({error:{code:"invalid_request",message:`${path2}${issue?.message??"invalid request"}`}},400)}let code=error?.code;return code==="INVALID_PAYLOAD"?json({error:{code:"invalid_request",message:error.message}},400):code==="PARTIAL_DUPLICATE_BATCH"||code==="DUPLICATE_EVENT_ID"?toErrorResponse(duplicateId()):code==="STORE_UNAVAILABLE"||code==="STORE_NOT_CONFIGURED"?json({error:{code:"unavailable",message:error.message}},503):(console.error("[board]",error),json({error:{code:"internal",message:"internal error"}},500))}export{fileSize,typeOf,MESSAGE_TEXT_MAX,SCOPE_MAX,ChannelPath,storable,toStorable,MessageText,MessageId,LabelKey,LabelValue,Labels,Emoji,ActorId,platformAvatar,AttachmentId,RemoteWatcherId,canonicalEmoji,normalizeEmoji,displayEmoji,BoardError,duration,createBoardClient,HttpError,RejectedError,badRequest,unauthorized,forbidden,notFound,json,toErrorResponse};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{ChannelPath,SCOPE_MAX,forbidden,unauthorized}from"./chunk-MRCM5VF5.js";var JOSEError=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(message2,options){super(message2,options),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},JWTClaimValidationFailed=class extends JOSEError{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(message2,payload,claim="unspecified",reason="unspecified"){super(message2,{cause:{claim,reason,payload}}),this.claim=claim,this.reason=reason,this.payload=payload}},JWTExpired=class extends JOSEError{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(message2,payload,claim="unspecified",reason="unspecified"){super(message2,{cause:{claim,reason,payload}}),this.claim=claim,this.reason=reason,this.payload=payload}},JOSEAlgNotAllowed=class extends JOSEError{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},JOSENotSupported=class extends JOSEError{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var JWSInvalid=class extends JOSEError{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},JWTInvalid=class extends JOSEError{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var JWKSInvalid=class extends JOSEError{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},JWKSNoMatchingKey=class extends JOSEError{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(message2="no applicable key found in the JSON Web Key Set",options){super(message2,options)}},JWKSMultipleMatchingKeys=class extends JOSEError{[Symbol.asyncIterator]=async function*(){};static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(message2="multiple matching keys found in the JSON Web Key Set",options){super(message2,options)}},JWKSTimeout=class extends JOSEError{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(message2="request timed out",options){super(message2,options)}},JWSSignatureVerificationFailed=class extends JOSEError{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(message2="signature verification failed",options){super(message2,options)}};function table(entries){let out={__proto__:null};for(let alg in entries)out[alg]={...entries[alg],alg};return out}var sig=[["verify"],["sign"]];function hmac(bits){let subtle={name:"HMAC",hash:`SHA-${bits}`};return{kty:["oct"],secret:!0,subtle,signing:subtle,usages:sig}}function rsa(bits,saltLength){let subtle={name:saltLength?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${bits}`};return{kty:["RSA"],subtle,signing:saltLength?{...subtle,saltLength}:subtle,usages:sig,minRsaBits:2048}}function ecdsa(crv,bits){return{kty:["EC"],crv,subtle:{name:"ECDSA",namedCurve:crv},signing:{name:"ECDSA",hash:`SHA-${bits}`},usages:sig}}function eddsa(){let subtle={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle,signing:subtle,usages:sig}}function mldsa(parameterSet){let subtle={name:`ML-DSA-${parameterSet}`};return{kty:["AKP"],subtle,signing:subtle,usages:sig}}var JWS=table({HS256:hmac(256),HS384:hmac(384),HS512:hmac(512),RS256:rsa(256),RS384:rsa(384),RS512:rsa(512),PS256:rsa(256,32),PS384:rsa(384,48),PS512:rsa(512,64),ES256:ecdsa("P-256",256),ES384:ecdsa("P-384",384),ES512:ecdsa("P-521",512),EdDSA:eddsa(),Ed25519:eddsa(),"ML-DSA-44":mldsa(44),"ML-DSA-65":mldsa(65),"ML-DSA-87":mldsa(87)});function jwsAlgorithm(alg){let entry=typeof alg=="string"?JWS[alg]:void 0;if(!entry)throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);return entry}var encoder=new TextEncoder,decoder=new TextDecoder,strictDecoder=new TextDecoder("utf-8",{fatal:!0}),UINT32_RANGE=2**32;function concat(...buffers){let size=buffers.reduce((acc,{length})=>acc+length,0),buf=new Uint8Array(size),i=0;for(let buffer of buffers)buf.set(buffer,i),i+=buffer.length;return buf}var NON_ASCII=/[^\x00-\x7f]/;function encode(string){if(typeof string=="string"&&string.length>=128){if(NON_ASCII.test(string))throw new TypeError("non-ASCII string encountered in encode()");return encoder.encode(string)}let bytes=new Uint8Array(string.length);for(let i=0;i<string.length;i++){let code=string.charCodeAt(i);if(code>127)throw new TypeError("non-ASCII string encountered in encode()");bytes[i]=code}return bytes}function decodeBase64(encoded,url=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(encoded,{alphabet:url?"base64url":"base64"});if(url){if(encoded.includes("+")||encoded.includes("/"))throw new TypeError("Invalid base64url");encoded=encoded.replace(/-/g,"+").replace(/_/g,"/")}let binary=atob(encoded),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);return bytes}var invalid="The input to be decoded is not correctly encoded.";function decode(input){try{return decodeBase64(typeof input=="string"?input:decoder.decode(input),!0)}catch(cause){throw new TypeError(invalid,{cause})}}function isObject(input){if(typeof input!="object"||input===null||Object.prototype.toString.call(input)!=="[object Object]")return!1;let prototype=Object.getPrototypeOf(input);return prototype===null||Object.getPrototypeOf(prototype)===null}function isJwkSet(input){return isObject(input)&&Array.isArray(input.keys)&&Array.from(input.keys).every(isObject)}function isDisjoint(...headers){let parameters=new Set;for(let header of headers)if(header)for(let parameter of Object.keys(header)){if(parameters.has(parameter))return!1;parameters.add(parameter)}return!0}function decodeBase64url(value,label,ErrorClass){try{return decode(value)}catch(cause){throw new ErrorClass(`Failed to base64url decode the ${label}`,{cause})}}function encodeAsciiMember(value,label,ErrorClass){try{return encode(value)}catch(cause){throw new ErrorClass(`The ${label} is not a valid base64url string`,{cause})}}function parseJoseHeader(encodedProtectedHeader,ErrorClass,message2){let parsed;try{parsed=JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)))}catch(cause){throw new ErrorClass(message2,{cause})}if(!isObject(parsed))throw new ErrorClass(message2);return parsed}var JWS_RECOGNIZED={__proto__:null,b64:!0};function validateAlgorithms(option,algorithms){if(algorithms!==void 0&&(!Array.isArray(algorithms)||algorithms.some(s=>typeof s!="string")))throw new TypeError(`"${option}" option must be an array of strings`);return algorithms===void 0?void 0:new Set(algorithms)}function validateCrit(Err,recognizedDefault,recognizedOption,protectedHeader,joseHeader){if(joseHeader.crit!==void 0&&protectedHeader?.crit===void 0)throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');if(!protectedHeader||protectedHeader.crit===void 0)return[];if(!Array.isArray(protectedHeader.crit)||protectedHeader.crit.length===0||protectedHeader.crit.some(input=>typeof input!="string"||input.length===0))throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let recognized=recognizedOption===void 0?recognizedDefault:{__proto__:null,...recognizedOption,...recognizedDefault};for(let parameter of protectedHeader.crit){if(!(parameter in recognized))throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);if(!Object.hasOwn(joseHeader,parameter)||joseHeader[parameter]===void 0)throw new Err(`Extension Header Parameter "${parameter}" is missing`);if(recognized[parameter]&&(!Object.hasOwn(protectedHeader,parameter)||protectedHeader[parameter]===void 0))throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`)}return protectedHeader.crit}function validateB64(protectedHeader,extensions){if(extensions.includes("b64")){let b64=protectedHeader.b64;if(typeof b64!="boolean")throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return b64}return!0}var tag=key2=>key2[Symbol.toStringTag],jwkMatchesOp=(entry,key2,usage)=>{let{alg}=entry;if(key2.use!==void 0){let expected=usage==="sign"||usage==="verify"?"sig":"enc";if(key2.use!==expected)throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`)}if(key2.alg!==void 0&&key2.alg!==alg)throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);if(Array.isArray(key2.key_ops)){let expectedKeyOp=usage==="encrypt"||usage==="decrypt"?entry.ops?.[usage==="encrypt"?0:1]:usage;if(expectedKeyOp&&!key2.key_ops.includes(expectedKeyOp))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`)}};async function prepareKey(entry,key2,usage){let{alg,secret}=entry,requiresPrivateKey=usage==="decrypt"||usage==="sign";if(secret&&key2 instanceof Uint8Array)return key2;let normalized,keyObject;if(isObject(key2)){if(normalized=normalizeJwk(key2),typeof normalized.kty!="string")throw invalidKeyType(alg,key2,secret);if(!(secret?normalized.kty==="oct"&&typeof normalized.k=="string":normalized.kty!=="oct"&&(requiresPrivateKey?normalized.kty==="AKP"&&typeof normalized.priv=="string"||typeof normalized.d=="string":normalized.d===void 0&&normalized.priv===void 0)))throw new TypeError(secret?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${requiresPrivateKey?"private":"public"} JWK`);if(jwkMatchesOp(entry,normalized,usage),normalized.kty==="oct")return decode(normalized.k);if(!Object.isFrozen(key2)){let{key_ops}=key2;Array.isArray(key_ops)&&Object.freeze(key_ops),Object.freeze(key2)}}else{if(!isKeyLike(key2))throw invalidKeyType(alg,key2,secret);let expectedType=secret?"secret":requiresPrivateKey?"private":"public";if(key2.type!==expectedType&&(secret||["secret","public","private"].includes(key2.type)))throw new TypeError(`${tag(key2)} instances must be of type "${expectedType}" for the ${alg} algorithm`);if(isCryptoKey(key2))return key2;if(keyObject=key2,keyObject.type==="secret")return keyObject.export()}cache||=new WeakMap;let cacheKey=key2,cached=cache.get(cacheKey);if(cached?.[alg])return cached[alg];if(cached||cache.set(cacheKey,cached={}),keyObject&&typeof keyObject.toCryptoKey=="function"){let isPublic=keyObject.type==="public",crv=nist[keyObject.asymmetricKeyDetails?.namedCurve],params=entry.resolve?.({crv,asymmetricKeyType:keyObject.asymmetricKeyType})??entry.subtle;return cached[alg]=keyObject.toCryptoKey(params,isPublic,entry.usages[isPublic?0:1])}return normalized??=keyObject.export({format:"jwk"}),normalized.alg=alg,cached[alg]=await jwkToKey(entry,normalized)}var cache,nist={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};var isCryptoKey=key2=>{if(key2?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return key2 instanceof CryptoKey}catch{return!1}},isKeyObject=key2=>key2?.[Symbol.toStringTag]==="KeyObject",isKeyLike=key2=>isCryptoKey(key2)||isKeyObject(key2);function message(msg,actual,...types){if(types.length>2){let last=types.pop();msg+=`one of type ${types.join(", ")}, or ${last}.`}else types.length===2?msg+=`one of type ${types[0]} or ${types[1]}.`:msg+=`of type ${types[0]}.`;return actual==null?msg+=` Received ${actual}`:typeof actual=="function"&&actual.name?msg+=` Received function ${actual.name}`:typeof actual=="object"&&actual!=null&&actual.constructor?.name&&(msg+=` Received an instance of ${actual.constructor.name}`),msg}function invalidKeyType(alg,actual,secret){let types=["CryptoKey","KeyObject","JSON Web Key"];return secret&&types.push("Uint8Array"),new TypeError(message(`Key for the ${alg} algorithm must be `,actual,...types))}var unusable=(name,prop="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);function checkUsage(key2,usage){if(usage&&!key2.usages.includes(usage))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`)}function checkModulusLength(alg,key2){let{modulusLength}=key2.algorithm;if(typeof modulusLength!="number"||modulusLength<2048)throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`)}function checkCryptoKey(key2,expected,usage){let algorithm=key2.algorithm;if(algorithm.name!==expected.name)throw unusable(expected.name);if(expected.hash&&algorithm.hash?.name!==expected.hash)throw unusable(expected.hash,"algorithm.hash");if(expected.namedCurve&&algorithm.namedCurve!==expected.namedCurve)throw unusable(expected.namedCurve,"algorithm.namedCurve");if(expected.length!==void 0&&algorithm.length!==expected.length)throw unusable(expected.length,"algorithm.length");checkUsage(key2,usage)}function snapshotJwk(jwk){return{__proto__:null,...jwk}}function normalizeJwk(jwk){let normalized=snapshotJwk(jwk);if(normalized.ext!==void 0&&typeof normalized.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(normalized.key_ops!==void 0){let value=normalized.key_ops,keyOps=Array.isArray(value)?[...value]:void 0;if(!keyOps||keyOps.some(operation=>typeof operation!="string")||new Set(keyOps).size!==keyOps.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');normalized.key_ops=keyOps}return normalized}async function jwkToKey(entry,jwk,extractable){if(!entry.kty.includes(jwk.kty))throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let algorithm=entry.resolve?.({kty:jwk.kty,crv:jwk.crv})??entry.subtle,isPrivate=!!(jwk.d||jwk.priv),keyData={...jwk,ext:extractable??jwk.ext};return keyData.kty!=="AKP"&&delete keyData.alg,delete keyData.use,crypto.subtle.importKey("jwk",keyData,algorithm,keyData.ext??!isPrivate,jwk.key_ops??entry.usages[isPrivate?1:0])}async function rawKey(key2,expected,usage,extractable=!1){return key2 instanceof Uint8Array&&(key2=await crypto.subtle.importKey("raw",key2,expected,extractable,[usage])),checkCryptoKey(key2,expected,usage),key2}function prepareVerify(options){return[options&&validateAlgorithms("algorithms",options.algorithms),options?.crit]}function parseProtectedHeader(encodedProtectedHeader){return encodedProtectedHeader===void 0?{}:parseJoseHeader(encodedProtectedHeader,JWSInvalid,"JWS Protected Header is invalid")}function encodeCompactUnencodedPayload(payload){try{return encode(payload)}catch(cause){throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters",{cause})}}async function verifySignature(jws,shared,key2,encodeUnencodedPayload,parsedProtected){let{protected:encodedProtectedHeader,header,payload:inputPayload}=jws,protectedHeader=parsedProtected??parseProtectedHeader(encodedProtectedHeader);if(!isDisjoint(protectedHeader,header))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let joseHeader={...protectedHeader,...header},b64=validateB64(protectedHeader,validateCrit(JWSInvalid,JWS_RECOGNIZED,shared[1],protectedHeader,joseHeader)),{alg}=joseHeader;if(typeof alg!="string"||!alg)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(shared[0]&&!shared[0].has(alg))throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(b64){if(typeof inputPayload!="string")throw new JWSInvalid("JWS Payload must be a string")}else if(typeof inputPayload!="string"&&!(inputPayload instanceof Uint8Array))throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let signingPayload=b64||typeof inputPayload!="string"?inputPayload:encodeUnencodedPayload(inputPayload),resolvedKey=!1;typeof key2=="function"&&(key2=await key2(protectedHeader,jws),resolvedKey=!0);let entry=jwsAlgorithm(alg),signingInput=concat(encodedProtectedHeader!==void 0?encode(encodedProtectedHeader):new Uint8Array,encode("."),typeof signingPayload=="string"?shared[2]??=encodeAsciiMember(signingPayload,"payload",JWSInvalid):signingPayload),signature=decodeBase64url(jws.signature,"signature",JWSInvalid),verificationKey=await prepareKey(entry,key2,"verify"),cryptoKey=await rawKey(verificationKey,entry.subtle,"verify");entry.minRsaBits&&checkModulusLength(entry.alg,cryptoKey);let verified=!1;try{verified=await crypto.subtle.verify(entry.signing,cryptoKey,signature,signingInput)}catch(cause){throw new JWSSignatureVerificationFailed(void 0,{cause})}if(!verified)throw new JWSSignatureVerificationFailed;let result={payload:typeof signingPayload=="string"?decodeBase64url(signingPayload,"payload",JWSInvalid):signingPayload};return encodedProtectedHeader!==void 0&&(result.protectedHeader=protectedHeader),header!==void 0&&(result.unprotectedHeader=header),resolvedKey?[{...result,key:verificationKey},b64]:[result,b64]}async function verifyCompact(jws,shared,key2){if(jws instanceof Uint8Array&&(jws=decoder.decode(jws)),typeof jws!="string")throw new JWSInvalid("Compact JWS must be a string or Uint8Array");let{0:protectedHeader,1:payload,2:signature,length}=jws.split(".");if(length!==3)throw new JWSInvalid("Invalid Compact JWS");return verifySignature({payload,protected:protectedHeader,signature},shared,key2,encodeCompactUnencodedPayload)}var epoch=date=>Math.floor(date.getTime()/1e3),multipliers={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},REGEX=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,checkFailed="check_failed";function invalidDuration(){throw new TypeError("Invalid time period format")}function secs(str){typeof str!="string"&&invalidDuration();let matched=REGEX.exec(str);(!matched||matched[4]&&matched[1])&&invalidDuration();let value=parseFloat(matched[2]),durationSeconds=Math.round(value*multipliers[matched[3][0].toLowerCase()]);return Number.isFinite(durationSeconds)||invalidDuration(),matched[1]==="-"||matched[4]==="ago"?-durationSeconds:durationSeconds}function validateInput(label,input){if(!Number.isFinite(input))throw new TypeError(`Invalid ${label} input`);return input}var normalizeTyp=value=>{let normalized=value.toLowerCase();return value.includes("/")?normalized:`application/${normalized}`},checkAudiencePresence=(audPayload,audOption)=>typeof audPayload=="string"?audOption.includes(audPayload):Array.isArray(audPayload)?audOption.some(aud=>audPayload.includes(aud)):!1;function validateNumericDate(claimsSet,claim,required=!1){let value=claimsSet[claim];if(!(value===void 0&&!required)){if(typeof value!="number")throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`,claimsSet,claim,"invalid");return value}}function unexpectedClaim(claimsSet,claim){throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`,claimsSet,claim,checkFailed)}function validateClaimsSet(protectedHeader,claimsSetBytes,options={}){let claimsSet;try{claimsSet=JSON.parse(strictDecoder.decode(claimsSetBytes))}catch(cause){throw new JWTInvalid("JWT Claims Set must be a top-level JSON object",{cause})}if(!isObject(claimsSet))throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");let{typ}=options;if(typ!==void 0&&(typeof protectedHeader.typ!="string"||normalizeTyp(protectedHeader.typ)!==normalizeTyp(typ)))throw new JWTClaimValidationFailed('unexpected "typ" JWT header value',claimsSet,"typ",checkFailed);let{requiredClaims=[],issuer,subject,audience,maxTokenAge}=options,presenceCheck=[...requiredClaims];maxTokenAge!==void 0&&presenceCheck.push("iat"),audience!==void 0&&presenceCheck.push("aud"),subject!==void 0&&presenceCheck.push("sub"),issuer!==void 0&&presenceCheck.push("iss");for(let claim of new Set(presenceCheck.reverse()))if(!Object.hasOwn(claimsSet,claim))throw new JWTClaimValidationFailed(`missing required "${claim}" claim`,claimsSet,claim,"missing");issuer!==void 0&&!(Array.isArray(issuer)?issuer:[issuer]).includes(claimsSet.iss)&&unexpectedClaim(claimsSet,"iss"),subject!==void 0&&claimsSet.sub!==subject&&unexpectedClaim(claimsSet,"sub"),audience!==void 0&&!checkAudiencePresence(claimsSet.aud,typeof audience=="string"?[audience]:audience)&&unexpectedClaim(claimsSet,"aud");let{clockTolerance}=options,tolerance=0;if(typeof clockTolerance=="string")tolerance=secs(clockTolerance);else if(clockTolerance!==void 0){if(typeof clockTolerance!="number")throw new TypeError("Invalid clockTolerance option type");tolerance=clockTolerance}validateInput("clockTolerance option",tolerance);let{currentDate}=options,now=validateInput("currentDate option",epoch(currentDate===void 0?new Date:currentDate)),iat=validateNumericDate(claimsSet,"iat",maxTokenAge!==void 0),nbf=validateNumericDate(claimsSet,"nbf");if(nbf!==void 0&&nbf>now+tolerance)throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed',claimsSet,"nbf",checkFailed);let exp=validateNumericDate(claimsSet,"exp");if(exp!==void 0&&exp<=now-tolerance)throw new JWTExpired('"exp" claim timestamp check failed',claimsSet,"exp",checkFailed);if(maxTokenAge!==void 0){let age=now-iat,max=validateInput("maxTokenAge option",typeof maxTokenAge=="number"?maxTokenAge:secs(maxTokenAge));if(age-tolerance>max)throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)',claimsSet,"iat",checkFailed);if(age<-tolerance)throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',claimsSet,"iat",checkFailed)}return claimsSet}async function jwtVerify(jwt,key2,options){let[verified,b64]=await verifyCompact(jwt,prepareVerify(options),key2);if(!b64)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");let payload=validateClaimsSet(verified.protectedHeader,verified.payload,options);return{...verified,payload}}function isUsableJWK(jwk,entry,alg,kid){let{kty,key_ops:keyOps,ext,kid:jwkKid,alg:jwkAlg,use,crv}=jwk;return(ext===void 0||typeof ext=="boolean")&&(keyOps===void 0||Array.isArray(keyOps)&&keyOps.every((operation,index)=>typeof operation=="string"&&keyOps.indexOf(operation)===index)&&keyOps.includes("verify"))&&entry.kty.includes(kty)&&(kid===void 0||typeof kid=="string"&&kid===jwkKid)&&(jwkAlg===void 0?kty!=="AKP":alg===jwkAlg)&&(use===void 0||use==="sig")&&(!entry.crv||crv===entry.crv)}async function importWithAlgCache(cache2,jwk,entry){let cached=cache2.get(jwk)||cache2.set(jwk,{}).get(jwk),{alg}=entry;if(cached[alg]===void 0){let pending=jwkToKey(entry,jwk,!0).then(key2=>{if(key2.type!=="public")throw new JWKSInvalid("JSON Web Key Set members must be public keys");return cached[alg]=key2,key2}).catch(error=>{throw cached[alg]===pending&&delete cached[alg],error});cached[alg]=pending}return cached[alg]}function createLocalJWKSet(jwks){let snapshot;try{snapshot=structuredClone(jwks)}catch(cause){throw new JWKSInvalid("JSON Web Key Set malformed",{cause})}if(!isJwkSet(snapshot))throw new JWKSInvalid("JSON Web Key Set malformed");let metadata=snapshot.keys.map(jwk=>{let normalized=snapshotJwk(jwk);return Array.isArray(normalized.key_ops)&&(normalized.key_ops=[...normalized.key_ops]),normalized}),cached=new WeakMap;return Object.defineProperty(async(protectedHeader,token)=>{let{alg,kid}={...protectedHeader,...token?.header},entry=typeof alg=="string"?JWS[alg]:void 0;if(!entry||entry.secret)throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');let candidates=snapshot.keys.filter((_,index)=>isUsableJWK(metadata[index],entry,alg,kid)),{0:jwk,length}=candidates;if(!length)throw new JWKSNoMatchingKey;if(length!==1){let error=new JWKSMultipleMatchingKeys;throw error[Symbol.asyncIterator]=async function*(){for(let jwk2 of candidates)try{yield await importWithAlgCache(cached,jwk2,entry)}catch{}},error}return importWithAlgCache(cached,jwk,entry)},"jwks",{value:()=>structuredClone(snapshot)})}function isCloudflareWorkers(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var USER_AGENT;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(USER_AGENT="jose/v6.2.14");var customFetch=Symbol();async function fetchJwks(url,headers,signal,fetchImpl=fetch){let response=await fetchImpl(url,{method:"GET",signal,redirect:"manual",headers}).catch(err=>{throw err.name==="TimeoutError"?new JWKSTimeout(void 0,{cause:err}):err});if(response.status!==200)throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await response.json()}catch(cause){throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON",{cause})}}var jwksCache=Symbol();function isFreshFor(timestamp,duration){return Number.isFinite(timestamp)&&Date.now()<timestamp+duration}function validateDuration(value,fallback,option){if(Number.isNaN(value))throw new TypeError(`"${option}" option must not be NaN`);return typeof value=="number"?value:fallback}function createRemoteJWKSet(url,options){if(!(url instanceof URL))throw new TypeError("url must be an instance of URL");let href=new URL(url.href).href,opts=options??{},timeoutOption=opts.timeoutDuration;if(typeof timeoutOption=="number"&&(!Number.isInteger(timeoutOption)||timeoutOption<0))throw new TypeError('"timeoutDuration" option must be a non-negative integer');let timeoutDuration=typeof timeoutOption=="number"?timeoutOption:5e3,cooldownDuration=validateDuration(opts.cooldownDuration,3e4,"cooldownDuration"),cacheMaxAge=validateDuration(opts.cacheMaxAge,6e5,"cacheMaxAge"),headers=new Headers(opts.headers);USER_AGENT&&!headers.has("User-Agent")&&headers.set("User-Agent",USER_AGENT),headers.has("accept")||headers.set("accept","application/json, application/jwk-set+json");let fetchImpl=opts[customFetch],cache2=opts[jwksCache],jwksTimestamp,pendingFetch,reloadSequence=0,appliedSequence=0,local;if(cache2&&typeof cache2=="object"){let{uat,jwks}=cache2;isFreshFor(uat,cacheMaxAge)&&isJwkSet(jwks)&&(jwksTimestamp=uat,local=createLocalJWKSet(jwks))}let reload=async()=>{if(pendingFetch&&isCloudflareWorkers()&&(pendingFetch=void 0),!pendingFetch){let sequence=++reloadSequence,current=pendingFetch=fetchJwks(href,headers,AbortSignal.timeout(timeoutDuration),fetchImpl).then(json=>{let next=createLocalJWKSet(json);if(sequence<=appliedSequence)return;local=next;let updatedAt=Date.now();cache2&&(cache2.uat=updatedAt,cache2.jwks=json),jwksTimestamp=updatedAt,appliedSequence=sequence}).finally(()=>{pendingFetch===current&&(pendingFetch=void 0)})}await pendingFetch};return Object.defineProperties(async(protectedHeader,token)=>{(!local||!isFreshFor(jwksTimestamp,cacheMaxAge))&&await reload();try{return await local(protectedHeader,token)}catch(err){if(err instanceof JWKSNoMatchingKey&&!isFreshFor(jwksTimestamp,cooldownDuration))return await reload(),local(protectedHeader,token);throw err}},{coolingDown:{get:()=>isFreshFor(jwksTimestamp,cooldownDuration),enumerable:!0},fresh:{get:()=>isFreshFor(jwksTimestamp,cacheMaxAge),enumerable:!0},reload:{value:reload,enumerable:!0},reloading:{get:()=>!!pendingFetch,enumerable:!0},jwks:{value:()=>local?.jwks(),enumerable:!0}})}function decodeJwt(jwt){if(typeof jwt!="string")throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");let{1:encodedPayload,length}=jwt.split(".");if(length===5)throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(length!==3)throw new JWTInvalid("Invalid JWT");if(!encodedPayload)throw new JWTInvalid("JWTs must contain a payload");let claimsSetBytes;try{claimsSetBytes=decode(encodedPayload)}catch(cause){throw new JWTInvalid("Failed to base64url decode the payload",{cause})}let claimsSet;try{claimsSet=JSON.parse(strictDecoder.decode(claimsSetBytes))}catch(cause){throw new JWTInvalid("Failed to parse the decoded payload as JSON",{cause})}if(!isObject(claimsSet))throw new JWTInvalid("Invalid JWT Claims Set");return claimsSet}var PERMISSIONS=["read","post","react","label","sync","manage"],IMPLIES={read:[],post:[],react:["read"],label:["read"],sync:["read"],manage:["read","post","react","label","sync"]},ORDER=new Map(PERMISSIONS.map((permission,index)=>[permission,index])),SHAPE="write *, a channel, or a channel and its subtree (feedback/)";function parsePattern(pattern){if(pattern==="*")return{kind:"all"};if(pattern.includes("*")){let before=pattern.slice(0,pattern.indexOf("*")).replace(/\/+$/,""),hint=before===""?"write * for every channel":ChannelPath.safeParse(before).success?`write ${before}/ for ${before} and its subtree`:SHAPE;throw new Error(`invalid channel pattern ${pattern}: ${hint}`)}let subtree=pattern.endsWith("/"),path=subtree?pattern.slice(0,-1):pattern;if(!ChannelPath.safeParse(path).success)throw new Error(`invalid channel pattern ${pattern||"(empty)"}: ${SHAPE}`);return subtree?{kind:"subtree",path}:{kind:"exact",path}}var key=pattern=>pattern.kind==="all"?"*":pattern.kind==="subtree"?`${pattern.path}/`:pattern.path;function expand(grant){let out=new Set,add=permission=>{if(!ORDER.has(permission))throw new Error(`unknown permission ${String(permission)}: use ${PERMISSIONS.join(", ")}`);if(!out.has(permission)){out.add(permission);for(let implied of IMPLIES[permission])add(implied)}};for(let permission of grant==="all"?PERMISSIONS:grant)add(permission);return out}var NOTHING=new Set;function compile(entries){let all=null,exact=new Map,subtrees=[];for(let[pattern,permissions]of entries)pattern.kind==="all"?all=permissions:pattern.kind==="exact"?exact.set(pattern.path,permissions):subtrees.push([pattern.path,permissions]);return subtrees.sort((a,b)=>b[0].length-a[0].length),{all,exact,subtrees}}var under=(channel,path)=>channel===path||channel.startsWith(`${path}/`);function resolve(rules,channel,subtreeOnly=!1){if(!subtreeOnly){let exact=rules.exact.get(channel);if(exact)return exact}for(let[path,permissions]of rules.subtrees)if(under(channel,path))return permissions;return rules.all??NOTHING}var at=(rules,pattern)=>pattern.kind==="all"?rules.all??NOTHING:resolve(rules,pattern.path,pattern.kind==="subtree"),equal=(a,b)=>a.size===b.size&&[...a].every(permission=>b.has(permission));function parent(rules,pattern){if(pattern.kind==="exact")return resolve(rules,pattern.path,!0);if(pattern.kind==="subtree"){for(let[path,permissions]of rules.subtrees)if(path!==pattern.path&&under(pattern.path,path))return permissions}return rules.all??NOTHING}function canonical(entries){let rules=compile(entries);return compile(entries.filter(([pattern,permissions])=>pattern.kind==="all"?permissions.size>0:!equal(permissions,parent(rules,pattern))))}function entriesOf(can){return can==="all"||Array.isArray(can)?[[{kind:"all"},expand(can)]]:Object.entries(can).map(([pattern,grant])=>[parsePattern(pattern),expand(grant)])}var entriesIn=rules=>[...rules.all?[[{kind:"all"},rules.all]]:[],...rules.subtrees.map(([path,permissions])=>[{kind:"subtree",path},permissions]),...[...rules.exact].map(([path,permissions])=>[{kind:"exact",path},permissions])],RULES=Symbol("board.access"),isAccess=value=>typeof value=="object"&&RULES in value;function fromRules(rules){let entries=entriesIn(rules),everywhere=permission=>(rules.all?.has(permission)??!1)&&entries.every(([,permissions])=>permissions.has(permission)),readable=new Map;return{[RULES]:rules,can:(permission,channel)=>resolve(rules,channel).has(permission),readable(channel){let found=readable.get(channel);return found===void 0&&readable.set(channel,found=resolve(rules,channel).has("read")),found},readsAll:everywhere("read"),everywhere,anywhere:permission=>entries.some(([,permissions])=>permissions.has(permission)),narrow(scope){let other=isAccess(scope)?scope[RULES]:canonical(entriesOf(scope)),patterns=new Map([["*",{kind:"all"}]]);for(let[pattern]of[...entries,...entriesIn(other)])patterns.set(key(pattern),pattern);return fromRules(canonical([...patterns.values()].map(pattern=>{let theirs=at(other,pattern);return[pattern,new Set([...at(rules,pattern)].filter(permission=>theirs.has(permission)))]})))},summary(){let named=entries.map(([pattern,permissions])=>[key(pattern),permissions]);named.sort(([a],[b])=>a==="*"?-1:b==="*"?1:a.localeCompare(b));let out={};for(let[name,permissions]of named)out[name]=[...permissions].sort((a,b)=>ORDER.get(a)-ORDER.get(b));return out}}}function compileAccess(can){return fromRules(canonical(entriesOf(can)))}var FULL_ACCESS=compileAccess("all");function parseScope(header){if(header.length>4e3)throw new Error(`x-board-scope is longer than ${SCOPE_MAX} characters`);let out={},entries=header.split(";").map(entry=>entry.trim());if(entries.every(entry=>entry===""))throw new Error("x-board-scope is empty: write pattern=permissions, like dev/=read,post");for(let entry of entries){if(entry==="")continue;let split=entry.indexOf("=");if(split<0)throw new Error(`x-board-scope entry ${entry} needs =: write pattern=permissions, like dev/=read,post`);let pattern=entry.slice(0,split).trim(),list=entry.slice(split+1).trim();if(Object.hasOwn(out,pattern))throw new Error(`x-board-scope lists ${pattern} twice`);parsePattern(pattern);let permissions=list===""?[]:list.split(",").map(permission=>permission.trim());if(permissions.length===1&&permissions[0]==="all"){out[pattern]="all";continue}for(let permission of permissions)if(!ORDER.has(permission))throw new Error(`x-board-scope: unknown permission ${permission||"(empty)"}: use ${PERMISSIONS.join(", ")}, or all`);out[pattern]=permissions}return out}var notInAccess=rule=>forbidden(`this token can't use this board: add ${rule} to access`);var VERCEL_ISSUER=/^https:\/\/oidc\.vercel\.com(?:\/[a-z0-9-]+)?$/;var issuerName=iss=>{let url=new URL(iss);return`${url.host}${url.pathname.replace(/\/+$/,"")}`.replace(/[%:]/g,char=>char==="%"?"%25":"%3A")};function trustedIssuers(issuers){let named=new Map;for(let iss of issuers){let name=issuerName(iss),other=named.get(name);if(other!==void 0&&other!==iss)throw new Error(`access: oidc issuers ${other} and ${iss} name the same principals, oidc:${name}:<sub>: pin one of them`);named.set(name,iss)}return new Set(issuers)}var issuersOf=rules=>[...new Set(rules.flatMap(rule=>typeof rule!="function"&&rule.issuer==="oidc"?[rule.url]:[]))];function createAuthority(options){let rules=typeof options.access=="function"?[]:options.access,host=typeof options.access=="function"?options.access:null,oidcIssuers=trustedIssuers(issuersOf(rules));async function byRules(principal,facts){if(facts?.issuer==="host")throw forbidden("this token can't use this board: its board no longer takes a host's principals");if(facts?.issuer==="oidc"&&!oidcIssuers.has(facts.iss))throw unauthorized(`untrusted issuer: ${facts.iss}`);let claims=facts?.claims??{},own=facts?.issuer==="vercel"?await options.project():null,context=own?{teamId:facts.team??own.teamId,projectId:own.id}:{teamId:null,projectId:null},environment=String(claims.environment??""),here=boardEnvironment(),ownDeployment=own!==null&&own.id!==null&&claims.project_id===own.id,ownHere=ownDeployment&&here!==null&&environment===here;for(let rule of rules){if(typeof rule=="function"){if(ownHere)continue;let can=await rule(principal);if(can===void 0)continue;if(can===null)throw forbidden("this token can't use this board");return compileAccess(can)}if(facts&&rule.issuer===facts.issuer&&(rule.issuer!=="oidc"||rule.url===facts.iss)&&rule.matches(claims,context))return rule.access}if(ownHere)return FULL_ACCESS;throw facts?facts.issuer==="oidc"?notInAccess(`oidc({ issuer: '${facts.iss}', claims, can })`):facts.issuer==="github"?notInAccess(`githubActions({ repository: '${String(claims.repository)}', can })`):ownDeployment?forbidden(`this token can't use this board: it runs in ${here??"no Vercel environment"}, so its ${environment||"unnamed"} deployments need vercelProject({ project: 'self', environments: ['${environment}'], can })`):notInAccess(`vercelProject({ project: '${String(claims.project??"")||String(claims.project_id)}', can })`):forbidden("this token can't use this board")}async function grant(principal){let access=FULL_ACCESS,hosted=principal.facts?.issuer==="host";if(principal.id.startsWith("board:")||principal.kind==="external"&&!hosted)access=FULL_ACCESS;else{if(hosted){if(!options.hosts)throw forbidden("this token can't use this board: its board no longer takes a host's principals");let{exp}=principal.facts.claims;if(typeof exp=="number"&&exp*1e3<=Date.now())throw unauthorized("token expired")}if(host){let can=await host(principal);if(can==null)throw forbidden("this token can't use this board");access=compileAccess(can)}else principal.kind!=="person"&&(access=await byRules(principal,(hosted?void 0:principal.facts)??factsFromId(principal.id)))}return principal.scope===void 0?access:access.narrow(parseScope(principal.scope))}async function accessNow(principal){try{return await grant(principal)}catch(error){let status=error.status;if(status===401||status===403)return null;throw error}}return{grant,accessNow}}var boardEnvironment=()=>process.env.VERCEL_TARGET_ENV||process.env.VERCEL_ENV||null;function factsFromId(id){let deployment=id.match(/^vercel:project:([^:]+):([^:]+)$/);return deployment?{issuer:"vercel",iss:"",claims:{project_id:deployment[1],environment:deployment[2]}}:null}var TOKENS=Symbol("board.oidcTokens"),verifiedTokens=new WeakSet;function markVerified(principal){return verifiedTokens.add(principal),principal}var verifiesTokens=authenticate=>TOKENS in authenticate,fromTokens=principal=>verifiedTokens.has(principal),PRINCIPAL_ID=/^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*:[^\s+\]]{1,200}$/,KINDS=["person","deployment","workflow","external"];function hostPrincipal(value){let fail=why=>{throw new TypeError(`authenticate returned an invalid principal: ${why}`)};(typeof value!="object"||value===null)&&fail("not an object"),(typeof value.id!="string"||!PRINCIPAL_ID.test(value.id)||value.id.startsWith("board:"))&&fail(`id must look like \`vercel:user:<id>\`, got ${JSON.stringify(value.id)}`),KINDS.includes(value.kind)||fail(`kind must be one of ${KINDS.join(", ")}`),(typeof value.handle!="string"||!/^\S{1,64}$/.test(value.handle))&&fail("handle must be 1-64 characters, no spaces");let expiresAt=value.expiresAt??null;if(expiresAt!==null&&(!(expiresAt instanceof Date)||Number.isNaN(expiresAt.getTime()))&&fail("expiresAt must be a Date or null"),expiresAt!==null&&expiresAt.getTime()<=Date.now())throw unauthorized("token expired");let claims=expiresAt===null?{}:{exp:Math.floor(expiresAt.getTime()/1e3)};return{id:value.id,kind:value.kind,handle:value.handle,expiresAt,facts:{issuer:"host",iss:"",claims}}}export{jwtVerify,createRemoteJWKSet,decodeJwt,compileAccess,parseScope,VERCEL_ISSUER,issuerName,trustedIssuers,issuersOf,createAuthority,TOKENS,markVerified,verifiesTokens,fromTokens,hostPrincipal};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
const __dirname = __dirname_(__filename);
|
|
7
|
-
var options={re:{type:"string",value:"id",description:"in a thread: its root's ID"},by:{type:"string",value:"handle",description:"by an author: a handle, me, or an actor ID"},mentions:{type:"string",value:"@handle",optionalValue:!0,description:"mentioning a handle, or you without one"},label:{type:"string",multiple:!0,value:"k[=v|w]",description:"with a label on the message or its thread's root"},source:{type:"string",value:"source",description:"from a source: a sync key such as slack, or board"},text:{type:"string",value:"words",description:"containing these words"},after:{type:"string",value:"id",description:"after a message or a cursor"},url:{type:"string",value:"url",description:"the board at this URL, not the one the environment points at"},scope:{type:"string",value:"team",description:"a team's board in Vercel's API, by its slug or ID"},team:{type:"string",value:"team",description:"the same as --scope",hidden:!0},as:{type:"string",value:"profile",description:"write as a profile, such as an agent's name"},avatar:{type:"string",value:"url",description:"the profile's avatar, with --as"},human:{type:"boolean",description:"write as yourself, with no profile or session"},handle:{type:"string",value:"h",description:"your handle (default: your Vercel username)"},json:{type:"boolean",description:"JSON, for programs"},help:{type:"boolean",short:"h",description:"this help, or a command's"},version:{type:"boolean",short:"v",description:"the CLI's version"},limit:{type:"string",short:"n",value:"N",description:"how many"},"idempotency-key":{type:"string",value:"key",description:"sending the same one again posts once"},sync:{type:"string",multiple:!0,value:"target",description:"sync the new thread to a target too, e.g. slack:#incidents"},"no-sync":{type:"boolean",description:"keep it on the board: sync it nowhere"},attach:{type:"string",multiple:!0,value:"file",description:"attach a file"},unset:{type:"string",multiple:!0,value:"k",description:"remove a label"},if:{type:"string",multiple:!0,value:"k=v",description:"only while the message has this label now"},"if-unset":{type:"string",multiple:!0,value:"k",description:"only while the message doesn't have this label"},"if-revision":{type:"string",value:"N",description:"only if it is still at this revision, as read --json shows it"},channel:{type:"string",value:"c",description:"in a channel"},remove:{type:"boolean",description:"take the reaction back"},all:{type:"boolean",short:"a",description:"everything, not only what most want"},timeout:{type:"string",value:"duration",description:"how long to wait (default: 30m)"},code:{type:"boolean",description:"post a code from your account instead of signing in"},"no-wait":{type:"boolean",description:"start linking, and don't wait for it to finish"},"no-open":{type:"boolean",description:"don't open the browser"},in:{type:"string",value:"duration",description:"once, this long from now, e.g. 1d"},at:{type:"string",value:"time",description:"at a time: once, or with --every, the first"},every:{type:"string",value:"duration",description:"repeating at this interval, e.g. 30m"},until:{type:"string",short:"u",value:"time",description:"repeating until a time"},for:{type:"string",value:"duration",description:"repeating for this long, e.g. 24h"},times:{type:"string",value:"N",description:"repeating this many times"},port:{type:"string",value:"N",description:"the port to listen on"},dir:{type:"string",value:"dir",description:"where the board keeps its log (default: .board/)"},"no-inspect":{type:"boolean",description:"don't start the inspector"},agent:{type:"string",value:"name",description:"the agent whose turn ended",hidden:!0}},option=(name,description,value)=>({name,...options[name],...description?{description}:{},...value?{value}:{}}),filters=["re","by","source","label","text","mentions","after"].map(name=>option(name)),globalOptions=["url","scope","team","as","avatar","human","handle","json","help","version"].map(name=>option(name)),id=(description="a message ID, as read shows it (#812)")=>({name:"id",required:!0,description}),text=(description="what it says: - reads it from stdin, and it may be left out when you --attach")=>({name:"text",required:!1,description}),AFTER="a reply only while this is the thread's newest message",groups=["you","the board","messages","agents","live"],commands=[{group:"you",name:"whoami",description:"who am I, on which board, with which token, and what I can do",arguments:[],options:[],examples:[{name:"see who you are on the board",value:"whoami"}]},{group:"the board",name:"channels",description:"channels, grouped by path prefix",arguments:[],options:[],examples:[{name:"list the channels",value:"channels"}]},{group:"the board",name:"actors",description:"actors and their handles",arguments:[],options:[],examples:[{name:"list who has written here",value:"actors"}]},{group:"the board",name:"identity",description:"your linked Slack and GitHub accounts",arguments:[],options:[],runsWithoutSubcommand:!0,examples:[{name:"list your linked accounts",value:"identity"}],subcommands:[{name:"link",description:"link your account on a sync entry: sign in, or post a code from it",arguments:[{name:"key",required:!0,description:"the sync entry, e.g. slack"}],options:[option("code"),option("no-wait"),option("no-open")],examples:[{name:"link your Slack account",value:"identity link slack"}]},{name:"unlink",description:"unlink one, by handle or actor ID",arguments:[{name:"account",required:!0,description:"a handle or actor ID from identity"}],options:[],examples:[{name:"unlink an account",value:"identity unlink @ada"}]}]},{group:"messages",name:"read",description:"the latest threads, one each (root, replies, latest reply), or one thread, every message",arguments:[{name:"channel|id|link",required:!1,description:"a channel (every channel without one), a message's ID, or a Slack or GitHub link the board synced"}],options:[option("limit","threads to list (default: 50)")],filters:!0,examples:[{name:"list a channel's latest threads",value:"read dev"},{name:"read one thread, every message",value:"read 812"},{name:"list the open bugs",value:"read dev --label kind=bug --label state=open"}]},{group:"messages",name:"post",description:"a new thread in a channel, or with an ID, a reply in its thread",arguments:[{name:"channel|id",required:!0,description:"a channel, or a message ID to reply in its thread"},text()],options:[option("label","label it","k=v"),option("attach"),option("sync"),option("no-sync"),option("idempotency-key"),option("after",AFTER)],examples:[{name:"start a thread",value:'post dev "deploys are green again"'},{name:"start a labeled thread",value:'post dev "checkout times out" --label kind=bug'}]},{group:"messages",name:"reply",description:"a reply in a thread",arguments:[id("the ID of a message in the thread"),text()],options:[option("attach"),option("idempotency-key"),option("no-sync"),option("after",AFTER)],examples:[{name:"reply in a thread",value:'reply 812 "on it"'},{name:"reply only if #815 is still the thread's newest",value:'reply 812 "on it" --after 815'}]},{group:"messages",name:"schedule",description:"post later, as you: once (--in or --at), or repeating (--every) until a stop or until canceled",arguments:[{name:"channel|id",required:!0,description:"a channel, or a message ID to reply in its thread"},text()],options:[option("in"),option("at"),option("every"),option("until"),option("for"),option("times"),option("label","label it","k=v"),option("attach"),option("no-sync")],examples:[{name:"reply in a thread tomorrow",value:'schedule 812 "still broken?" --in 1d'},{name:"post every morning",value:'schedule dev "standup" --at 2026-11-02T09:00:00Z --every 1d'}],runsWithoutSubcommand:!0,subcommands:[{name:"cancel",description:"stop one (yours, or with manage)",arguments:[{name:"schedule",required:!0,description:"its ID, as schedules shows it (s12)"}],options:[],examples:[{name:"cancel a schedule",value:"schedule cancel s12"}]}]},{group:"messages",name:"schedules",description:"pending schedules, or a thread's with an ID",arguments:[{name:"id",required:!1,description:"a message in the thread"}],options:[option("by","scheduled by a handle"),option("channel","posting in a channel"),option("all","done and canceled ones too")],examples:[{name:"list pending schedules",value:"schedules"}]},{group:"messages",name:"edit",description:"change a message's text",arguments:[id(),{name:"text",required:!0,description:"its new text: - reads it from stdin"}],options:[option("if-revision")],examples:[{name:"fix a typo",value:'edit 812 "deploys are green again"'},{name:"only if no one changed it since you read it",value:'edit 812 "step 3 of 5" --if-revision 820'}]},{group:"messages",name:"delete",aliases:["rm","del"],description:"delete a message, leaving a tombstone",arguments:[id()],options:[option("if-revision")],examples:[{name:"delete a message",value:"delete 812"}]},{group:"messages",name:"react",description:"react to a message",arguments:[id(),{name:"emoji",required:!0,description:"its name or the emoji itself: eyes, \u{1F440}"}],options:[option("remove")],examples:[{name:"react with eyes",value:"react 812 eyes"}]},{group:"messages",name:"label",description:"set labels on a message, or remove them",arguments:[id(),{name:"k=v",required:!1,multiple:!0,description:"a label to set"}],options:[option("unset"),option("if"),option("if-unset")],examples:[{name:"mark a bug fixed",value:"label 812 state=fixed --unset wip"},{name:"claim a thread, unless someone has",value:"label 812 owner=claude --if-unset owner"},{name:"move it on from open only",value:"label 812 state=fixing --if state=open"}]},{group:"messages",name:"typing",description:"show typing in the thread's synced platform threads (marks WhatsApp read)",arguments:[id(),{name:"status",required:!1,description:'what Slack shows instead of "Typing\u2026"'}],options:[],examples:[{name:"show typing while you work",value:'typing 812 "looking into it"'}]},{group:"messages",name:"sync",description:"where the thread is synced, or with a target, attach it there (backfilling it)",arguments:[id(),{name:"target",required:!1,description:"where to sync it, e.g. slack:#incidents"}],options:[],examples:[{name:"list where a thread is synced",value:"sync 812"},{name:"sync a thread to a Slack channel",value:"sync 812 slack:#incidents"}]},{group:"messages",name:"inbox",description:"raw platform events, for debugging sync",arguments:[{name:"key",required:!0,description:"the sync entry, e.g. slack"},{name:"channel",required:!1,description:"the board channel its events went to"}],options:[option("limit","events to list")],examples:[{name:"list Slack's latest events",value:"inbox slack"}]},{group:"messages",name:"sources",description:"the board's sources: its sync entries (slack, github, \u2026)",arguments:[{name:"key",required:!1,description:"a sync entry, e.g. slack"}],options:[],runsWithoutSubcommand:!0,argumentsBeforeSubcommand:!0,examples:[{name:"list the board's sources",value:"sources"}],subcommands:[{name:"read",description:"read a source's channel, thread, or message link without syncing it (full access only)",arguments:[{name:"target",required:!0,description:"a channel ('#general'), a thread, or a message link"}],options:[option("limit","messages to read"),option("after","where the last read left off: the cursor it printed")],examples:[{name:"read a Slack channel",value:"sources slack read '#general'"},{name:"read a Linear project's issues",value:"sources linear read https://linear.app/acme/project/checkout-a1b2c3"}]},{name:"join",description:"add the app to a public channel so it can be read, where the board opted in (full access only)",arguments:[{name:"channel",required:!0,description:"a channel or its link"}],options:[],examples:[{name:"join a Slack channel",value:"sources slack join '#general'"}]}]},{group:"messages",name:"download",description:"save an attachment (its name, here, by default; - for stdout)",arguments:[{name:"attachment",required:!0,description:"the ID read shows on a file line"},{name:"path",required:!1,description:"where to save it, or - for stdout"}],options:[],examples:[{name:"save an attachment",value:"download Yt2mR8vQ1x0pLk3sF7dA9w"}]},{group:"messages",name:"conformance",description:"check that the board speaks the protocol (1 if a check fails): it posts, and deletes what it posted",arguments:[],options:[option("channel","the channel to check in (default: conformance)")],examples:[{name:"check the board",value:"conformance"}]},{group:"agents",name:"hooks",description:"the turn-end hooks an earlier board installed",arguments:[],options:[],examples:[],subcommands:[{name:"uninstall",description:"remove the turn-end hooks an earlier board installed, from every agent or the ones named",arguments:[{name:"agent",required:!1,multiple:!0,description:"claude, codex, cursor, or pi"}],options:[],examples:[{name:"remove every hook",value:"hooks uninstall"}]}]},{group:"agents",name:"hook",description:"what an earlier turn-end hook runs: it does nothing now",arguments:[{name:"event",required:!1,multiple:!0}],options:[option("agent")],examples:[],hidden:!0},{group:"live",name:"tail",description:"what happens, live, until Ctrl-C",arguments:[{name:"channel",required:!1,description:"a channel, or a path prefix (dev/)"}],options:[option("all","delivery receipts too")],filters:!0,examples:[{name:"follow the bugs",value:"tail dev --label kind=bug"}]},{group:"live",name:"wait",description:"block for the next match and print it",arguments:[{name:"channel",required:!1,description:"a channel, or a path prefix (dev/)"}],options:[option("timeout")],filters:!0,examples:[{name:"wait for a mention",value:"wait dev --mentions --timeout 10m"}]},{group:"live",name:"help",description:"this help, or a command's",arguments:[{name:"command",required:!1,multiple:!0}],options:[],examples:[],hidden:!0}];function usage(path){let words=[];return path.forEach((command,at)=>{let last=at===path.length-1;if(words.push(command.name),last||command.argumentsBeforeSubcommand)for(let argument of command.arguments){let required=argument.required||!last;words.push(`${required?`<${argument.name}>`:`[${argument.name}]`}${argument.multiple?"...":""}`)}}),path.at(-1)?.filters&&words.push("[filters]"),words.join(" ")}export{options,filters,globalOptions,groups,commands,usage};
|