@alva-ai/toolkit 0.29.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/dist/browser.global.js +63 -24
- package/dist/browser.global.js.map +1 -1
- package/dist/cli.d.ts +137 -1
- package/dist/cli.js +377 -40
- package/dist/cli.js.map +1 -1
- package/dist/dispatch.d.ts +137 -1
- package/dist/dispatch.js +174 -17
- package/dist/dispatch.js.map +1 -1
- package/dist/index.cjs +294 -31
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +138 -2
- package/dist/index.d.ts +138 -2
- package/dist/index.js +294 -31
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/browser.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AlvaToolkit=(()=>{var fe=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var fn=Object.prototype.hasOwnProperty;var r=(t,e)=>fe(t,"name",{value:e,configurable:!0});var yn=(t,e)=>{for(var n in e)fe(t,n,{get:e[n],enumerable:!0})},gn=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of hn(e))!fn.call(t,s)&&s!==n&&fe(t,s,{get:()=>e[s],enumerable:!(i=mn(e,s))||i.enumerable});return t};var bn=t=>gn(fe({},"__esModule",{value:!0}),t);var ir={};yn(ir,{AlertsResource:()=>V,AlvaClient:()=>nt,AlvaError:()=>u,AutomationAlertDeliveryResource:()=>pe,AutomationResource:()=>Q,CliUsageError:()=>be,ForYouResource:()=>B,MarketsResource:()=>W,PBSV_UPDATE_MESSAGE:()=>vt,SUBSCRIBE_MANAGE_MESSAGE:()=>qt,SUBSCRIBE_PROPOSE_MESSAGE:()=>Ct,SUBSCRIBE_RESULT_MESSAGE:()=>It,SchedulesResource:()=>Y,StewardResource:()=>H,ThesesResource:()=>K,TradingPairsResource:()=>z,UDF_AUTH_REQUIRED_MESSAGE:()=>At,UDF_CONSENT_REQUEST_MESSAGE:()=>Tt,UDF_CONSENT_RESPONSE_MESSAGE:()=>Et,UdfAuthRequiredError:()=>$,UdfConsentDeniedError:()=>ne,UdfConsentRequiredError:()=>te,UdfConsentTimeoutError:()=>ie,UdfError:()=>b,UdfExecutionError:()=>le,UdfFunctionDisabledError:()=>oe,UdfFunctionNotFoundError:()=>se,UdfInsufficientCredits:()=>re,UdfPidMismatchError:()=>D,UdfRateLimitedError:()=>ae,UdfTokenExpiredError:()=>Z,UdfTokenInvalidError:()=>ee,UdfTransportError:()=>j,VERSION:()=>nr,getViewerToken:()=>ue,installPlaybookRuntime:()=>ut,mapUdfErrorResponse:()=>at,playbookIdFromToken:()=>ot,subscribe:()=>Gt,udf:()=>Lt});var b=class extends Error{static{r(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:i={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=i,this.status=s}},$=class extends b{static{r(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},Z=class extends b{static{r(this,"UdfTokenExpiredError")}},ee=class extends b{static{r(this,"UdfTokenInvalidError")}},D=class extends b{static{r(this,"UdfPidMismatchError")}},te=class extends b{static{r(this,"UdfConsentRequiredError")}},ne=class extends b{static{r(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},ie=class extends b{static{r(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},re=class extends b{static{r(this,"UdfInsufficientCredits")}},se=class extends b{static{r(this,"UdfFunctionNotFoundError")}},oe=class extends b{static{r(this,"UdfFunctionDisabledError")}},ae=class extends b{static{r(this,"UdfRateLimitedError")}},le=class extends b{static{r(this,"UdfExecutionError")}},j=class extends b{static{r(this,"UdfTransportError")}},vt="alva:pbsv:update",Tt="alva:udf:consent-request",Et="alva:udf:consent-response",At="alva:udf:auth-required",Ct="alva:subscribe:propose",It="alva:subscribe:result",qt="alva:subscribe:manage",xt="https://api-llm.prd.alva.ai",Dt=300*1e3,X=null,T=null,st=xt,C=null,R=null,wt=!1,ye=new Map,ge=new Map,_n=r(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Pn=r(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),ot=r(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Pn(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),ue=r(()=>X,"getViewerToken"),M=r(()=>!!ue(),"isAuthenticated"),Rn=r(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),kn=r(t=>{let e=new URLSearchParams(t.location.search);X=e.get("_pbsv"),T=e.get("parent_origin"),st=(e.get("api_origin")||xt).replace(/\/$/,""),C=ot(X),X&&Rn(t)},"parseBootParams"),Nt=r(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Sn=r(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),wn=r(t=>{let e=t;return{...e,result:Sn(e.result)}},"normalizeInvokeResponse"),Ut=r(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),at=r((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,s=Ut(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new Z(i,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new ee(i,o);case"PBSV_PID_MISMATCH":return new D(i,o);case"CONSENT_REQUIRED":return new te(i,o);case"INSUFFICIENT_CREDITS":return new re(i,o);case"FUNCTION_NOT_FOUND":return new se(i,o);case"FUNCTION_DISABLED":return new oe(i,o);case"RESOURCE_EXHAUSTED":return new ae(i,o);case"EXECUTION_FAILED":return new le(i,o);default:return new j(i,o)}},"mapUdfErrorResponse"),vn=r(t=>{if(!R||!T||t.origin!==T||t.source!==R.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===vt){typeof e.token=="string"&&e.token.length>0&&(X=e.token,C=ot(e.token));return}if(e.type===It){if(typeof e.request_id!="string")return;let i=ge.get(e.request_id);if(!i)return;clearTimeout(i.timer),ge.delete(e.request_id),i.resolve(_n(e.status));return}if(e.type!==Et||typeof e.request_id!="string")return;let n=ye.get(e.request_id);n&&(clearTimeout(n.timer),ye.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),Ft=r(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),Tn=r(()=>{if(!C)return null;let t=Number(C);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),En=r(async(t,e)=>{if(!R||!T)return"denied";let n=T,i=Ft();return new Promise(s=>{let o=setTimeout(()=>{ye.delete(i),s("timeout")},Dt);ye.set(i,{resolve:s,timer:o}),R?.parent.postMessage({type:Tt,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),An=r(async t=>{if(!R||!T)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",n=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!n)return"error";let i=T,s=Ft();return new Promise(o=>{let a=setTimeout(()=>{ge.delete(s),o("timeout")},Dt);ge.set(s,{resolve:o,timer:a}),R?.parent.postMessage({type:Ct,request_id:s,playbook_id:C,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),Cn=r(()=>{!R||!T||R.parent.postMessage({type:qt,playbook_id:C},T)},"manageSubscriptions"),Gt={propose:An,manage:Cn},In=r(t=>{!R||!T||R.parent.postMessage({type:At,function_name:t},T)},"requestAuthentication"),lt=r(async(t,e,n=!1)=>{let i=ue();if(!i)throw new $;if(!C)throw new D("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=Tn();if(!s)throw new D("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${st}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new j("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Nt(o);if(o.ok)return wn(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let l=Ut(a),c=typeof l.playbook_id=="string"?l.playbook_id:C,d=typeof l.min_allowance_suggested=="number"?l.min_allowance_suggested:1,p=await En(c,d);if(p==="granted")return lt(t,e,!0);throw p==="timeout"?new ie:new ne}throw at(a,o.status)},"call"),qn=r(async()=>{let t=ue();if(!t)throw new $;if(!C)throw new D("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${st}/api/v1/service/functions`);e.searchParams.set("playbook_id",C);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await Nt(n);if(!n.ok)throw at(i,n.status);let s=i.functions;return Array.isArray(s)?s:[]},"list"),rt=r((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),xn=r(t=>{if(typeof t!="string")return t;let n=R?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),Dn=r((t,e)=>{if(!R)throw new Error("Playbook runtime is not installed.");let n=xn(t),i=R.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=M()?s:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),M()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!M()){In(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=o,rt(i,"alva:udf-button:loading",{functionName:e.functionName});try{let l=await lt(e.functionName,e.params??{});rt(i,"alva:udf-button:result",{functionName:e.functionName,result:l})}catch(l){rt(i,"alva:udf-button:error",{functionName:e.functionName,error:l})}finally{i.disabled=!1,i.textContent=M()?s:a,M()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),Lt={call:lt,list:qn,getViewerToken:ue,isAuthenticated:M,renderButton:Dn,UdfError:b,UdfAuthRequiredError:$,UdfTokenExpiredError:Z,UdfTokenInvalidError:ee,UdfPidMismatchError:D,UdfConsentRequiredError:te,UdfConsentDeniedError:ne,UdfConsentTimeoutError:ie,UdfInsufficientCredits:re,UdfFunctionNotFoundError:se,UdfFunctionDisabledError:oe,UdfRateLimitedError:ae,UdfExecutionError:le,UdfTransportError:j},ut=r(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||wt)return;R=e,wt=!0,kn(e),e.addEventListener("message",vn);let n=e,i=n.alva||{};n.alva={...i,udf:Lt,subscribe:Gt}},"installPlaybookRuntime");var u=class extends Error{static{r(this,"AlvaError")}code;status;details;constructor(e,n,i,s){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=s}},be=class extends Error{static{r(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function Ot(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}r(Ot,"isArrayBuffer");var Mt=1;function Nn(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,s=0,o=0;if(n>=194&&n<=223)i=1,s=128,o=n&31;else if(n>=224&&n<=239)i=2,s=2048,o=n&15;else if(n>=240&&n<=244)i=3,s=65536,o=n&7;else return!1;if(e+i>=t.length)return!1;for(let a=1;a<=i;a+=1){let l=t[e+a];if((l&192)!==128)return!1;o=o<<6|l&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=i+1}return!0}r(Nn,"isValidUtf8");var _e=class{constructor(e){this.client=e}client;static{r(this,"FsResource")}async read(e){let n=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!Ot(n)||!Nn(new Uint8Array(n)))return n;let i=new TextDecoder("utf-8").decode(n);try{return JSON.parse(i)}catch{return i}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:Mt}:{}}})}async rawWrite(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{query:{path:e.path,mkdir_parents:e.mkdir_parents,...e.append?{flags:Mt}:{}},rawBody:e.body})}async stat(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/stat",{query:{path:e.path}})}async readdir(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readdir",{query:{path:e.path,recursive:e.recursive}})}async mkdir(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/mkdir",{body:{path:e.path}})}async remove(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/fs/remove",{query:{path:e.path,recursive:e.recursive}})}async rename(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/rename",{body:{old_path:e.old_path,new_path:e.new_path}})}async copy(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/copy",{body:{src_path:e.src_path,dst_path:e.dst_path}})}async symlink(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/symlink",{body:{target_path:e.target_path,link_path:e.link_path}})}async readlink(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readlink",{query:{path:e.path}})}async chmod(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/chmod",{body:{path:e.path,mode:e.mode}})}async grant(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/grant",{body:{path:e.path,subject:e.subject,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/revoke",{body:{path:e.path,subject:e.subject,permission:e.permission}})}};var $t="9007199254740991";function jt(t,e,n,i){let s=t.length+e,o=n.length+i;if(s!==o)return s>o;for(let a=0;a<s;a++){let l=a<t.length?t[a]:"0",c=a<n.length?n[a]:"0";if(l!==c)return l>c}return!1}r(jt,"scaledIntegerGreater");function Un(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,i=e.groups.fraction??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+i).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=s-i.length;return a>=0?jt(o,a,$t,0):jt(o,0,$t,-a)}r(Un,"numberOutsideSafeRange");function Fn(t){let e=0;for(;e<t.length;){if(t[e]==='"'){for(e++;e<t.length;)if(t[e]==="\\")e+=2;else if(t[e++]==='"')break;continue}if(t[e]==="-"||/\d/.test(t[e]??"")){let n=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(n){if(Un(n[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=n[0].length;continue}}e++}}r(Fn,"validateJSONNumberTokens");function ct(t,e,n){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`${e} must contain only finite numbers`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`${e} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`);return}if(typeof t!="object")throw new TypeError(`${e} must contain only JSON data`);if(n.has(t))throw new TypeError(`${e} must not contain circular references`);if(n.add(t),Array.isArray(t))t.forEach((i,s)=>ct(i,`${e}[${s}]`,n));else{let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[s,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);ct(o.value,`${e}.${s}`,n)}}n.delete(t)}}r(ct,"assertPlainJSONData");function ce(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");ct(t,"args",new Set);let e=JSON.stringify(t);return Bt(e),e}r(ce,"serializeStructuredArgs");function Bt(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");Fn(t)}r(Bt,"validateSerializedArgs");function de(t,e,n){let i=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Bt(n),i.push([e,n])),`{${i.map(([s,o])=>{let a=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}r(de,"objectWithRawJSONField");var Pe=class{constructor(e){this.client=e}client;static{r(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,ce(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let i={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...n===void 0?{body:i}:{jsonBody:de(i,"args",n)},timeoutMs:e.timeout_ms})}};var Re=class{constructor(e){this.client=e}client;static{r(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,ce(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let i={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...n===void 0?{body:i}:{jsonBody:de(i,"args",n)}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/deploy/cronjobs",{query:{limit:e?.limit,cursor:e?.cursor}})}async get(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.id}`)}async update(e){return this.client._requireAuth(),e.args===void 0?this.updateRequest(e):this.updateRequest(e,ce(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:i,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${i}`,{...n===void 0?{body:s}:{jsonBody:de(s,"args",n)}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/deploy/cronjob/${e.id}`)}async pause(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/pause`)}async resume(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/resume`)}async trigger(e){return this.client._requireAuth(),this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/trigger`)}async listRuns(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs`,{query:{first:e.first,cursor:e.cursor}})}async getRunStatus(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/by-workflow/${encodeURIComponent(e.workflow_run_id)}`)}async getRunLogs(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/${e.run_id}/logs`)}};var ke=class{constructor(e){this.client=e}client;static{r(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var Se=class{constructor(e){this.client=e}client;static{r(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url,confirm_bundled_feed_exposure:e.confirm_bundled_feed_exposure}})}};var ve=class{constructor(e){this.client=e}client;static{r(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let n=we(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=we(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=we(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=we(e.id);if(e.visibility!=="public"&&e.visibility!=="private")throw new Error("visibility must be 'public' or 'private'");return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/visibility`,{body:{visibility:e.visibility}})}};function we(t){if(typeof t=="string"){if(!/^[1-9]\d*$/.test(t))throw new Error("feed id must be a positive integer");return t}if(!Number.isSafeInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}r(we,"requireFeedID");var Gn=`
|
|
1
|
+
"use strict";var AlvaToolkit=(()=>{var be=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var bn=Object.getOwnPropertyNames;var _n=Object.prototype.hasOwnProperty;var r=(t,e)=>be(t,"name",{value:e,configurable:!0});var Pn=(t,e)=>{for(var n in e)be(t,n,{get:e[n],enumerable:!0})},Rn=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bn(e))!_n.call(t,s)&&s!==n&&be(t,s,{get:()=>e[s],enumerable:!(i=gn(e,s))||i.enumerable});return t};var kn=t=>Rn(be({},"__esModule",{value:!0}),t);var Pr={};Pn(Pr,{AlertsResource:()=>V,AlvaClient:()=>rt,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>me,AutomationResource:()=>Q,CliUsageError:()=>Re,ForYouResource:()=>B,MarketsResource:()=>W,PBSV_UPDATE_MESSAGE:()=>vt,SUBSCRIBE_MANAGE_MESSAGE:()=>Nt,SUBSCRIBE_PROPOSE_MESSAGE:()=>qt,SUBSCRIBE_RESULT_MESSAGE:()=>xt,SchedulesResource:()=>Y,StewardResource:()=>H,ThesesResource:()=>J,TradingPairsResource:()=>K,UDF_AUTH_REQUIRED_MESSAGE:()=>It,UDF_CONSENT_REQUEST_MESSAGE:()=>Et,UDF_CONSENT_RESPONSE_MESSAGE:()=>Ct,UdfAuthRequiredError:()=>$,UdfConsentDeniedError:()=>ne,UdfConsentRequiredError:()=>te,UdfConsentTimeoutError:()=>ie,UdfError:()=>R,UdfExecutionError:()=>ce,UdfFunctionDisabledError:()=>oe,UdfFunctionNotFoundError:()=>se,UdfInsufficientCredits:()=>re,UdfPidMismatchError:()=>D,UdfRateLimitedError:()=>ae,UdfTokenExpiredError:()=>Z,UdfTokenInvalidError:()=>ee,UdfTransportError:()=>j,VERSION:()=>_r,getViewerToken:()=>ue,installPlaybookRuntime:()=>dt,mapUdfErrorResponse:()=>ut,playbookIdFromToken:()=>ct,subscribe:()=>Ot,udf:()=>Mt});var R=class extends Error{static{r(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:i={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=i,this.status=s}},$=class extends R{static{r(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},Z=class extends R{static{r(this,"UdfTokenExpiredError")}},ee=class extends R{static{r(this,"UdfTokenInvalidError")}},D=class extends R{static{r(this,"UdfPidMismatchError")}},te=class extends R{static{r(this,"UdfConsentRequiredError")}},ne=class extends R{static{r(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},ie=class extends R{static{r(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},re=class extends R{static{r(this,"UdfInsufficientCredits")}},se=class extends R{static{r(this,"UdfFunctionNotFoundError")}},oe=class extends R{static{r(this,"UdfFunctionDisabledError")}},ae=class extends R{static{r(this,"UdfRateLimitedError")}},ce=class extends R{static{r(this,"UdfExecutionError")}},j=class extends R{static{r(this,"UdfTransportError")}},vt="alva:pbsv:update",Et="alva:udf:consent-request",Ct="alva:udf:consent-response",It="alva:udf:auth-required",qt="alva:subscribe:propose",xt="alva:subscribe:result",Nt="alva:subscribe:manage",Dt="https://api-llm.prd.alva.ai",Ut=300*1e3,X=null,E=null,at=Dt,I=null,w=null,At=!1,_e=new Map,Pe=new Map,wn=r(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Sn=r(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),ct=r(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Sn(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),ue=r(()=>X,"getViewerToken"),M=r(()=>!!ue(),"isAuthenticated"),Tn=r(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),An=r(t=>{let e=new URLSearchParams(t.location.search);X=e.get("_pbsv"),E=e.get("parent_origin"),at=(e.get("api_origin")||Dt).replace(/\/$/,""),I=ct(X),X&&Tn(t)},"parseBootParams"),Ft=r(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),vn=r(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),En=r(t=>{let e=t;return{...e,result:vn(e.result)}},"normalizeInvokeResponse"),Gt=r(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),ut=r((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,s=Gt(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new Z(i,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new ee(i,o);case"PBSV_PID_MISMATCH":return new D(i,o);case"CONSENT_REQUIRED":return new te(i,o);case"INSUFFICIENT_CREDITS":return new re(i,o);case"FUNCTION_NOT_FOUND":return new se(i,o);case"FUNCTION_DISABLED":return new oe(i,o);case"RESOURCE_EXHAUSTED":return new ae(i,o);case"EXECUTION_FAILED":return new ce(i,o);default:return new j(i,o)}},"mapUdfErrorResponse"),Cn=r(t=>{if(!w||!E||t.origin!==E||t.source!==w.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===vt){typeof e.token=="string"&&e.token.length>0&&(X=e.token,I=ct(e.token));return}if(e.type===xt){if(typeof e.request_id!="string")return;let i=Pe.get(e.request_id);if(!i)return;clearTimeout(i.timer),Pe.delete(e.request_id),i.resolve(wn(e.status));return}if(e.type!==Ct||typeof e.request_id!="string")return;let n=_e.get(e.request_id);n&&(clearTimeout(n.timer),_e.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),Lt=r(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),In=r(()=>{if(!I)return null;let t=Number(I);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),qn=r(async(t,e)=>{if(!w||!E)return"denied";let n=E,i=Lt();return new Promise(s=>{let o=setTimeout(()=>{_e.delete(i),s("timeout")},Ut);_e.set(i,{resolve:s,timer:o}),w?.parent.postMessage({type:Et,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),xn=r(async t=>{if(!w||!E)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",n=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!n)return"error";let i=E,s=Lt();return new Promise(o=>{let a=setTimeout(()=>{Pe.delete(s),o("timeout")},Ut);Pe.set(s,{resolve:o,timer:a}),w?.parent.postMessage({type:qt,request_id:s,playbook_id:I,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),Nn=r(()=>{!w||!E||w.parent.postMessage({type:Nt,playbook_id:I},E)},"manageSubscriptions"),Ot={propose:xn,manage:Nn},Dn=r(t=>{!w||!E||w.parent.postMessage({type:It,function_name:t},E)},"requestAuthentication"),lt=r(async(t,e,n=!1)=>{let i=ue();if(!i)throw new $;if(!I)throw new D("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=In();if(!s)throw new D("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${at}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new j("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Ft(o);if(o.ok)return En(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let c=Gt(a),u=typeof c.playbook_id=="string"?c.playbook_id:I,d=typeof c.min_allowance_suggested=="number"?c.min_allowance_suggested:1,m=await qn(u,d);if(m==="granted")return lt(t,e,!0);throw m==="timeout"?new ie:new ne}throw ut(a,o.status)},"call"),Un=r(async()=>{let t=ue();if(!t)throw new $;if(!I)throw new D("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${at}/api/v1/service/functions`);e.searchParams.set("playbook_id",I);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await Ft(n);if(!n.ok)throw ut(i,n.status);let s=i.functions;return Array.isArray(s)?s:[]},"list"),ot=r((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),Fn=r(t=>{if(typeof t!="string")return t;let n=w?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),Gn=r((t,e)=>{if(!w)throw new Error("Playbook runtime is not installed.");let n=Fn(t),i=w.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=M()?s:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),M()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!M()){Dn(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=o,ot(i,"alva:udf-button:loading",{functionName:e.functionName});try{let c=await lt(e.functionName,e.params??{});ot(i,"alva:udf-button:result",{functionName:e.functionName,result:c})}catch(c){ot(i,"alva:udf-button:error",{functionName:e.functionName,error:c})}finally{i.disabled=!1,i.textContent=M()?s:a,M()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),Mt={call:lt,list:Un,getViewerToken:ue,isAuthenticated:M,renderButton:Gn,UdfError:R,UdfAuthRequiredError:$,UdfTokenExpiredError:Z,UdfTokenInvalidError:ee,UdfPidMismatchError:D,UdfConsentRequiredError:te,UdfConsentDeniedError:ne,UdfConsentTimeoutError:ie,UdfInsufficientCredits:re,UdfFunctionNotFoundError:se,UdfFunctionDisabledError:oe,UdfRateLimitedError:ae,UdfExecutionError:ce,UdfTransportError:j},dt=r(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||At)return;w=e,At=!0,An(e),e.addEventListener("message",Cn);let n=e,i=n.alva||{};n.alva={...i,udf:Mt,subscribe:Ot}},"installPlaybookRuntime");var l=class extends Error{static{r(this,"AlvaError")}code;status;details;constructor(e,n,i,s){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=s}},Re=class extends Error{static{r(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function $t(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}r($t,"isArrayBuffer");var jt=1;function Ln(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,s=0,o=0;if(n>=194&&n<=223)i=1,s=128,o=n&31;else if(n>=224&&n<=239)i=2,s=2048,o=n&15;else if(n>=240&&n<=244)i=3,s=65536,o=n&7;else return!1;if(e+i>=t.length)return!1;for(let a=1;a<=i;a+=1){let c=t[e+a];if((c&192)!==128)return!1;o=o<<6|c&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=i+1}return!0}r(Ln,"isValidUtf8");var ke=class{constructor(e){this.client=e}client;static{r(this,"FsResource")}async read(e){let n=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!$t(n)||!Ln(new Uint8Array(n)))return n;let i=new TextDecoder("utf-8").decode(n);try{return JSON.parse(i)}catch{return i}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:jt}:{}}})}async rawWrite(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{query:{path:e.path,mkdir_parents:e.mkdir_parents,...e.append?{flags:jt}:{}},rawBody:e.body})}async stat(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/stat",{query:{path:e.path}})}async readdir(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readdir",{query:{path:e.path,recursive:e.recursive}})}async mkdir(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/mkdir",{body:{path:e.path}})}async remove(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/fs/remove",{query:{path:e.path,recursive:e.recursive}})}async rename(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/rename",{body:{old_path:e.old_path,new_path:e.new_path}})}async copy(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/copy",{body:{src_path:e.src_path,dst_path:e.dst_path}})}async symlink(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/symlink",{body:{target_path:e.target_path,link_path:e.link_path}})}async readlink(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readlink",{query:{path:e.path}})}async chmod(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/chmod",{body:{path:e.path,mode:e.mode}})}async grant(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/grant",{body:{path:e.path,subject:e.subject,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/revoke",{body:{path:e.path,subject:e.subject,permission:e.permission}})}};var Bt="9007199254740991";function Qt(t,e,n,i){let s=t.length+e,o=n.length+i;if(s!==o)return s>o;for(let a=0;a<s;a++){let c=a<t.length?t[a]:"0",u=a<n.length?n[a]:"0";if(c!==u)return c>u}return!1}r(Qt,"scaledIntegerGreater");function On(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,i=e.groups.fraction??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+i).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=s-i.length;return a>=0?Qt(o,a,Bt,0):Qt(o,0,Bt,-a)}r(On,"numberOutsideSafeRange");function Mn(t){let e=0;for(;e<t.length;){if(t[e]==='"'){for(e++;e<t.length;)if(t[e]==="\\")e+=2;else if(t[e++]==='"')break;continue}if(t[e]==="-"||/\d/.test(t[e]??"")){let n=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(n){if(On(n[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=n[0].length;continue}}e++}}r(Mn,"validateJSONNumberTokens");function pt(t,e,n){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`${e} must contain only finite numbers`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`${e} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`);return}if(typeof t!="object")throw new TypeError(`${e} must contain only JSON data`);if(n.has(t))throw new TypeError(`${e} must not contain circular references`);if(n.add(t),Array.isArray(t))t.forEach((i,s)=>pt(i,`${e}[${s}]`,n));else{let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[s,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);pt(o.value,`${e}.${s}`,n)}}n.delete(t)}}r(pt,"assertPlainJSONData");function le(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");pt(t,"args",new Set);let e=JSON.stringify(t);return Vt(e),e}r(le,"serializeStructuredArgs");function Vt(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");Mn(t)}r(Vt,"validateSerializedArgs");function de(t,e,n){let i=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Vt(n),i.push([e,n])),`{${i.map(([s,o])=>{let a=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}r(de,"objectWithRawJSONField");var we=class{constructor(e){this.client=e}client;static{r(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,le(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let i={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...n===void 0?{body:i}:{jsonBody:de(i,"args",n)},timeoutMs:e.timeout_ms})}};var Se=class{constructor(e){this.client=e}client;static{r(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,le(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let i={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...n===void 0?{body:i}:{jsonBody:de(i,"args",n)}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/deploy/cronjobs",{query:{limit:e?.limit,cursor:e?.cursor}})}async get(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.id}`)}async update(e){return this.client._requireAuth(),e.args===void 0?this.updateRequest(e):this.updateRequest(e,le(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:i,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${i}`,{...n===void 0?{body:s}:{jsonBody:de(s,"args",n)}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/deploy/cronjob/${e.id}`)}async pause(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/pause`)}async resume(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/resume`)}async trigger(e){return this.client._requireAuth(),this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/trigger`)}async listRuns(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs`,{query:{first:e.first,cursor:e.cursor}})}async getRunStatus(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/by-workflow/${encodeURIComponent(e.workflow_run_id)}`)}async getRunLogs(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/${e.run_id}/logs`)}};var Te=class{constructor(e){this.client=e}client;static{r(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var Ae=class{constructor(e){this.client=e}client;static{r(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url,confirm_bundled_feed_exposure:e.confirm_bundled_feed_exposure}})}};var Ee=class{constructor(e){this.client=e}client;static{r(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let n=ve(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=ve(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=ve(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=ve(e.id);if(e.visibility!=="public"&&e.visibility!=="private")throw new Error("visibility must be 'public' or 'private'");return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/visibility`,{body:{visibility:e.visibility}})}};function ve(t){if(typeof t=="string"){if(!/^[1-9]\d*$/.test(t))throw new Error("feed id must be a positive integer");return t}if(!Number.isSafeInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}r(ve,"requireFeedID");var $n=`
|
|
2
2
|
query ToolkitForYou($input: FeedEntryConnectionInput) {
|
|
3
3
|
viewer {
|
|
4
4
|
forYou(input: $input) {
|
|
@@ -25,7 +25,42 @@ query ToolkitForYou($input: FeedEntryConnectionInput) {
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
`.trim();function
|
|
28
|
+
`.trim();function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(h,"record");function jn(t){if(!h(t))throw new Error("For You parameters must be an object");let e=t.first===void 0?20:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>50)throw new Error("first must be an integer between 1 and 50");for(let n of["after","newerThan"]){let i=t[n];if(i!==void 0&&(typeof i!="string"||!i.trim()))throw new Error(`${n} must be a non-empty cursor`)}if(t.feedId!==void 0&&!q(t.feedId))throw new Error("feedId must be a positive decimal int64 string")}r(jn,"validateForYouListParams");function q(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}r(q,"isPositiveInt64");function pe(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}r(pe,"invalidResponse");function Bn(t){if(!h(t)||!Array.isArray(t.edges)||!h(t.pageInfo))return pe();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return pe();for(let s of t.edges){if(!h(s)||typeof s.cursor!="string"||!s.cursor.trim()||!h(s.node))return pe();let o=s.node;if(typeof o.id!="string"||!o.id.startsWith("FeedEntry:")||!q(o.id.slice(10))||!h(o.feed)||!q(o.feed.id)||!h(o.major)||typeof o.major.id!="string"||!q(o.major.feedId)||typeof o.title!="string"||typeof o.body!="string")return pe()}let n=t.edges[0],i=t.edges[t.edges.length-1];return e.startCursor!==(n?.cursor??"")||e.endCursor!==(i?.cursor??"")||t.edges.length===0&&e.hasNextPage?pe():t}r(Bn,"connection");var Qn=`
|
|
29
|
+
query ToolkitForYouTheses($input: ThesisRecommendationInput) {
|
|
30
|
+
viewer {
|
|
31
|
+
thesisRecommendations(input: $input) {
|
|
32
|
+
listId pageCursor nextCursor exhausted scanLimited
|
|
33
|
+
pageInfo { startCursor endCursor hasNextPage hasPreviousPage }
|
|
34
|
+
edges {
|
|
35
|
+
cursor
|
|
36
|
+
node {
|
|
37
|
+
itemKey
|
|
38
|
+
publication {
|
|
39
|
+
thesisId playbookId authorVersionId materialVersionId itemKey
|
|
40
|
+
title body publishedAtMs changeKind visibility
|
|
41
|
+
closed archived note closingNote researchPaused
|
|
42
|
+
entityIds categoryIds
|
|
43
|
+
entityStances { entityId stance }
|
|
44
|
+
entities { id ticker name }
|
|
45
|
+
publisher {
|
|
46
|
+
id displayName avatarUrl bio followersCount
|
|
47
|
+
viewerState { following }
|
|
48
|
+
}
|
|
49
|
+
medias { type coverUrl url }
|
|
50
|
+
signalFeed { id }
|
|
51
|
+
snapshotRelease {
|
|
52
|
+
versionId materialVersionId publishedAtMs changeKind
|
|
53
|
+
sourceRefs {
|
|
54
|
+
title sourceKind sourceContentId publicUrl sourceTimeMs locator
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
`.trim();function Vn(t){if(!h(t))throw new Error("Thesis parameters must be an object");let e=t.first===void 0?10:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>10)throw new Error("first must be an integer between 1 and 10");if(t.after!==void 0&&(typeof t.after!="string"||!t.after.trim()))throw new Error("after must be a non-empty cursor")}r(Vn,"validateForYouThesesParams");function Wt(t,e){if(!h(t))throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${e} response`,502);if(t.errors!==void 0){if(!Array.isArray(t.errors))throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${e} response`,502);if(t.errors.length>0){let n=t.errors.flatMap(i=>h(i)&&typeof i.message=="string"?[i.message]:[]);throw new l("GRAPHQL_ERROR",n.join("; ")||"GraphQL request failed",400,{errors:t.errors})}}if(!h(t.data)||!h(t.data.viewer)||t.data.viewer[e]==null)throw new l("GRAPHQL_EMPTY_RESPONSE",`GraphQL response did not include viewer.${e}`,502);return t.data.viewer[e]}r(Wt,"graphqlViewerField");function Ce(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid Thesis recommendation page",502)}r(Ce,"invalidPage");function Yt(t){return Array.isArray(t)&&t.every(q)}r(Yt,"positiveInt64List");function Wn(t){return Array.isArray(t)&&t.every(e=>h(e)&&q(e.entityId)&&typeof e.stance=="string"&&e.stance.trim()!=="")}r(Wn,"stanceList");function Yn(t){return Array.isArray(t)&&t.every(e=>h(e)&&typeof e.id=="string"&&e.id.trim()!==""&&typeof e.ticker=="string"&&typeof e.name=="string")}r(Yn,"entityList");function Hn(t){return Array.isArray(t)&&t.every(e=>h(e)&&typeof e.type=="string"&&e.type.trim()!==""&&typeof e.coverUrl=="string"&&(e.url===null||typeof e.url=="string"))}r(Hn,"mediaList");function Kn(t){return Array.isArray(t)&&t.every(e=>h(e)&&(e.title===null||typeof e.title=="string")&&typeof e.sourceKind=="string"&&typeof e.sourceContentId=="string"&&typeof e.publicUrl=="string"&&zn(e.sourceTimeMs)&&typeof e.locator=="string")}r(Kn,"sourceRefList");function zn(t){return t===null||typeof t=="number"&&Number.isFinite(t)}r(zn,"nullableMs");function Jn(t){return h(t)&&q(t.versionId)&&q(t.materialVersionId)&&typeof t.publishedAtMs=="number"&&Number.isFinite(t.publishedAtMs)&&typeof t.changeKind=="string"&&t.changeKind.trim()!==""&&Kn(t.sourceRefs)}r(Jn,"snapshot");function Xn(t){return h(t)&&typeof t.id=="string"&&t.id.trim()!==""&&typeof t.displayName=="string"&&typeof t.avatarUrl=="string"&&typeof t.bio=="string"&&typeof t.followersCount=="number"&&Number.isInteger(t.followersCount)&&h(t.viewerState)&&(t.viewerState.following===null||typeof t.viewerState.following=="boolean")}r(Xn,"publisher");function Zn(t){if(!h(t))return!1;for(let e of["thesisId","playbookId","authorVersionId","materialVersionId"])if(!q(t[e]))return!1;if(typeof t.itemKey!="string"||!t.itemKey.trim()||typeof t.title!="string"||typeof t.body!="string"||typeof t.publishedAtMs!="number"||!Number.isFinite(t.publishedAtMs)||typeof t.changeKind!="string"||!t.changeKind.trim()||typeof t.visibility!="string"||typeof t.note!="string"||typeof t.closingNote!="string")return!1;for(let e of["closed","archived","researchPaused"])if(typeof t[e]!="boolean")return!1;return!Yt(t.entityIds)||!Yt(t.categoryIds)||!Wn(t.entityStances)||!Yn(t.entities)||!Hn(t.medias)||!Xn(t.publisher)||!Jn(t.snapshotRelease)?!1:t.signalFeed===null||h(t.signalFeed)&&q(t.signalFeed.id)}r(Zn,"publication");function ei(t){if(!h(t)||!Array.isArray(t.edges)||!h(t.pageInfo)||typeof t.listId!="string"||typeof t.pageCursor!="string"||typeof t.exhausted!="boolean"||typeof t.scanLimited!="boolean"||t.nextCursor!==null&&typeof t.nextCursor!="string")return Ce();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean"||e.hasNextPage!==(t.nextCursor!==null))return Ce();for(let i of t.edges)if(!h(i)||typeof i.cursor!="string"||!i.cursor.trim()||!h(i.node)||typeof i.node.itemKey!="string"||!i.node.itemKey.trim()||!Zn(i.node.publication))return Ce();let n=t.edges[0];return e.startCursor!==(n?.cursor??"")?Ce():t}r(ei,"recommendationPage");var B=class{constructor(e){this.client=e}client;static{r(this,"ForYouResource")}async list(e={}){jn(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:$n,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});return Bn(Wt(n,"forYou"))}async theses(e={}){Vn(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:Qn,variables:{input:{first:e.first??10,after:e.after}}}}),i=Wt(n,"thesisRecommendations");return ei(i)}};var ti=`
|
|
29
64
|
query ToolkitAutomationAlertDelivery($automationId: ID!) {
|
|
30
65
|
automation(id: $automationId) {
|
|
31
66
|
alertDelivery {
|
|
@@ -35,7 +70,7 @@ query ToolkitAutomationAlertDelivery($automationId: ID!) {
|
|
|
35
70
|
}
|
|
36
71
|
}
|
|
37
72
|
}
|
|
38
|
-
`.trim()
|
|
73
|
+
`.trim(),ni=`
|
|
39
74
|
mutation ToolkitUpdateAutomationAlertDelivery(
|
|
40
75
|
$input: UpdateAutomationAlertDeliveryInput!
|
|
41
76
|
$includeAlvaChannels: Boolean!
|
|
@@ -50,7 +85,7 @@ mutation ToolkitUpdateAutomationAlertDelivery(
|
|
|
50
85
|
}
|
|
51
86
|
}
|
|
52
87
|
}
|
|
53
|
-
`.trim(),Q=class{constructor(e){this.client=e;this.delivery=new pe(e)}client;static{r(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=jn(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=Ee(e.id);if(!Bn(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(n))}`,{body:{version:e.version,cronjob_id:e.cronjob_id,description:e.description,changelog:e.changelog,agent_type:e.agent_type,trigger:e.trigger}})}stop(e){return this.client.feed.stop(e)}resume(e){return this.client.feed.resume(e)}delete(e){return this.client.feed.delete(e)}publish(e){return this.client.release.feed(e)}},pe=class{constructor(e){this.client=e}client;static{r(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Ee(e.id),s=(await this.graphql(Mn,{automationId:n})).automation?.alertDelivery;if(!s)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=Ee(e.id),i=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!i&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=i?Qn(e.alvaChannelIds??[]):void 0,l=(await this.graphql($n,{input:{automationId:n,...i?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:i,includeEmail:s})).updateAutomationAlertDelivery;if(!l)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return l}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(i.errors&&i.errors.length>0)throw new u("GRAPHQL_ERROR",Vn(i.errors),400,{errors:i.errors});if(!i.data)throw new u("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};function jn(t){if(typeof t=="string")return Ee(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}r(jn,"requireAutomationID");function Ee(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}r(Ee,"requireAutomationIDString");function Bn(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}r(Bn,"hasAutomationUpdate");function Qn(t){let e=[...new Set(t)];for(let n of e)if(!/^(0|[1-9]\d*)$/.test(n))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}r(Qn,"uniqueAlvaChannelIDs");function Vn(t){let e=t.map(n=>n&&typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}r(Vn,"graphQLErrorMessage");var Qt=["public","private","paid"];var Ae=class{constructor(e){this.client=e}client;static{r(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let n={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:n})}async listOwn(e={}){let n={};return e.filter&&(n.filter=e.filter),e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:n})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let n=e.ref.indexOf("/");if(n<=0||n===e.ref.length-1)throw new u("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let i=e.ref.slice(0,n),s=e.ref.slice(n+1),o;for(;;){let a=await this.listByOwner({owner:i,cursor:o,limit:100}),l=a.items.find(c=>c.name===s);if(l)return l;if(!a.has_next||!a.next_cursor)return null;o=a.next_cursor}}throw new u("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let n={};e.cursor&&(n.cursor=e.cursor),e.current&&(n.current=e.current),e.limit!==void 0&&(n.limit=e.limit),e.dir&&(n.dir=e.dir),e.sort&&(n.sort=e.sort),e.keyword&&(n.keyword=e.keyword),e.tags&&e.tags.length>0&&(n.tags=e.tags.join(","));let i=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),s=Wn(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(o=>Yn(o,s)),has_next:i.has_next??!1}}async setVisibility(e){if(!Qt.includes(e.visibility))throw new u("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${Qt.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Wn(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let i=n[1].toLowerCase();return i==="prd"?"https://alva.ai":`https://${i}.alva.ai`}}catch{}return"https://alva.ai"}r(Wn,"webOriginFromApiBase");function Yn(t,e){let n=t.creator?.name??"",i=t.name??"",s=n&&i?`${n}/${i}`:i,o=n&&i?`/u/${n}/playbooks/${i}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:i,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}r(Yn,"toAgentPlaybook");var Ce=class{constructor(e){this.client=e}client;static{r(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let n=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${n}`)}async update(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${n}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${n}`)}};var Ie=class{constructor(e){this.client=e}client;static{r(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let n=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${n}/summary`)}};var Vt=[{skill:"arrays-data-api-crypto-futures-data",file:"binance-perp-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/perp/usdt/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"binance-spot-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/spot/usdt/kline"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"fear-greed-index",method:"GET",path:"/api/v1/crypto/fear-greed-index"},{skill:"arrays-data-api-crypto-futures-data",file:"funding-rate",method:"GET",path:"/api/v1/crypto/funding-rate"},{skill:"arrays-data-api-crypto-futures-data",file:"hyperliquid-perp-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/perp/usdc/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"hyperliquid-spot-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/spot/usdc/kline"},{skill:"arrays-data-api-crypto-futures-data",file:"long-short-ratio",method:"GET",path:"/api/v1/crypto/long-short-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-market-cap",method:"GET",path:"/api/v1/crypto/market-cap"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"market-metrics",method:"GET",path:"/api/v1/crypto/market-metrics"},{skill:"arrays-data-api-crypto-futures-data",file:"open-interest",method:"GET",path:"/api/v1/crypto/open-interest"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics",method:"GET",path:"/api/v1/crypto/screener/metrics"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics-timerange",method:"GET",path:"/api/v1/crypto/screener/metrics/timerange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-detail",method:"GET",path:"/api/v1/crypto/detail"},{skill:"arrays-data-api-etf-fundamentals",file:"country-weightings",method:"GET",path:"/api/v1/etf/country-weightings"},{skill:"arrays-data-api-etf-fundamentals",file:"holdings",method:"GET",path:"/api/v1/etf/holdings"},{skill:"arrays-data-api-etf-fundamentals",file:"info",method:"GET",path:"/api/v1/etf/info"},{skill:"arrays-data-api-etf-fundamentals",file:"sector-weightings",method:"GET",path:"/api/v1/etf/sector-weightings"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-historical",method:"GET",path:"/api/v1/macro/commodity/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-real-time",method:"GET",path:"/api/v1/macro/commodity/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-symbol-list",method:"GET",path:"/api/v1/macro/commodity/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"economic-indicators",method:"GET",path:"/api/v1/macro/economic-indicators"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-historical",method:"GET",path:"/api/v1/macro/forex/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-real-time",method:"GET",path:"/api/v1/macro/forex/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-symbol-list",method:"GET",path:"/api/v1/macro/forex/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-historical",method:"GET",path:"/api/v1/macro/index/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-real-time",method:"GET",path:"/api/v1/macro/index/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"rates",method:"GET",path:"/api/v1/macro/treasury-rates"},{skill:"arrays-data-api-equity-fundamentals",file:"company-balance-sheets",method:"GET",path:"/api/v1/stocks/company/balance-sheets"},{skill:"arrays-data-api-equity-fundamentals",file:"company-cashflow-statements",method:"GET",path:"/api/v1/stocks/company/cashflow-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail",method:"GET",path:"/api/v1/stocks/company/detail"},{skill:"arrays-data-api-equity-fundamentals",file:"company-income-statements",method:"GET",path:"/api/v1/stocks/company/income-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-kpi",method:"GET",path:"/api/v1/stocks/company/kpi"},{skill:"arrays-data-api-equity-events",file:"crowdfunding-offerings",method:"GET",path:"/api/v1/stocks/crowdfunding/offerings"},{skill:"arrays-data-api-equity-events",file:"dividends",method:"GET",path:"/api/v1/stocks/dividends"},{skill:"arrays-data-api-equity-events",file:"earnings-calendar",method:"GET",path:"/api/v1/stocks/earnings-calendar"},{skill:"arrays-data-api-equity-events",file:"equity-offering",method:"GET",path:"/api/v1/stocks/equity-offering"},{skill:"arrays-data-api-stock-metrics",file:"financial-metrics",method:"GET",path:"/api/v1/stocks/financial-metrics"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates",method:"GET",path:"/api/v1/stocks/fiscal-dates"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates-range",method:"GET",path:"/api/v1/stocks/fiscal-dates/range"},{skill:"arrays-data-api-equity-events",file:"ipo-calendar",method:"GET",path:"/api/v1/stocks/ipo-calendar"},{skill:"arrays-data-api-equity-events",file:"ipo-confirmed-calendar",method:"GET",path:"/api/v1/stocks/ipo-confirmed-calendar"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-kline",method:"GET",path:"/api/v1/stocks/kline"},{skill:"arrays-data-api-stock-metrics",file:"market-metrics",method:"GET",path:"/api/v1/stocks/market-metrics"},{skill:"arrays-data-api-equity-events",file:"mergers-acquisitions",method:"GET",path:"/api/v1/stocks/mergers-acquisitions"},{skill:"arrays-data-api-equity-fundamentals",file:"outstanding-shares",method:"GET",path:"/api/v1/stocks/outstanding-shares"},{skill:"arrays-data-api-stock-metrics",file:"ratings",method:"GET",path:"/api/v1/stocks/ratings"},{skill:"arrays-data-api-stock-screener",file:"basic-info-screener",method:"GET",path:"/api/v1/stocks/screener/basic-info/{sub}"},{skill:"arrays-data-api-stock-screener",file:"event-screener",method:"GET",path:"/api/v1/stocks/screener/events"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics",method:"GET",path:"/api/v1/stocks/screener/financial-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/financial-metrics/timerange"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics",method:"GET",path:"/api/v1/stocks/screener/technical-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/technical-metrics/timerange"},{skill:"arrays-data-api-equity-events",file:"sec-earnings-release",method:"GET",path:"/api/v1/stocks/sec-earnings-release"},{skill:"arrays-data-api-equity-fundamentals",file:"shares-float",method:"GET",path:"/api/v1/stocks/shares-float"},{skill:"arrays-data-api-equity-events",file:"splits",method:"GET",path:"/api/v1/stocks/splits"},{skill:"arrays-data-api-crypto-exchange-flow",file:"exchange-flows",method:"GET",path:"/api/v1/crypto/exchange-flows"},{skill:"arrays-data-api-company-crypto-holdings",file:"crypto-holdings",method:"GET",path:"/api/v1/crypto/holdings"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-inflow-cdd",method:"GET",path:"/api/v1/crypto/metrics/inflow-cdd"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-leverage-ratio",method:"GET",path:"/api/v1/crypto/metrics/leverage-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-miner-to-exchange",method:"GET",path:"/api/v1/crypto/metrics/miner-to-exchange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-mvrv",method:"GET",path:"/api/v1/crypto/metrics/mvrv"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-nupl",method:"GET",path:"/api/v1/crypto/metrics/nupl"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-puell-multiple",method:"GET",path:"/api/v1/crypto/metrics/puell-multiple"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-realized-price",method:"GET",path:"/api/v1/crypto/metrics/realized-price"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-sopr",method:"GET",path:"/api/v1/crypto/metrics/sopr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-ssr",method:"GET",path:"/api/v1/crypto/metrics/ssr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-whale-ratio",method:"GET",path:"/api/v1/crypto/metrics/whale-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-supply",method:"GET",path:"/api/v1/crypto/supply"},{skill:"arrays-data-api-crypto-futures-data",file:"taker-buy-sell-volume",method:"GET",path:"/api/v1/crypto/taker-buy-sell-volume"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"unlock-events",method:"GET",path:"/api/v1/crypto/unlock-events"},{skill:"arrays-data-api-etf-fundamentals",file:"flow",method:"GET",path:"/api/v1/etf/flow"},{skill:"arrays-data-api-options",file:"contracts",method:"GET",path:"/api/v1/options/contracts"},{skill:"arrays-data-api-options",file:"kline",method:"GET",path:"/api/v1/options/kline"},{skill:"arrays-data-api-options",file:"greeks",method:"GET",path:"/api/v1/options/greeks"},{skill:"arrays-data-api-options",file:"chain",method:"GET",path:"/api/v1/options/chain"},{skill:"arrays-data-api-equity-fundamentals",file:"company-executives",method:"GET",path:"/api/v1/stocks/company/executives"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-consensus",method:"GET",path:"/api/v1/stocks/company/price-target-consensus"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-news",method:"GET",path:"/api/v1/stocks/company/price-target-news"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-summary",method:"GET",path:"/api/v1/stocks/company/price-target-summary"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"congress-recent-trades",method:"GET",path:"/api/v1/stocks/congress/recent-trades"},{skill:"arrays-data-api-stock-metrics",file:"darkpool",method:"GET",path:"/api/v1/stocks/darkpool"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"estimates-guidance",method:"GET",path:"/api/v1/stocks/estimates-guidance"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"insider-transactions",method:"GET",path:"/api/v1/stocks/insider/transactions"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"institution-holder",method:"GET",path:"/api/v1/stocks/institution-holder"},{skill:"arrays-data-api-polymarket",file:"activity",method:"GET",path:"polymarket:/activity"},{skill:"arrays-data-api-polymarket",file:"book",method:"GET",path:"polymarket:/book"},{skill:"arrays-data-api-polymarket",file:"closed-positions",method:"GET",path:"polymarket:/closed-positions"},{skill:"arrays-data-api-polymarket",file:"events",method:"GET",path:"polymarket:/events"},{skill:"arrays-data-api-polymarket",file:"holders",method:"GET",path:"polymarket:/holders"},{skill:"arrays-data-api-polymarket",file:"markets",method:"GET",path:"polymarket:/markets"},{skill:"arrays-data-api-polymarket",file:"midpoint",method:"GET",path:"polymarket:/midpoint"},{skill:"arrays-data-api-polymarket",file:"oi",method:"GET",path:"polymarket:/oi"},{skill:"arrays-data-api-polymarket",file:"positions",method:"GET",path:"polymarket:/positions"},{skill:"arrays-data-api-polymarket",file:"price",method:"GET",path:"polymarket:/price"},{skill:"arrays-data-api-polymarket",file:"prices-history",method:"GET",path:"polymarket:/prices-history"},{skill:"arrays-data-api-polymarket",file:"public-search",method:"GET",path:"polymarket:/public-search"},{skill:"arrays-data-api-polymarket",file:"series",method:"GET",path:"polymarket:/series"},{skill:"arrays-data-api-polymarket",file:"sports",method:"GET",path:"polymarket:/sports"},{skill:"arrays-data-api-polymarket",file:"spread",method:"GET",path:"polymarket:/spread"},{skill:"arrays-data-api-polymarket",file:"tags",method:"GET",path:"polymarket:/tags"},{skill:"arrays-data-api-polymarket",file:"trades",method:"GET",path:"polymarket:/trades"},{skill:"arrays-data-api-polymarket",file:"value",method:"GET",path:"polymarket:/value"},{skill:"arrays-data-api-equity-events",file:"earnings-transcript",method:"GET",path:"/api/v1/stocks/earnings-transcript"},{skill:"arrays-data-api-news",file:"market-news",method:"GET",path:"/api/v1/stocks/market-news"},{skill:"arrays-data-api-social-feeds",file:"x-by-handle",method:"GET",path:"/api/v1/social-feeds/x/by-handle"},{skill:"arrays-data-api-social-feeds",file:"x-by-url",method:"GET",path:"/api/v1/social-feeds/x/by-url"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handle",method:"GET",path:"/api/v1/social-feeds/x/entities/handle/{twitter_handle}"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handles",method:"GET",path:"/api/v1/social-feeds/x/entities/handles"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail-non-us",method:"GET",path:"/api/v1/stocks/non-us/company/detail"},{skill:"arrays-data-api-social-feeds",file:"x-search",method:"GET",path:"/api/v1/social-feeds/x/search"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-non-us-kline",method:"GET",path:"/api/v1/stocks/non-us/kline"},{skill:"arrays-data-api-semiconductor-price",file:"dram-spot-price",method:"GET",path:"/api/v1/other/semiconductor/dram-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"dram-contract-price",method:"GET",path:"/api/v1/other/semiconductor/dram-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-spot-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-contract-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"memory-card-price",method:"GET",path:"/api/v1/other/semiconductor/memory-card-price"},{skill:"arrays-data-api-semiconductor-price",file:"dxi-index",method:"GET",path:"/api/v1/other/semiconductor/dxi-index"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"short-interest",method:"GET",path:"/api/v1/stocks/short-interest"},{skill:"arrays-data-api-social-feeds",file:"x-handles",method:"POST",path:"/api/v1/social-feeds/x/handles"}];function Wt(t,e){return Vt.find(n=>n.skill===t&&n.file===e)}r(Wt,"getSkillEndpointMetadata");function dt(t){return Vt.filter(e=>e.skill===t)}r(dt,"listSkillEndpointMetadata");var qe=class{constructor(e){this.client=e}client;static{r(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...Yt(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!s)throw new Error(`empty skills summary response for "${e.name}"`);let o=dt(e.name);return{...s,...Yt(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!s)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=Wt(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function Yt(t){let e=dt(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}r(Yt,"metadataSummaryForSkill");function Ht(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}r(Ht,"normalizePlaybookSkillSummary");function zt(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new u("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}r(zt,"parsePlaybookSkillId");var xe=class{constructor(e){this.client=e}client;static{r(this,"PlaybookSkillsResource")}async list(e){let n={};return e?.tag&&(n.tag=e.tag),e?.username&&(n.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:n})).data??[]).map(Ht)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=zt(e),s=encodeURIComponent(n),o=encodeURIComponent(i),l=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!l)throw new u("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...Ht(l),files:l.files??[]}}async file(e,n){let{username:i,name:s}=zt(e),o=encodeURIComponent(i),a=encodeURIComponent(s),l=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${a}/files/${l}`)).data?.[0];if(!d)throw new u("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var De=class{constructor(e){this.client=e}client;static{r(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var Ne=class{constructor(e){this.client=e}client;static{r(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var Ue=class{constructor(e){this.client=e}client;static{r(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var Fe=class{constructor(e){this.client=e}client;static{r(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var Ge=class{constructor(e){this.client=e}client;static{r(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var Le=class{constructor(e){this.client=e}client;static{r(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var Oe=class{constructor(e){this.client=e}client;static{r(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var Me=class{constructor(e){this.client=e}client;static{r(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let n=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",n,{query:Hn(e)})}};function Hn(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}r(Hn,"buildQuery");var $e=class{constructor(e){this.client=e}client;static{r(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var je=class{constructor(e){this.client=e}client;static{r(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",n)}async unfollowPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async subscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",n):this.client._request("POST",n,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async list(e={}){this.client._requireAuth();let n={};return e.first!==void 0&&e.first>0&&(n.first=String(e.first)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:n})}async follows(e={}){this.client._requireAuth();let n={};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:n})}async subscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/subscribe-batch",{body:{feed_ids:e.feedIds,channel_id:e.channelId}})}async unsubscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/unsubscribe-batch",{body:{feed_ids:e.feedIds}})}};var V=class{constructor(e){this.client=e}client;static{r(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var Be=class{constructor(e){this.client=e}client;static{r(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:Jt(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:Jt(e)})}async getGroupChatHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-history",{query:{channel:e.channel,remote_chat_id:e.remote_chat_id,from_micros:String(e.from_micros),to_micros:String(e.to_micros)}})}};function Jt(t){return`{"session_id":${Kt(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${Kt(t.target_id)}}`}r(Jt,"mutationBody");function Kt(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new u("INVALID_ARGUMENT","channel group subscription ids must be positive safe integers; pass large int64 ids as strings",0);return String(t)}if(!/^[1-9]\d*$/.test(t))throw new u("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}r(Kt,"idLiteral");var Qe=class{constructor(e){this.client=e}client;static{r(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var Ve=class{constructor(e){this.client=e}client;static{r(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/invoke",{body:{playbook_id:e.playbook_id,function_name:e.function_name,parameters_json:JSON.stringify(e.parameters??{})}});return{...n,result:Jn(n.result)}}async getAllowance(e){this.client._requireAuth();let n=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return pt(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>pt(n)).filter(n=>n!==null)}}async createAllowance(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:zn(n.allowance)}}async revokeAllowance(e){return this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}}),{ok:!0}}};function pt(t){if(!t)return null;let e={id:t.id??"",consumer_uid:t.consumer_uid??t.consumerUid??"",playbook_id:t.playbook_id??t.playbookId??"",amount:t.amount??0,used:t.used??0,remaining:t.remaining??0},n=Xt(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=Xt(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),i!==void 0&&(e.updated_at_ms=i),e}r(pt,"normalizeAllowance");function zn(t){let e=pt(t);if(!e)throw new Error("allowance response missing allowance");return e}r(zn,"requireAllowance");function Xt(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}if(typeof t!="object")return;let e=t,n=typeof e.seconds=="number"?e.seconds:typeof e.seconds=="string"?Number(e.seconds):void 0,i=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(n===void 0||!Number.isFinite(n)))return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}r(Xt,"timestampMs");function Jn(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}r(Jn,"parseResultPayload");var Kn=`
|
|
88
|
+
`.trim(),Q=class{constructor(e){this.client=e;this.delivery=new me(e)}client;static{r(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=ii(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=Ie(e.id);if(!ri(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(n))}`,{body:{version:e.version,cronjob_id:e.cronjob_id,description:e.description,changelog:e.changelog,agent_type:e.agent_type,trigger:e.trigger}})}stop(e){return this.client.feed.stop(e)}resume(e){return this.client.feed.resume(e)}delete(e){return this.client.feed.delete(e)}publish(e){return this.client.release.feed(e)}},me=class{constructor(e){this.client=e}client;static{r(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Ie(e.id),s=(await this.graphql(ti,{automationId:n})).automation?.alertDelivery;if(!s)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=Ie(e.id),i=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!i&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=i?si(e.alvaChannelIds??[]):void 0,c=(await this.graphql(ni,{input:{automationId:n,...i?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:i,includeEmail:s})).updateAutomationAlertDelivery;if(!c)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return c}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",oi(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};function ii(t){if(typeof t=="string")return Ie(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}r(ii,"requireAutomationID");function Ie(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}r(Ie,"requireAutomationIDString");function ri(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}r(ri,"hasAutomationUpdate");function si(t){let e=[...new Set(t)];for(let n of e)if(!/^(0|[1-9]\d*)$/.test(n))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}r(si,"uniqueAlvaChannelIDs");function oi(t){let e=t.map(n=>n&&typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}r(oi,"graphQLErrorMessage");var Ht=["public","private","paid"];var qe=class{constructor(e){this.client=e}client;static{r(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let n={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:n})}async listOwn(e={}){let n={};return e.filter&&(n.filter=e.filter),e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:n})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let n=e.ref.indexOf("/");if(n<=0||n===e.ref.length-1)throw new l("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let i=e.ref.slice(0,n),s=e.ref.slice(n+1),o;for(;;){let a=await this.listByOwner({owner:i,cursor:o,limit:100}),c=a.items.find(u=>u.name===s);if(c)return c;if(!a.has_next||!a.next_cursor)return null;o=a.next_cursor}}throw new l("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let n={};e.cursor&&(n.cursor=e.cursor),e.current&&(n.current=e.current),e.limit!==void 0&&(n.limit=e.limit),e.dir&&(n.dir=e.dir),e.sort&&(n.sort=e.sort),e.keyword&&(n.keyword=e.keyword),e.tags&&e.tags.length>0&&(n.tags=e.tags.join(","));let i=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),s=ai(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(o=>ci(o,s)),has_next:i.has_next??!1}}async setVisibility(e){if(!Ht.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${Ht.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function ai(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let i=n[1].toLowerCase();return i==="prd"?"https://alva.ai":`https://${i}.alva.ai`}}catch{}return"https://alva.ai"}r(ai,"webOriginFromApiBase");function ci(t,e){let n=t.creator?.name??"",i=t.name??"",s=n&&i?`${n}/${i}`:i,o=n&&i?`/u/${n}/playbooks/${i}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:i,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}r(ci,"toAgentPlaybook");var xe=class{constructor(e){this.client=e}client;static{r(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let n=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${n}`)}async update(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${n}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${n}`)}};var Ne=class{constructor(e){this.client=e}client;static{r(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let n=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${n}/summary`)}};var Kt=[{skill:"arrays-data-api-crypto-futures-data",file:"binance-perp-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/perp/usdt/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"binance-spot-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/spot/usdt/kline"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"fear-greed-index",method:"GET",path:"/api/v1/crypto/fear-greed-index"},{skill:"arrays-data-api-crypto-futures-data",file:"funding-rate",method:"GET",path:"/api/v1/crypto/funding-rate"},{skill:"arrays-data-api-crypto-futures-data",file:"hyperliquid-perp-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/perp/usdc/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"hyperliquid-spot-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/spot/usdc/kline"},{skill:"arrays-data-api-crypto-futures-data",file:"long-short-ratio",method:"GET",path:"/api/v1/crypto/long-short-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-market-cap",method:"GET",path:"/api/v1/crypto/market-cap"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"market-metrics",method:"GET",path:"/api/v1/crypto/market-metrics"},{skill:"arrays-data-api-crypto-futures-data",file:"open-interest",method:"GET",path:"/api/v1/crypto/open-interest"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics",method:"GET",path:"/api/v1/crypto/screener/metrics"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics-timerange",method:"GET",path:"/api/v1/crypto/screener/metrics/timerange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-detail",method:"GET",path:"/api/v1/crypto/detail"},{skill:"arrays-data-api-etf-fundamentals",file:"country-weightings",method:"GET",path:"/api/v1/etf/country-weightings"},{skill:"arrays-data-api-etf-fundamentals",file:"holdings",method:"GET",path:"/api/v1/etf/holdings"},{skill:"arrays-data-api-etf-fundamentals",file:"info",method:"GET",path:"/api/v1/etf/info"},{skill:"arrays-data-api-etf-fundamentals",file:"sector-weightings",method:"GET",path:"/api/v1/etf/sector-weightings"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-historical",method:"GET",path:"/api/v1/macro/commodity/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-real-time",method:"GET",path:"/api/v1/macro/commodity/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-symbol-list",method:"GET",path:"/api/v1/macro/commodity/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"economic-indicators",method:"GET",path:"/api/v1/macro/economic-indicators"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-historical",method:"GET",path:"/api/v1/macro/forex/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-real-time",method:"GET",path:"/api/v1/macro/forex/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-symbol-list",method:"GET",path:"/api/v1/macro/forex/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-historical",method:"GET",path:"/api/v1/macro/index/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-real-time",method:"GET",path:"/api/v1/macro/index/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"rates",method:"GET",path:"/api/v1/macro/treasury-rates"},{skill:"arrays-data-api-equity-fundamentals",file:"company-balance-sheets",method:"GET",path:"/api/v1/stocks/company/balance-sheets"},{skill:"arrays-data-api-equity-fundamentals",file:"company-cashflow-statements",method:"GET",path:"/api/v1/stocks/company/cashflow-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail",method:"GET",path:"/api/v1/stocks/company/detail"},{skill:"arrays-data-api-equity-fundamentals",file:"company-income-statements",method:"GET",path:"/api/v1/stocks/company/income-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-kpi",method:"GET",path:"/api/v1/stocks/company/kpi"},{skill:"arrays-data-api-equity-events",file:"crowdfunding-offerings",method:"GET",path:"/api/v1/stocks/crowdfunding/offerings"},{skill:"arrays-data-api-equity-events",file:"dividends",method:"GET",path:"/api/v1/stocks/dividends"},{skill:"arrays-data-api-equity-events",file:"earnings-calendar",method:"GET",path:"/api/v1/stocks/earnings-calendar"},{skill:"arrays-data-api-equity-events",file:"equity-offering",method:"GET",path:"/api/v1/stocks/equity-offering"},{skill:"arrays-data-api-stock-metrics",file:"financial-metrics",method:"GET",path:"/api/v1/stocks/financial-metrics"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates",method:"GET",path:"/api/v1/stocks/fiscal-dates"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates-range",method:"GET",path:"/api/v1/stocks/fiscal-dates/range"},{skill:"arrays-data-api-equity-events",file:"ipo-calendar",method:"GET",path:"/api/v1/stocks/ipo-calendar"},{skill:"arrays-data-api-equity-events",file:"ipo-confirmed-calendar",method:"GET",path:"/api/v1/stocks/ipo-confirmed-calendar"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-kline",method:"GET",path:"/api/v1/stocks/kline"},{skill:"arrays-data-api-stock-metrics",file:"market-metrics",method:"GET",path:"/api/v1/stocks/market-metrics"},{skill:"arrays-data-api-equity-events",file:"mergers-acquisitions",method:"GET",path:"/api/v1/stocks/mergers-acquisitions"},{skill:"arrays-data-api-equity-fundamentals",file:"outstanding-shares",method:"GET",path:"/api/v1/stocks/outstanding-shares"},{skill:"arrays-data-api-stock-metrics",file:"ratings",method:"GET",path:"/api/v1/stocks/ratings"},{skill:"arrays-data-api-stock-screener",file:"basic-info-screener",method:"GET",path:"/api/v1/stocks/screener/basic-info/{sub}"},{skill:"arrays-data-api-stock-screener",file:"event-screener",method:"GET",path:"/api/v1/stocks/screener/events"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics",method:"GET",path:"/api/v1/stocks/screener/financial-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/financial-metrics/timerange"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics",method:"GET",path:"/api/v1/stocks/screener/technical-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/technical-metrics/timerange"},{skill:"arrays-data-api-equity-events",file:"sec-earnings-release",method:"GET",path:"/api/v1/stocks/sec-earnings-release"},{skill:"arrays-data-api-equity-fundamentals",file:"shares-float",method:"GET",path:"/api/v1/stocks/shares-float"},{skill:"arrays-data-api-equity-events",file:"splits",method:"GET",path:"/api/v1/stocks/splits"},{skill:"arrays-data-api-crypto-exchange-flow",file:"exchange-flows",method:"GET",path:"/api/v1/crypto/exchange-flows"},{skill:"arrays-data-api-company-crypto-holdings",file:"crypto-holdings",method:"GET",path:"/api/v1/crypto/holdings"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-inflow-cdd",method:"GET",path:"/api/v1/crypto/metrics/inflow-cdd"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-leverage-ratio",method:"GET",path:"/api/v1/crypto/metrics/leverage-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-miner-to-exchange",method:"GET",path:"/api/v1/crypto/metrics/miner-to-exchange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-mvrv",method:"GET",path:"/api/v1/crypto/metrics/mvrv"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-nupl",method:"GET",path:"/api/v1/crypto/metrics/nupl"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-puell-multiple",method:"GET",path:"/api/v1/crypto/metrics/puell-multiple"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-realized-price",method:"GET",path:"/api/v1/crypto/metrics/realized-price"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-sopr",method:"GET",path:"/api/v1/crypto/metrics/sopr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-ssr",method:"GET",path:"/api/v1/crypto/metrics/ssr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-whale-ratio",method:"GET",path:"/api/v1/crypto/metrics/whale-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-supply",method:"GET",path:"/api/v1/crypto/supply"},{skill:"arrays-data-api-crypto-futures-data",file:"taker-buy-sell-volume",method:"GET",path:"/api/v1/crypto/taker-buy-sell-volume"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"unlock-events",method:"GET",path:"/api/v1/crypto/unlock-events"},{skill:"arrays-data-api-etf-fundamentals",file:"flow",method:"GET",path:"/api/v1/etf/flow"},{skill:"arrays-data-api-options",file:"contracts",method:"GET",path:"/api/v1/options/contracts"},{skill:"arrays-data-api-options",file:"kline",method:"GET",path:"/api/v1/options/kline"},{skill:"arrays-data-api-options",file:"greeks",method:"GET",path:"/api/v1/options/greeks"},{skill:"arrays-data-api-options",file:"chain",method:"GET",path:"/api/v1/options/chain"},{skill:"arrays-data-api-equity-fundamentals",file:"company-executives",method:"GET",path:"/api/v1/stocks/company/executives"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-consensus",method:"GET",path:"/api/v1/stocks/company/price-target-consensus"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-news",method:"GET",path:"/api/v1/stocks/company/price-target-news"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-summary",method:"GET",path:"/api/v1/stocks/company/price-target-summary"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"congress-recent-trades",method:"GET",path:"/api/v1/stocks/congress/recent-trades"},{skill:"arrays-data-api-stock-metrics",file:"darkpool",method:"GET",path:"/api/v1/stocks/darkpool"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"estimates-guidance",method:"GET",path:"/api/v1/stocks/estimates-guidance"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"insider-transactions",method:"GET",path:"/api/v1/stocks/insider/transactions"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"institution-holder",method:"GET",path:"/api/v1/stocks/institution-holder"},{skill:"arrays-data-api-polymarket",file:"activity",method:"GET",path:"polymarket:/activity"},{skill:"arrays-data-api-polymarket",file:"book",method:"GET",path:"polymarket:/book"},{skill:"arrays-data-api-polymarket",file:"closed-positions",method:"GET",path:"polymarket:/closed-positions"},{skill:"arrays-data-api-polymarket",file:"events",method:"GET",path:"polymarket:/events"},{skill:"arrays-data-api-polymarket",file:"holders",method:"GET",path:"polymarket:/holders"},{skill:"arrays-data-api-polymarket",file:"markets",method:"GET",path:"polymarket:/markets"},{skill:"arrays-data-api-polymarket",file:"midpoint",method:"GET",path:"polymarket:/midpoint"},{skill:"arrays-data-api-polymarket",file:"oi",method:"GET",path:"polymarket:/oi"},{skill:"arrays-data-api-polymarket",file:"positions",method:"GET",path:"polymarket:/positions"},{skill:"arrays-data-api-polymarket",file:"price",method:"GET",path:"polymarket:/price"},{skill:"arrays-data-api-polymarket",file:"prices-history",method:"GET",path:"polymarket:/prices-history"},{skill:"arrays-data-api-polymarket",file:"public-search",method:"GET",path:"polymarket:/public-search"},{skill:"arrays-data-api-polymarket",file:"series",method:"GET",path:"polymarket:/series"},{skill:"arrays-data-api-polymarket",file:"sports",method:"GET",path:"polymarket:/sports"},{skill:"arrays-data-api-polymarket",file:"spread",method:"GET",path:"polymarket:/spread"},{skill:"arrays-data-api-polymarket",file:"tags",method:"GET",path:"polymarket:/tags"},{skill:"arrays-data-api-polymarket",file:"trades",method:"GET",path:"polymarket:/trades"},{skill:"arrays-data-api-polymarket",file:"value",method:"GET",path:"polymarket:/value"},{skill:"arrays-data-api-equity-events",file:"earnings-transcript",method:"GET",path:"/api/v1/stocks/earnings-transcript"},{skill:"arrays-data-api-news",file:"market-news",method:"GET",path:"/api/v1/stocks/market-news"},{skill:"arrays-data-api-social-feeds",file:"x-by-handle",method:"GET",path:"/api/v1/social-feeds/x/by-handle"},{skill:"arrays-data-api-social-feeds",file:"x-by-url",method:"GET",path:"/api/v1/social-feeds/x/by-url"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handle",method:"GET",path:"/api/v1/social-feeds/x/entities/handle/{twitter_handle}"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handles",method:"GET",path:"/api/v1/social-feeds/x/entities/handles"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail-non-us",method:"GET",path:"/api/v1/stocks/non-us/company/detail"},{skill:"arrays-data-api-social-feeds",file:"x-search",method:"GET",path:"/api/v1/social-feeds/x/search"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-non-us-kline",method:"GET",path:"/api/v1/stocks/non-us/kline"},{skill:"arrays-data-api-semiconductor-price",file:"dram-spot-price",method:"GET",path:"/api/v1/other/semiconductor/dram-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"dram-contract-price",method:"GET",path:"/api/v1/other/semiconductor/dram-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-spot-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-contract-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"memory-card-price",method:"GET",path:"/api/v1/other/semiconductor/memory-card-price"},{skill:"arrays-data-api-semiconductor-price",file:"dxi-index",method:"GET",path:"/api/v1/other/semiconductor/dxi-index"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"short-interest",method:"GET",path:"/api/v1/stocks/short-interest"},{skill:"arrays-data-api-social-feeds",file:"x-handles",method:"POST",path:"/api/v1/social-feeds/x/handles"}];function zt(t,e){return Kt.find(n=>n.skill===t&&n.file===e)}r(zt,"getSkillEndpointMetadata");function mt(t){return Kt.filter(e=>e.skill===t)}r(mt,"listSkillEndpointMetadata");var De=class{constructor(e){this.client=e}client;static{r(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...Jt(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!s)throw new Error(`empty skills summary response for "${e.name}"`);let o=mt(e.name);return{...s,...Jt(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!s)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=zt(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function Jt(t){let e=mt(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}r(Jt,"metadataSummaryForSkill");function Xt(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}r(Xt,"normalizePlaybookSkillSummary");function Zt(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new l("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}r(Zt,"parsePlaybookSkillId");var Ue=class{constructor(e){this.client=e}client;static{r(this,"PlaybookSkillsResource")}async list(e){let n={};return e?.tag&&(n.tag=e.tag),e?.username&&(n.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:n})).data??[]).map(Xt)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=Zt(e),s=encodeURIComponent(n),o=encodeURIComponent(i),c=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!c)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...Xt(c),files:c.files??[]}}async file(e,n){let{username:i,name:s}=Zt(e),o=encodeURIComponent(i),a=encodeURIComponent(s),c=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${a}/files/${c}`)).data?.[0];if(!d)throw new l("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var Fe=class{constructor(e){this.client=e}client;static{r(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var Ge=class{constructor(e){this.client=e}client;static{r(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var Le=class{constructor(e){this.client=e}client;static{r(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var Oe=class{constructor(e){this.client=e}client;static{r(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var Me=class{constructor(e){this.client=e}client;static{r(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var $e=class{constructor(e){this.client=e}client;static{r(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var je=class{constructor(e){this.client=e}client;static{r(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var Be=class{constructor(e){this.client=e}client;static{r(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let n=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",n,{query:ui(e)})}};function ui(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}r(ui,"buildQuery");var Qe=class{constructor(e){this.client=e}client;static{r(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var Ve=class{constructor(e){this.client=e}client;static{r(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",n)}async unfollowPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async subscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",n):this.client._request("POST",n,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async list(e={}){this.client._requireAuth();let n={};return e.first!==void 0&&e.first>0&&(n.first=String(e.first)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:n})}async follows(e={}){this.client._requireAuth();let n={};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:n})}async subscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/subscribe-batch",{body:{feed_ids:e.feedIds,channel_id:e.channelId}})}async unsubscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/unsubscribe-batch",{body:{feed_ids:e.feedIds}})}};var V=class{constructor(e){this.client=e}client;static{r(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var We=class{constructor(e){this.client=e}client;static{r(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:en(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:en(e)})}async getGroupChatHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-history",{query:{channel:e.channel,remote_chat_id:e.remote_chat_id,from_micros:String(e.from_micros),to_micros:String(e.to_micros)}})}};function en(t){return`{"session_id":${tn(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${tn(t.target_id)}}`}r(en,"mutationBody");function tn(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive safe integers; pass large int64 ids as strings",0);return String(t)}if(!/^[1-9]\d*$/.test(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}r(tn,"idLiteral");var Ye=class{constructor(e){this.client=e}client;static{r(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var He=class{constructor(e){this.client=e}client;static{r(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/invoke",{body:{playbook_id:e.playbook_id,function_name:e.function_name,parameters_json:JSON.stringify(e.parameters??{})}});return{...n,result:di(n.result)}}async getAllowance(e){this.client._requireAuth();let n=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return ht(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>ht(n)).filter(n=>n!==null)}}async createAllowance(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:li(n.allowance)}}async revokeAllowance(e){return this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}}),{ok:!0}}};function ht(t){if(!t)return null;let e={id:t.id??"",consumer_uid:t.consumer_uid??t.consumerUid??"",playbook_id:t.playbook_id??t.playbookId??"",amount:t.amount??0,used:t.used??0,remaining:t.remaining??0},n=nn(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=nn(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),i!==void 0&&(e.updated_at_ms=i),e}r(ht,"normalizeAllowance");function li(t){let e=ht(t);if(!e)throw new Error("allowance response missing allowance");return e}r(li,"requireAllowance");function nn(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}if(typeof t!="object")return;let e=t,n=typeof e.seconds=="number"?e.seconds:typeof e.seconds=="string"?Number(e.seconds):void 0,i=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(n===void 0||!Number.isFinite(n)))return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}r(nn,"timestampMs");function di(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}r(di,"parseResultPayload");var pi=`
|
|
54
89
|
query ToolkitCreditWallet {
|
|
55
90
|
viewer {
|
|
56
91
|
creditWallet {
|
|
@@ -60,7 +95,7 @@ query ToolkitCreditWallet {
|
|
|
60
95
|
}
|
|
61
96
|
}
|
|
62
97
|
}
|
|
63
|
-
`.trim(),
|
|
98
|
+
`.trim(),mi=`
|
|
64
99
|
query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
|
|
65
100
|
viewer {
|
|
66
101
|
creditWallet {
|
|
@@ -92,7 +127,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
|
|
|
92
127
|
}
|
|
93
128
|
}
|
|
94
129
|
}
|
|
95
|
-
`.trim();function
|
|
130
|
+
`.trim();function hi(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}r(hi,"graphQLErrorMessage");var Ke=class{constructor(e){this.client=e}client;static{r(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(pi)).viewer?.creditWallet;if(!n)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet",502);return n}async items(e){this.client._requireAuth();let i=(await this.graphql(mi,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return i}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",hi(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var fi=["Q1","Q2","Q3","Q4"],yi=["latest-completed","next-confirmed"],gi=`
|
|
96
131
|
query ToolkitCompanyNarrative($ticker: String!) {
|
|
97
132
|
market {
|
|
98
133
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -118,7 +153,7 @@ query ToolkitCompanyNarrative($ticker: String!) {
|
|
|
118
153
|
}
|
|
119
154
|
}
|
|
120
155
|
}
|
|
121
|
-
`.trim(),
|
|
156
|
+
`.trim(),bi=`
|
|
122
157
|
query ToolkitCompanyEarningsCatalog($ticker: String!) {
|
|
123
158
|
market {
|
|
124
159
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -149,7 +184,7 @@ query ToolkitCompanyEarningsCatalog($ticker: String!) {
|
|
|
149
184
|
}
|
|
150
185
|
}
|
|
151
186
|
}
|
|
152
|
-
`.trim(),
|
|
187
|
+
`.trim(),_i=`
|
|
153
188
|
query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
154
189
|
market {
|
|
155
190
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -219,7 +254,7 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
219
254
|
}
|
|
220
255
|
}
|
|
221
256
|
}
|
|
222
|
-
`.trim();function
|
|
257
|
+
`.trim();function Pi(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}r(Pi,"graphQLErrorMessage");function ft(t){let e=t.trim().toUpperCase();if(!e)throw new l("INVALID_ARGUMENT","ticker is required",400);return e}r(ft,"normalizedTicker");var W=class{constructor(e){this.client=e}client;static{r(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=ft(e),s=(await this.graphql(gi,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);return{ticker:s.ticker,current:s.companyInsight,history:s.companyInsightHistory}}async earningsPeriods(e){this.client._requireAuth();let n=ft(e),s=(await this.graphql(bi,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);if(!s.earningsPeriods)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings periods are available for ${s.ticker}`,404,{ticker:s.ticker});return s.earningsPeriods}async earnings(e){this.client._requireAuth();let n=ft(e.ticker),i=e.event,s=e.fiscalYear,o=e.fiscalQuarter;if(i!==void 0&&(s!==void 0||o!==void 0))throw new l("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(s===void 0!=(o===void 0))throw new l("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(i!==void 0&&!yi.includes(i))throw new l("INVALID_ARGUMENT",`Unknown earnings event selector: ${i}`,400);if(s!==void 0&&(!Number.isInteger(s)||s<1900||s>9999))throw new l("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(o!==void 0&&!fi.includes(o))throw new l("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let c,u;if(s!==void 0&&o!==void 0)c=s,u=o;else{let f=i??"latest-completed",T=await this.earningsPeriods(n),x=this.selectPeriod(T,f,n);c=x.fiscalYear,u=x.fiscalQuarter}let m=(await this.graphql(_i,{ticker:n,input:{fiscalYear:c,fiscalQuarter:u}})).market?.entity;if(!m)throw this.notFound(n);if(!m.earnings)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${m.ticker} FY${c} ${u}`,404,{ticker:m.ticker,fiscalYear:c,fiscalQuarter:u});return{ticker:m.ticker,...m.earnings}}selectPeriod(e,n,i){if(n==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let s=e.periods.filter(o=>o.status==="UPCOMING").sort((o,a)=>o.earningsDate.localeCompare(a.earningsDate));if(s.length>0)return s[0]}throw new l("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${n} earnings event is available for ${i}`,404,{ticker:i,event:n})}notFound(e){return new l("MARKETS_ENTITY_NOT_FOUND",`No stock entity was found for ${e}`,404,{ticker:e})}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",Pi(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};var ze=`
|
|
223
258
|
id
|
|
224
259
|
name
|
|
225
260
|
rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
|
|
@@ -232,45 +267,45 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
232
267
|
nextFireAtMs
|
|
233
268
|
createdAtMs
|
|
234
269
|
updatedAtMs
|
|
235
|
-
`,
|
|
270
|
+
`,Ri=`
|
|
236
271
|
query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
|
|
237
272
|
viewer { channel(id: $channelId) {
|
|
238
273
|
schedules(input: { first: 64, after: $after }) {
|
|
239
|
-
edges { node { channel { id } ${
|
|
274
|
+
edges { node { channel { id } ${ze} } }
|
|
240
275
|
pageInfo { hasNextPage endCursor }
|
|
241
276
|
}
|
|
242
277
|
} }
|
|
243
|
-
}`.trim(),
|
|
278
|
+
}`.trim(),ki=`
|
|
244
279
|
mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
|
|
245
280
|
updateChannelSchedule(input: $input) {
|
|
246
|
-
schedule { channel { id } ${
|
|
281
|
+
schedule { channel { id } ${ze} }
|
|
247
282
|
deleted
|
|
248
283
|
}
|
|
249
|
-
}`.trim(),
|
|
284
|
+
}`.trim(),wi=`
|
|
250
285
|
query ToolkitListSessionSchedules($inboxPath: String!, $after: String) {
|
|
251
286
|
viewer { sessionSchedules(inboxPath: $inboxPath, input: { first: 64, after: $after }) {
|
|
252
|
-
edges { node { ${
|
|
287
|
+
edges { node { ${ze} } }
|
|
253
288
|
pageInfo { hasNextPage endCursor }
|
|
254
289
|
} }
|
|
255
|
-
}`.trim(),
|
|
290
|
+
}`.trim(),Si=`
|
|
256
291
|
mutation ToolkitUpdateSessionSchedule($input: UpdateSessionScheduleInput!) {
|
|
257
292
|
updateSessionSchedule(input: $input) {
|
|
258
|
-
schedule { ${
|
|
293
|
+
schedule { ${ze} }
|
|
259
294
|
deleted
|
|
260
295
|
}
|
|
261
|
-
}`.trim(),
|
|
296
|
+
}`.trim(),Ti=`
|
|
262
297
|
query ToolkitAgentChannel {
|
|
263
298
|
viewer { channels { id kind } }
|
|
264
|
-
}`.trim(),
|
|
299
|
+
}`.trim(),Ai=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,vi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Ei=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,Ci=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,Ii={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},Y=class{constructor(e){this.client=e}client;static{r(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=gt(e),i="inboxPath"in n,s=[],o=null,a=new Set;for(;;){let c=await this.graphql(i?wi:Ri,{...n,after:o}),u=i?c.viewer?.sessionSchedules:c.viewer?.channel?.schedules;if(!u?.edges)throw sn();for(let m of u.edges){if(!m?.node)throw k();s.push(yt(m.node))}if(u.pageInfo?.hasNextPage!==!0)return s;let d=u.pageInfo.endCursor;if(!d||a.has(d))throw k();a.add(d),o=d}}async put(e){this.client._requireAuth();let n={...gt(e),name:on(e.name),definition:{...qi(e.rule,e.bounds),message:{text:Ui(e.text)}}},i=(await this.update(n))?.schedule;if(!i)throw k();return yt(i)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.update({...rn(e),lifecycle:"REMOVED"}))?.deleted!==!0)throw k()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(Ti)).viewer?.channels?.find(i=>i.kind==="AGENT")?.id;if(!n)throw sn();return n}async manage(e,n){this.client._requireAuth();let i=(await this.update({...rn(n),lifecycle:e}))?.schedule;if(!i)throw k();return yt(i)}async update(e){let n="inboxPath"in e,i=await this.graphql(n?Si:ki,{input:e});return n?i.updateSessionSchedule:i.updateChannelSchedule}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors?.length){let s=i.errors.map(d=>d.extensions?.code),a=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,c=a?Ii[a]:void 0,u=a!==void 0&&c!==void 0?a:"GRAPHQL_ERROR";throw new l(u,i.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",c??502,{errors:i.errors})}if(!i.data)throw k();return i.data}};function qi(t,e){let n=xi(e);switch(t.kind){case"after":if(n)throw b("after does not accept recurring bounds");let i=Date.now()+an(t.duration,1),s=Math.ceil(i/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw b("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw b("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:bt(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:Fi(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw b("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}r(qi,"ruleInput");function xi(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=bt(t.startsAt)),t.until!==void 0&&(e.untilMs=bt(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw b("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}r(xi,"boundsInput");function yt(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw k();let i=t.bounds??{},s=t.message??{},o={name:t.name,rule:Ni(t.rule),bounds:{...i.startsAtMs!=null?{startsAt:L(i.startsAtMs,!0)}:{},...i.untilMs!=null?{until:L(i.untilMs,!0)}:{},...i.maxOccurrences!=null?{maxOccurrences:_t(i.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:_t(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:L(t.nextFireAtMs,!0)}:{},createdAt:L(t.createdAtMs),updatedAt:L(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw k();let c={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!c)throw k();o.failure={code:c,...t.failureAtMs!=null?{at:L(t.failureAtMs)}:{}}}return o}r(yt,"fromWireSchedule");function Ni(t){switch(t.kind){case"AT":if(t.atMs==null)throw k();return{kind:"at",timestamp:L(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw k();return{kind:"every",interval:`PT${_t(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw k();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw k()}r(Ni,"fromWireRule");function rn(t){return{...gt(t),name:on(t.name)}}r(rn,"managementInput");function gt(t){if(t.channelId!==void 0==(t.inboxPath!==void 0))throw b("exactly one of channelId or inboxPath is required");if(t.channelId!==void 0)return{channelId:Di(t.channelId)};let e=t.inboxPath,n=typeof e=="string"?cn(e):void 0;if(typeof e!="string"||n===void 0||n>2048||!e.startsWith("/")||e.includes("\0")||e.slice(1).split("/").some(s=>s===""||s==="."||s===".."))throw b("inboxPath must be a canonical absolute ALFS Inbox path");let i=e.endsWith(".inbox.jsonl")?e.slice(0,-12)+".jsonl":e.endsWith(".inbox")&&!e.endsWith(".jsonl.inbox")?e.slice(0,-6):void 0;if(i===void 0||/\.inbox(?:\.jsonl)?$/.test(i)||/\.lock(?:\.recovery|\.heartbeat-[^/]+|\.stale-[^/]+)?$/.test(i)||i.endsWith("/.jsonl"))throw b("inboxPath must identify a standard Session Inbox sidecar");return{inboxPath:e}}r(gt,"targetInput");function Di(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw b("numeric channelId must be a positive safe integer; use a decimal string for larger IDs");let e=String(t);if(!/^[1-9]\d*$/.test(e))throw b("channelId must be a positive integer");return e}r(Di,"channelID");function on(t){if(!Ai.test(t))throw b("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}r(on,"requireName");function Ui(t){let e=cn(t);if(e===void 0||!t.trim()||e>16*1024)throw b("text must be 1..16384 UTF-8 bytes");return t}r(Ui,"requireText");function Fi(t){let e=an(t,60);if(e%1e3!==0)throw b("duration must resolve to whole seconds");return e/1e3}r(Fi,"durationSeconds");function an(t,e){let n=Ci.exec(t);if(!n||n.slice(1,5).every(d=>d===void 0)||t.includes("T")&&n.slice(2,5).every(d=>d===void 0))throw b("duration must be a positive ISO 8601 day/time duration");let[i,s,o,a]=n.slice(1,5).map(d=>BigInt(d??"0")),c=((i*24n+s)*60n+o)*60n+a;if(c<BigInt(e))throw b(`duration must be at least ${e} whole seconds`);let u=Number(c*1000n);if(!Number.isSafeInteger(u))throw b("duration is out of range");return u}r(an,"durationMilliseconds");function bt(t,e=!1){let n=(e?Ei:vi).exec(t);if(!n)throw b("timestamp must be RFC3339 with a timezone");let[i,s,o,a,c,u]=n.slice(1,7).map(Number),d=Number(n[8]??0),m=Number(n[9]??0),f=new Date(Date.UTC(i,s,0)).getUTCDate(),T=Date.parse(t);if(!Number.isFinite(T)||i<1||i>9999||s<1||s>12||o<1||o>f||a>23||c>59||u>59||d>23||m>59)throw b("timestamp must be RFC3339 with a timezone");return T}r(bt,"timestampMilliseconds");function L(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw k();let n=new Date(t);if(Number.isNaN(n.getTime()))throw k();return n.toISOString()}r(L,"timestampString");function _t(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw b(`${e} exceeds JavaScript safe integer range`);return n}r(_t,"safeInteger");function b(t){return new l("INVALID_ARGUMENT",t,400)}r(b,"invalid");function cn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}r(cn,"utf8Size");function sn(){return new l("NOT_FOUND","channel schedule target not found",404)}r(sn,"scheduleNotFound");function k(){return new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}r(k,"scheduleEmptyResponse");var Gi={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},Li=`
|
|
265
300
|
mutation ToolkitStewardDecide($input: UpdateStewardDeliveryInput!) {
|
|
266
301
|
updateStewardDelivery(input: $input) { delivery { deliveryId state } }
|
|
267
|
-
}`.trim(),
|
|
302
|
+
}`.trim(),Oi=`
|
|
268
303
|
mutation ToolkitStewardForward($input: UpdateStewardDeliveryInput!) {
|
|
269
304
|
updateStewardDelivery(input: $input) { delivery { deliveryId state channelMessageId } }
|
|
270
|
-
}`.trim(),
|
|
305
|
+
}`.trim(),Mi=`
|
|
271
306
|
mutation ToolkitStewardSend($input: PostStewardMessageInput!) {
|
|
272
307
|
postStewardMessage(input: $input) { message { channelMessageId requestId } }
|
|
273
|
-
}`.trim()
|
|
308
|
+
}`.trim(),$i=`
|
|
274
309
|
query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInput) {
|
|
275
310
|
viewer {
|
|
276
311
|
stewardDigestPending(inboxPath: $inboxPath, input: $input) {
|
|
@@ -283,8 +318,12 @@ query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInp
|
|
|
283
318
|
windowUntilMs
|
|
284
319
|
}
|
|
285
320
|
}
|
|
286
|
-
}`.trim(),
|
|
321
|
+
}`.trim(),ji=`
|
|
287
322
|
mutation ToolkitStewardBriefed($input: CompleteStewardBriefInput!) {
|
|
288
323
|
completeStewardBrief(input: $input) { ok }
|
|
289
|
-
}`.trim(),Ai=new Set(["immediate","digest","suppress"]),Ci=/^[1-9][0-9]{0,18}$/;function w(t){return new u("INVALID_ARGUMENT",t,400)}r(w,"invalid");function me(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw w("steward commands require the steward Session Inbox path");return t.inboxPath}r(me,"requireInboxPath");function bt(t,e="delivery id"){if(!Ci.test(t))throw w(`${e} must be a positive integer`);return t}r(bt,"requireDeliveryId");function sn(t){if(t.length===0)throw w("at least one delivery id is required");let e=new Set;for(let n of t){if(bt(n),e.has(n))throw w(`duplicate delivery id ${n}`);e.add(n)}return[...e]}r(sn,"requireDeliveryIds");function Ii(t){if(!Ai.has(t))throw w("decision must be one of immediate, digest, suppress");return t}r(Ii,"requireDecision");function qi(){let t=globalThis.crypto;if(typeof t?.randomUUID=="function")return t.randomUUID();let e=new Uint8Array(16);if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let i=0;i<e.length;i+=1)e[i]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}r(qi,"generateRequestId");function on(t){if(t===void 0)return qi();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw w("request id must be a UUID");return t}r(on,"requireRequestId");function N(){return new u("EMPTY_RESPONSE","steward response was empty",502)}r(N,"emptyResponse");var H=class{constructor(e){this.client=e}client;static{r(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw w("a decision reason is required");let s=(await this.graphql(Si,{input:{inboxPath:me(e),deliveryId:bt(e.deliveryId),decision:{decision:Ii(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!s)throw N();return{state:s.state}}async forward(e){this.client._requireAuth();let i=(await this.graphql(wi,{input:{inboxPath:me(e),deliveryId:bt(e.deliveryId),forward:{requestId:on(e.requestId)}}})).updateStewardDelivery?.delivery;if(!i||!i.channelMessageId)throw N();return{channelMessageId:i.channelMessageId,state:i.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw w("a message body is required");let i=(await this.graphql(vi,{input:{inboxPath:me(e),requestId:on(e.requestId),body:e.body,deliveryIds:sn(e.deliveryIds)}})).postStewardMessage?.message;if(!i)throw N();return i}async pending(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw w("first must be an integer between 1 and 100");let i={first:n};if(e.after!==void 0&&e.after!=="")i.after=e.after;else{for(let[p,P]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(P!==void 0&&(!Number.isSafeInteger(P)||P<=0))throw w(`${p} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw w("untilMs must be after sinceMs");e.sinceMs!==void 0&&(i.sinceMs=e.sinceMs),e.untilMs!==void 0&&(i.untilMs=e.untilMs)}let o=(await this.graphql(Ti,{inboxPath:me(e),input:i})).viewer?.stewardDigestPending;if(!o||!Array.isArray(o.edges))throw N();let a=o.windowSinceMs??0,l=o.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(l)||a<=0||l<=a)throw N();let c=o.edges.map(p=>p.node),d=o.pageInfo?.hasNextPage===!0&&o.pageInfo.endCursor?o.pageInfo.endCursor:null;return{items:c,nextCursor:d,windowSinceMs:a,windowUntilMs:l}}async briefed(e){this.client._requireAuth();let n=e.digestRunId?.trim();if(!n)throw w("a digest run id is required");if((await this.graphql(Ei,{input:{inboxPath:me(e),deliveryIds:sn(e.deliveryIds),digestRunId:n}})).completeStewardBrief?.ok!==!0)throw N();return{ok:!0}}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i||typeof i!="object")throw N();if(i.errors?.length){let s=i.errors.map(l=>l.extensions?.code),o=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=o?ki[o]:void 0;throw new u(o!==void 0&&a!==void 0?o:"GRAPHQL_ERROR",i.errors.map(l=>l.message).filter(l=>typeof l=="string").join("; ")||"GraphQL request failed",a??502,{errors:i.errors})}if(!i.data)throw N();return i.data}};function U(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(U,"isRecord");function f(t){return typeof t=="string"&&t.trim()!==""?t:void 0}r(f,"stringValue");function He(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}r(He,"numberValue");function Je(t){return t===void 0?void 0:t.trim().toUpperCase()}r(Je,"upper");function ln(t){return t.split("_")}r(ln,"pairParts");function xi(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":ln(e)[1]?.toLowerCase()??""}r(xi,"inferInstrumentType");function Di(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}r(Di,"inferUnderlyingType");function an(t,e){let n=f(t.trading_pair)??f(t.tradingPair)??f(t.symbol);if(n===void 0)return;let i=f(t.type),s=ln(n),o=f(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),a=f(t.market)??f(t.exchange)??s[0]??"",l=f(t.quote)??s[s.length-1]??"",c=f(t.instrument_type)??f(t.instrumentType)??xi(i,n),d=f(t.underlying_type)??f(t.underlyingType)??Di(i);return{symbol:o,tradingPair:n,market:a,instrumentType:c,...d===void 0?{}:{underlyingType:d},quote:l,...i===void 0?{}:{type:i},...f(t.description)===void 0?{}:{description:f(t.description)},...He(t.fee_rate)===void 0?He(t.feeRate)===void 0?{}:{feeRate:He(t.feeRate)}:{feeRate:He(t.fee_rate)},...f(t.symbol_icon_url)===void 0?f(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:f(t.symbolIconUrl)}:{symbolIconUrl:f(t.symbol_icon_url)}}}r(an,"normalizeCandidate");function Ni(t){if(!U(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>U(s)?[an(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let i=[];for(let s of n){if(!U(s))continue;let o=f(s.symbol),a=s.trading_pairs;if(Array.isArray(a)){for(let l of a)if(!(!U(l)||!Array.isArray(l.pairs)))for(let c of l.pairs){if(!U(c))continue;let d=an({...c,instrument_type:c.instrument_type??l.instrument_type},o);d!==void 0&&i.push(d)}}}return i}r(Ni,"flattenResponse");function Ui(t,e){let n=e.trim();return t.tradingPair===n?!0:Je(t.symbol)===Je(n)}r(Ui,"matchesQuery");function ze(t,e){return e===void 0||Je(t)===Je(e)}r(ze,"matchesFilter");function Fi(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}r(Fi,"dedupe");function Gi(t){let e=U(t)?t:{};return{market:typeof e.market=="string"?e.market:void 0,instrumentType:typeof e.instrumentType=="string"?e.instrumentType:void 0,underlyingType:typeof e.underlyingType=="string"?e.underlyingType:void 0,quote:typeof e.quote=="string"?e.quote:void 0}}r(Gi,"resolveFilters");function Li(t,e){let n=t.split("_"),i=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!i||!s||!o||!a?{symbol:t,...e}:{symbol:o,market:e.market??i,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??a}}r(Li,"pairSearchParams");var z=class{constructor(e){this.client=e}client;static{r(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=U(e)?e.symbol:void 0,i=typeof n=="string"?n.trim():"";if(!i)throw new u("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:i,strict:!0}}),o=Fi(Ni(s)).filter(l=>Ui(l,i)).filter(l=>ze(l.market,e.market)).filter(l=>ze(l.instrumentType,e.instrumentType)).filter(l=>ze(l.underlyingType,e.underlyingType)).filter(l=>ze(l.quote,e.quote)),a=e.limit;return a!==void 0&&o.length>a?{query:i,candidates:o.slice(0,a),truncated:!0}:{query:i,candidates:o}}async resolve(e){let n=U(e)?e:{},i=typeof n.pair=="string"?n.pair.trim():void 0,s=Gi(e),o=i===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:Li(i,s),a=await this.search(o),l=i===void 0?a.candidates:a.candidates.filter(c=>c.tradingPair===i);if(l.length!==1)throw new u(l.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",l.length===0?`no canonical trading pair matched "${i??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,l.length===0?404:409,{query:i??o.symbol,candidateCount:l.length,candidates:l.slice(0,50),...l.length>50?{truncated:!0}:{}});return l[0]}};var Oi=9223372036854775807n,Mi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$i=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,un=new TextEncoder,K=class{constructor(e){this.client=e}client;static{r(this,"ThesesResource")}async create(e){this.client._requireAuth();let n=ji(e);return J(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){return this.client._requireAuth(),Qi(await this.client._request("GET",`/api/v1/theses/${v(e,"id")}`))}async getVersion(e,n){this.client._requireAuth();let i=v(e,"id"),s=v(n,"author_version_id"),o=J(await this.client._request("GET",`/api/v1/theses/${i}/versions/${s}`));if(o.thesis.id!==i||o.thesis.author_version_id!==s)throw m("version response must match the requested thesis and author version");return o}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw y("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw y("cursor must be a string");return Vi(await this.client._request("GET",`/api/v1/theses/${v(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=Bi(n);return J(await this.client._request("PUT",`/api/v1/theses/${v(e,"id")}`,{body:i}))}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw y("params is required");let i=v(e,"id"),s=et(n.visibility),o=J(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:s}}));if(o.thesis.id!==i||o.thesis.visibility!==s)throw m("visibility response must match the requested thesis and visibility");return o}async close(e,n){this.client._requireAuth();let i={expected_author_version_id:v(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(i.note=F(n.note,"note")),J(await this.client._request("POST",`/api/v1/theses/${v(e,"id")}/close`,{body:i}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${v(e,"id")}`);if(n===void 0)return{};if(!k(n)||Object.keys(n).length!==0)throw m("delete response must be {}");return{}}async rewrite(e){this.client._requireAuth();let n=Ze(e.body),i=e.mode===void 0?"reformat":Yi(e.mode),s=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:i}});if(!k(s)||typeof s.body!="string")throw m("rewrite response must contain a string body");return{body:pn(s.body)}}};function ji(t){let e={request_id:cn(t.request_id),body:Ze(t.body),title:Pt(t.title??""),entity_ids:dn(t.entity_ids??[],"entity_ids"),visibility:et(t.visibility??"public")};return t.tickers!==void 0&&(e.tickers=Wi(t.tickers)),e}r(ji,"createBody");function Bi(t){return{request_id:cn(t.request_id),expected_author_version_id:v(t.expected_author_version_id,"expected_author_version_id"),body:Ze(t.body),title:Pt(t.title??""),entity_ids:dn(t.entity_ids??[],"entity_ids"),visibility:et(t.visibility),editorial:t.editorial??!1}}r(Bi,"updateBody");function J(t){if(!k(t)||!k(t.thesis))throw m("response must contain thesis");let e=t.thesis;return{thesis:{id:I(e.id,"thesis.id"),author_version_id:I(e.author_version_id,"thesis.author_version_id"),material_version_id:I(e.material_version_id,"thesis.material_version_id"),title:Ki(e.title),body:pn(e.body),entity_ids:Hi(e.entity_ids,"thesis.entity_ids"),visibility:Ji(e.visibility),closed:Xe(e.closed,"thesis.closed"),closing_note:zi(e.closing_note),author_kind:g(e.author_kind,"thesis.author_kind"),author_ref:g(e.author_ref,"thesis.author_ref")}}}r(J,"thesisResponse");function Qi(t){let e=J(t);if(!k(t)||!k(t.author))throw m("response must contain author");let n=t.author,i={id:I(n.id,"author.id"),kind:g(n.kind,"author.kind"),display_name:g(n.display_name,"author.display_name"),avatar_url:g(n.avatar_url,"author.avatar_url"),username:g(n.username,"author.username")};if(!Array.isArray(t.entities))throw m("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw m("entities must match thesis.entity_ids");let s=t.entities.map((o,a)=>{if(!k(o))throw m(`entities[${a}] must be an object`);let l={id:I(o.id,`entities[${a}].id`),ticker:g(o.ticker,`entities[${a}].ticker`),name:g(o.name,`entities[${a}].name`),icon_url:g(o.icon_url,`entities[${a}].icon_url`),kind:g(o.kind,`entities[${a}].kind`)};if(l.id!==e.thesis.entity_ids[a])throw m("entities must preserve thesis.entity_ids order");return l});return{thesis:e.thesis,author:i,entities:s}}r(Qi,"thesisGetResponse");function Vi(t,e,n){if(!k(t)||!k(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw m("invalid Signal history response");let i=t.research,s={state:g(i.state,"research.state"),pending_work:Ke(i.pending_work,"research.pending_work"),read_complete:Xe(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(s.last_attempt_ms=Ke(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(s.last_completed_ms=Ke(i.last_completed_ms,"research.last_completed_ms"));let o=t.entries.map(l=>{if(!k(l)||!k(l.signal)||!k(l.signal.source))throw m("entry must include a Signal and source");let c=l.signal,d=c.source,p=I(c.thesis_id,"signal.thesis_id");if(p!==e)throw m("Signal belongs to another Thesis");let P=_t(l.cursor,"entry.cursor"),S={title:g(d.title,"source.title")};d.url!==void 0&&(S.url=g(d.url,"source.url")),d.published_at_ms!==void 0&&(S.published_at_ms=Ke(d.published_at_ms,"source.published_at_ms"));let q={id:I(c.id,"signal.id"),thesis_id:p,author_version_id:I(c.author_version_id,"signal.author_version_id"),statement_snapshot:_t(c.statement_snapshot,"signal.statement_snapshot"),stance:g(c.stance,"signal.stance"),explanation:g(c.explanation,"signal.explanation"),information_kind:g(c.information_kind,"signal.information_kind"),source:S};if(c.evidence_excerpt!==void 0){if(!k(c.evidence_excerpt))throw m("invalid evidence excerpt");q.evidence_excerpt={text:_t(c.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:Xe(c.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:Xe(c.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:I(l.feed_entry_id,"feed_entry_id"),cursor:P,signal:q}}),a=g(t.next_cursor,"next_cursor");if(a&&a!==o[o.length-1]?.cursor)throw m("next_cursor must match the final entry");return{research:s,entries:o,next_cursor:a}}r(Vi,"thesisSignalsResponse");function Ke(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw m(e+" must be a nonnegative safe integer");return t}r(Ke,"responseNonnegativeInteger");function _t(t,e){let n=g(t,e);if(!n.trim())throw m(e+" must be nonempty");return n}r(_t,"responseNonemptyText");function cn(t){if(!Mi.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw y("request_id must be a non-zero RFC 4122 UUID");return t}r(cn,"requireRequestID");function v(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw y(`${e} must be a positive int64 decimal string`);if(BigInt(t)>Oi)throw y(`${e} must be a positive int64 decimal string`);return t}r(v,"requireID");function dn(t,e){if(!Array.isArray(t))throw y(`${e} must be an array`);if(t.length>20)throw y(`${e} must contain at most 20 IDs`);return t.map((n,i)=>v(n,`${e}[${i}]`))}r(dn,"requireIDs");function Wi(t){if(!Array.isArray(t))throw y("tickers must be an array");if(t.length>100)throw y("tickers must contain at most 100 values");return t.map((e,n)=>{let i=F(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw y(`tickers[${n}] must be non-empty`);return i})}r(Wi,"requireTickers");function Ze(t){let e=F(t,"body");if(e.trim().length===0)throw y("body must not be blank");if(un.encode(e).byteLength>65536)throw y("body must be at most 65536 UTF-8 bytes");return e}r(Ze,"requireBody");function Pt(t){let e=F(t,"title");if(un.encode(e).byteLength>500)throw y("title must be at most 500 UTF-8 bytes");return e}r(Pt,"requireTitle");function et(t){let e=F(t,"visibility");if(e!=="public"&&e!=="private")throw y("visibility must be public or private");return e}r(et,"requireVisibility");function Yi(t){let e=F(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw y("mode must be reformat, shorten, or enrich")}r(Yi,"requireRewriteMode");function F(t,e){if(typeof t!="string")throw y(`${e} must be a string`);if($i.test(t))throw y(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw y(`${e} must not contain NUL`);return t}r(F,"requireText");function I(t,e){if(typeof t=="number")throw m(`${e} must be a decimal string; numeric IDs are unsafe`);try{return v(t,e)}catch{throw m(`${e} must be a positive int64 decimal string`)}}r(I,"responseID");function Hi(t,e){if(!Array.isArray(t))throw m(`${e} must be an array`);if(t.length>20)throw m(`${e} must contain at most 20 IDs`);return t.map((n,i)=>I(n,`${e}[${i}]`))}r(Hi,"responseIDs");function g(t,e){try{return F(t,e)}catch{throw m(`${e} must be valid text`)}}r(g,"responseText");function zi(t){try{return F(t,"note")}catch{throw m("thesis.closing_note must be valid text")}}r(zi,"responseClosingNote");function Xe(t,e){if(typeof t!="boolean")throw m(`${e} must be boolean`);return t}r(Xe,"responseBoolean");function Ji(t){try{return et(t)}catch{throw m("thesis.visibility must be public or private")}}r(Ji,"responseVisibility");function pn(t){try{return Ze(t)}catch{throw m("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}r(pn,"responseBody");function Ki(t){try{return Pt(t)}catch{throw m("response title must be valid text at most 500 UTF-8 bytes")}}r(Ki,"responseTitle");function k(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(k,"isRecord");function y(t){return new u("INVALID_ARGUMENT",t,400)}r(y,"invalidArgument");function m(t){return new u("INVALID_RESPONSE",t,502)}r(m,"invalidResponse");var Xi="https://api-llm.prd.alva.ai",Zi="https://data-tools.prd.space.id";function Rt(t){return typeof t=="object"&&t!==null}r(Rt,"isRecord");function tt(t,e){if(!Rt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}r(tt,"stringField");function er(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let i=tt(t,"code");i&&(e.code=i)}else if(Rt(t)){let i=tt(t,"code"),s=tt(t,"name"),o=tt(t,"message");i&&(e.code=i),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(i=>!!i);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}r(er,"describeCause");function tr(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",n={};t instanceof Error?(n.name=t.name,n.message=t.message):n.message=String(t);let{message:i,details:s}=er(Rt(t)?t.cause:void 0);return s&&(n.cause=s),{message:i?`${e}; cause: ${i}`:e,details:n}}r(tr,"describeFetchFailure");var nt=class{static{r(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;originInboxPath;_fs;_run;_deploy;_serviceAccount;_release;_feed;_forYou;_automation;_playbooks;_secrets;_sdk;_dataSkills;_playbookSkills;_comments;_remix;_screenshot;_user;_trading;_portfolio;_arraysJwt;_notifications;_notificationPreferences;_subscriptions;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_steward;_tradingPairs;_theses;constructor(e){this.baseUrl=e.baseUrl??Xi,this.arraysBaseUrl=e.arraysBaseUrl??Zi,this.viewer_token=e.viewer_token,this.pbsvToken=e.pbsvToken,this.apiKey=e.apiKey,this.gaClientId=e.gaClientId,this.gaSessionId=e.gaSessionId,this.utmParams=e.utmParams,this.signal=e.signal,this.originSessionId=e.originSessionId,this.originSessionKind=e.originSessionKind,this.originInboxPath=e.originInboxPath}get fs(){return this._fs??=new _e(this)}get run(){return this._run??=new Pe(this)}get deploy(){return this._deploy??=new Re(this)}get serviceAccount(){return this._serviceAccount??=new ke(this)}get release(){return this._release??=new Se(this)}get feed(){return this._feed??=new ve(this)}get automation(){return this._automation??=new Q(this)}get playbooks(){return this._playbooks??=new Ae(this)}get secrets(){return this._secrets??=new Ce(this)}get sdk(){return this._sdk??=new Ie(this)}get dataSkills(){return this._dataSkills??=new qe(this)}get playbookSkills(){return this._playbookSkills??=new xe(this)}get comments(){return this._comments??=new De(this)}get remix(){return this._remix??=new Ne(this)}get screenshot(){return this._screenshot??=new Ue(this)}get user(){return this._user??=new Fe(this)}get trading(){return this._trading??=new Ge(this)}get portfolio(){return this._portfolio??=new Le(this)}get arraysJwt(){return this._arraysJwt??=new Oe(this)}get notifications(){return this._notifications??=new Me(this)}get notificationPreferences(){return this._notificationPreferences??=new $e(this)}get subscriptions(){return this._subscriptions??=new je(this)}get alerts(){return this._alerts??=new V(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new Be(this)}get feedback(){return this._feedback??=new Qe(this)}get functions(){return this._functions??=new Ve(this)}get credits(){return this._credits??=new We(this)}get markets(){return this._markets??=new W(this)}get tradingPairs(){return this._tradingPairs??=new z(this)}get schedules(){return this._schedules??=new Y(this)}get steward(){return this._steward??=new H(this)}get theses(){return this._theses??=new K(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new u("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get forYou(){return this._forYou??=new B(this)}async _request(e,n,i){let o=`${i?.baseUrl??this.baseUrl}${n}`;if(i?.query){let A=new URLSearchParams;for(let[x,it]of Object.entries(i.query))it!=null&&A.set(x,String(it));let O=A.toString();O&&(o+=`?${O}`)}let a={};i?.noAuth||(this.pbsvToken?(a.Authorization=`Bearer ${this.pbsvToken}`,a["X-Pbsv"]="1"):this.viewer_token?a["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(a["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(a["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(a["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(a["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!i?.noAuth&&(a["X-Alva-Origin-Session-Id"]=this.originSessionId);let l;i?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",l=i.rawBody):i?.jsonBody!==void 0?(a["Content-Type"]="application/json",l=i.jsonBody):i?.body!==void 0&&(a["Content-Type"]="application/json",l=JSON.stringify(i.body));let c,d=i?.timeoutMs,p=i?.signal??this.signal;if(p?.aborted)throw new u("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let P=d!==void 0?new AbortController:void 0,S=!1,q,he;P&&d!==void 0&&(p&&(he=r(()=>P.abort(p.reason),"abortListener"),p.addEventListener("abort",he,{once:!0})),q=setTimeout(()=>{S=!0,P.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let kt={method:e,headers:a,body:l,signal:P?.signal??p};d!==void 0&&(kt.timeout=d);try{c=await fetch(o,kt)}catch(A){if(p?.aborted&&!S)throw new u("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(S)throw new u("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let O=tr(A);throw new u("NETWORK_ERROR",O.message,0,{method:e,path:n,...O.details})}finally{he&&p&&p.removeEventListener("abort",he),q!==void 0&&clearTimeout(q)}if(!c.ok){let A="";try{A=await Promise.resolve(c.text())}catch{A=""}if((c.headers.get("content-type")??"").includes("application/json")&&A)try{let x=JSON.parse(A);if(x.error)throw new u(x.error.code??"UNKNOWN",x.error.message??`HTTP ${c.status}`,c.status)}catch(x){if(x instanceof u)throw x}throw new u("UNKNOWN",`HTTP ${c.status}: ${A.slice(0,200)}`,c.status)}if(c.status===204)return;let St=(c.headers.get("content-type")??"").toLowerCase();return St.includes("application/json")||St.includes("+json")?c.json():c.arrayBuffer()}};var nr="0.29.0";ut();return bn(ir);})();
|
|
324
|
+
}`.trim(),Bi=new Set(["immediate","digest","suppress"]),Qi=/^[1-9][0-9]{0,18}$/;function A(t){return new l("INVALID_ARGUMENT",t,400)}r(A,"invalid");function he(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw A("steward commands require the steward Session Inbox path");return t.inboxPath}r(he,"requireInboxPath");function Pt(t,e="delivery id"){if(!Qi.test(t))throw A(`${e} must be a positive integer`);return t}r(Pt,"requireDeliveryId");function ln(t){let e=new Set;for(let n of t){if(Pt(n),e.has(n))throw A(`duplicate delivery id ${n}`);e.add(n)}return[...e]}r(ln,"normalizeDeliveryIds");function Vi(t){if(t.length===0)throw A("at least one delivery id is required");return ln(t)}r(Vi,"requireDeliveryIds");function Wi(t){if(!Bi.has(t))throw A("decision must be one of immediate, digest, suppress");return t}r(Wi,"requireDecision");function Yi(){let t=globalThis.crypto;if(typeof t?.randomUUID=="function")return t.randomUUID();let e=new Uint8Array(16);if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let i=0;i<e.length;i+=1)e[i]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}r(Yi,"generateRequestId");function un(t){if(t===void 0)return Yi();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw A("request id must be a UUID");return t}r(un,"requireRequestId");function U(){return new l("EMPTY_RESPONSE","steward response was empty",502)}r(U,"emptyResponse");var H=class{constructor(e){this.client=e}client;static{r(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw A("a decision reason is required");let s=(await this.graphql(Li,{input:{inboxPath:he(e),deliveryId:Pt(e.deliveryId),decision:{decision:Wi(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!s)throw U();return{state:s.state}}async forward(e){this.client._requireAuth();let i=(await this.graphql(Oi,{input:{inboxPath:he(e),deliveryId:Pt(e.deliveryId),forward:{requestId:un(e.requestId)}}})).updateStewardDelivery?.delivery;if(!i||!i.channelMessageId)throw U();return{channelMessageId:i.channelMessageId,state:i.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw A("a message body is required");let i=(await this.graphql(Mi,{input:{inboxPath:he(e),requestId:un(e.requestId),body:e.body,deliveryIds:ln(e.deliveryIds??[])}})).postStewardMessage?.message;if(!i)throw U();return i}async pending(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw A("first must be an integer between 1 and 100");let i={first:n};if(e.after!==void 0&&e.after!=="")i.after=e.after;else{for(let[m,f]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(f!==void 0&&(!Number.isSafeInteger(f)||f<=0))throw A(`${m} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw A("untilMs must be after sinceMs");e.sinceMs!==void 0&&(i.sinceMs=e.sinceMs),e.untilMs!==void 0&&(i.untilMs=e.untilMs)}let o=(await this.graphql($i,{inboxPath:he(e),input:i})).viewer?.stewardDigestPending;if(!o||!Array.isArray(o.edges))throw U();let a=o.windowSinceMs??0,c=o.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(c)||a<=0||c<=a)throw U();let u=o.edges.map(m=>m.node),d=o.pageInfo?.hasNextPage===!0&&o.pageInfo.endCursor?o.pageInfo.endCursor:null;return{items:u,nextCursor:d,windowSinceMs:a,windowUntilMs:c}}async briefed(e){this.client._requireAuth();let n=e.digestRunId?.trim();if(!n)throw A("a digest run id is required");if((await this.graphql(ji,{input:{inboxPath:he(e),deliveryIds:Vi(e.deliveryIds),digestRunId:n}})).completeStewardBrief?.ok!==!0)throw U();return{ok:!0}}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i||typeof i!="object")throw U();if(i.errors?.length){let s=i.errors.map(c=>c.extensions?.code),o=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=o?Gi[o]:void 0;throw new l(o!==void 0&&a!==void 0?o:"GRAPHQL_ERROR",i.errors.map(c=>c.message).filter(c=>typeof c=="string").join("; ")||"GraphQL request failed",a??502,{errors:i.errors})}if(!i.data)throw U();return i.data}};function F(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(F,"isRecord");function _(t){return typeof t=="string"&&t.trim()!==""?t:void 0}r(_,"stringValue");function Je(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}r(Je,"numberValue");function Ze(t){return t===void 0?void 0:t.trim().toUpperCase()}r(Ze,"upper");function pn(t){return t.split("_")}r(pn,"pairParts");function Hi(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":pn(e)[1]?.toLowerCase()??""}r(Hi,"inferInstrumentType");function Ki(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}r(Ki,"inferUnderlyingType");function dn(t,e){let n=_(t.trading_pair)??_(t.tradingPair)??_(t.symbol);if(n===void 0)return;let i=_(t.type),s=pn(n),o=_(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),a=_(t.market)??_(t.exchange)??s[0]??"",c=_(t.quote)??s[s.length-1]??"",u=_(t.instrument_type)??_(t.instrumentType)??Hi(i,n),d=_(t.underlying_type)??_(t.underlyingType)??Ki(i);return{symbol:o,tradingPair:n,market:a,instrumentType:u,...d===void 0?{}:{underlyingType:d},quote:c,...i===void 0?{}:{type:i},..._(t.description)===void 0?{}:{description:_(t.description)},...Je(t.fee_rate)===void 0?Je(t.feeRate)===void 0?{}:{feeRate:Je(t.feeRate)}:{feeRate:Je(t.fee_rate)},..._(t.symbol_icon_url)===void 0?_(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:_(t.symbolIconUrl)}:{symbolIconUrl:_(t.symbol_icon_url)}}}r(dn,"normalizeCandidate");function zi(t){if(!F(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>F(s)?[dn(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let i=[];for(let s of n){if(!F(s))continue;let o=_(s.symbol),a=s.trading_pairs;if(Array.isArray(a)){for(let c of a)if(!(!F(c)||!Array.isArray(c.pairs)))for(let u of c.pairs){if(!F(u))continue;let d=dn({...u,instrument_type:u.instrument_type??c.instrument_type},o);d!==void 0&&i.push(d)}}}return i}r(zi,"flattenResponse");function Ji(t,e){let n=e.trim();return t.tradingPair===n?!0:Ze(t.symbol)===Ze(n)}r(Ji,"matchesQuery");function Xe(t,e){return e===void 0||Ze(t)===Ze(e)}r(Xe,"matchesFilter");function Xi(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}r(Xi,"dedupe");function Zi(t){let e=F(t)?t:{};return{market:typeof e.market=="string"?e.market:void 0,instrumentType:typeof e.instrumentType=="string"?e.instrumentType:void 0,underlyingType:typeof e.underlyingType=="string"?e.underlyingType:void 0,quote:typeof e.quote=="string"?e.quote:void 0}}r(Zi,"resolveFilters");function er(t,e){let n=t.split("_"),i=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!i||!s||!o||!a?{symbol:t,...e}:{symbol:o,market:e.market??i,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??a}}r(er,"pairSearchParams");var K=class{constructor(e){this.client=e}client;static{r(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=F(e)?e.symbol:void 0,i=typeof n=="string"?n.trim():"";if(!i)throw new l("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:i,strict:!0}}),o=Xi(zi(s)).filter(c=>Ji(c,i)).filter(c=>Xe(c.market,e.market)).filter(c=>Xe(c.instrumentType,e.instrumentType)).filter(c=>Xe(c.underlyingType,e.underlyingType)).filter(c=>Xe(c.quote,e.quote)),a=e.limit;return a!==void 0&&o.length>a?{query:i,candidates:o.slice(0,a),truncated:!0}:{query:i,candidates:o}}async resolve(e){let n=F(e)?e:{},i=typeof n.pair=="string"?n.pair.trim():void 0,s=Zi(e),o=i===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:er(i,s),a=await this.search(o),c=i===void 0?a.candidates:a.candidates.filter(u=>u.tradingPair===i);if(c.length!==1)throw new l(c.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",c.length===0?`no canonical trading pair matched "${i??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,c.length===0?404:409,{query:i??o.symbol,candidateCount:c.length,candidates:c.slice(0,50),...c.length>50?{truncated:!0}:{}});return c[0]}};var tr=9223372036854775807n,nr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ir=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,mn=new TextEncoder,J=class{constructor(e){this.client=e}client;static{r(this,"ThesesResource")}async assetCandidates(e){this.client._requireAuth();let n=ye(e),i=await this.client._request("POST","/query",{body:{query:`query ThesisAssetCandidates($input: ThesisAssetCandidatesInput!) {
|
|
325
|
+
viewer { thesisAssetCandidates(input: $input) {
|
|
326
|
+
mentions { quote ticker resolution stance candidates { entityId ticker name kind } }
|
|
327
|
+
} }
|
|
328
|
+
}`,variables:{input:{text:n}}}});if(Array.isArray(i?.errors)&&i.errors.length>0)throw new l("GRAPHQL_ERROR","Asset extraction failed",400,{errors:i.errors});let s=i?.data,o=g(s)?s.viewer:void 0,a=g(o)?o.thesisAssetCandidates:void 0;if(!g(a)||!Array.isArray(a.mentions))throw p("asset candidates response must contain mentions");return{mentions:a.mentions.map((u,d)=>{if(!g(u)||typeof u.quote!="string"||typeof u.ticker!="string"||!["RESOLVED","AMBIGUOUS","UNRESOLVED"].includes(u.resolution)||!["UNKNOWN","BULLISH","BEARISH"].includes(u.stance)||!Array.isArray(u.candidates))throw p(`asset mention ${d} is invalid`);let m=u.candidates.map(f=>{if(!g(f)||typeof f.ticker!="string"||typeof f.name!="string"||!["STOCK","ETF","CRYPTO","INDEX"].includes(f.kind))throw p(`asset mention ${d} has invalid candidate`);return{entityId:v(f.entityId,`asset mention ${d} candidate.entityId`),ticker:f.ticker,name:f.name,kind:f.kind}});return{...u,candidates:m}})}}async create(e){this.client._requireAuth();let n=rr(e);return z(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){return this.client._requireAuth(),ar(await this.client._request("GET",`/api/v1/theses/${S(e,"id")}`))}async getVersion(e,n){this.client._requireAuth();let i=S(e,"id"),s=S(n,"author_version_id"),o=z(await this.client._request("GET",`/api/v1/theses/${i}/versions/${s}`));if(o.thesis.id!==i||o.thesis.author_version_id!==s)throw p("version response must match the requested thesis and author version");return o}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw y("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw y("cursor must be a string");return cr(await this.client._request("GET",`/api/v1/theses/${S(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=or(n);return z(await this.client._request("PUT",`/api/v1/theses/${S(e,"id")}`,{body:i}))}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw y("params is required");let i=S(e,"id"),s=nt(n.visibility),o=z(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:s}}));if(o.thesis.id!==i||o.thesis.visibility!==s)throw p("visibility response must match the requested thesis and visibility");return o}async close(e,n){this.client._requireAuth();let i={expected_author_version_id:S(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(i.note=G(n.note,"note")),z(await this.client._request("POST",`/api/v1/theses/${S(e,"id")}/close`,{body:i}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${S(e,"id")}`);if(n===void 0)return{};if(!g(n)||Object.keys(n).length!==0)throw p("delete response must be {}");return{}}async rewrite(e){this.client._requireAuth();let n=ye(e.body),i=e.mode===void 0?"reformat":lr(e.mode),s=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:i}});if(!g(s)||typeof s.body!="string")throw p("rewrite response must contain a string body");return{body:yn(s.body)}}};function rr(t){let e={request_id:hn(t.request_id),body:ye(t.body),title:kt(t.title??""),entity_ids:fn(t.entity_ids??[],"entity_ids"),visibility:nt(t.visibility??"public")};return t.tickers!==void 0&&(e.tickers=ur(t.tickers)),t.entity_stances!==void 0&&(e.entity_stances=sr(t.entity_stances,e.entity_ids)),e}r(rr,"createBody");function sr(t,e){if(!Array.isArray(t)||t.length>fe)throw y("entity_stances must contain at most 100 values");let n=new Set(e),i=new Set;return t.map((s,o)=>{if(!g(s))throw y(`entity_stances[${o}] must be an object`);let a=S(s.entity_id,`entity_stances[${o}].entity_id`);if(!n.has(a)||i.has(a))throw y("entity stance must reference one unique entity_id");if(i.add(a),!["unknown","bullish","bearish"].includes(s.stance))throw y(`entity_stances[${o}].stance is invalid`);return{entity_id:a,stance:s.stance}})}r(sr,"requireEntityStances");function or(t){return{request_id:hn(t.request_id),expected_author_version_id:S(t.expected_author_version_id,"expected_author_version_id"),body:ye(t.body),title:kt(t.title??""),entity_ids:fn(t.entity_ids??[],"entity_ids"),visibility:nt(t.visibility),editorial:t.editorial??!1}}r(or,"updateBody");function z(t){if(!g(t)||!g(t.thesis))throw p("response must contain thesis");let e=t.thesis,n={id:v(e.id,"thesis.id"),author_version_id:v(e.author_version_id,"thesis.author_version_id"),material_version_id:v(e.material_version_id,"thesis.material_version_id"),title:hr(e.title),body:yn(e.body),entity_ids:dr(e.entity_ids,"thesis.entity_ids"),visibility:mr(e.visibility),closed:tt(e.closed,"thesis.closed"),closing_note:pr(e.closing_note),author_kind:P(e.author_kind,"thesis.author_kind"),author_ref:P(e.author_ref,"thesis.author_ref")};if(e.entity_stances!==void 0){if(!Array.isArray(e.entity_stances))throw p("thesis.entity_stances must be an array");n.entity_stances=e.entity_stances.map(i=>{if(!g(i))throw p("thesis.entity_stances contains invalid entry");let s=v(i.entity_id,"entity_stances.entity_id");if(!n.entity_ids.includes(s))throw p("entity stance must reference a thesis entity");if(!["unknown","bullish","bearish"].includes(i.stance))throw p("thesis.entity_stances contains invalid stance");return{entity_id:s,stance:i.stance}})}return{thesis:n}}r(z,"thesisResponse");function ar(t){let e=z(t);if(!g(t)||!g(t.author))throw p("response must contain author");let n=t.author,i={id:v(n.id,"author.id"),kind:P(n.kind,"author.kind"),display_name:P(n.display_name,"author.display_name"),avatar_url:P(n.avatar_url,"author.avatar_url"),username:P(n.username,"author.username")};if(!Array.isArray(t.entities))throw p("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw p("entities must match thesis.entity_ids");let s=t.entities.map((o,a)=>{if(!g(o))throw p(`entities[${a}] must be an object`);let c={id:v(o.id,`entities[${a}].id`),ticker:P(o.ticker,`entities[${a}].ticker`),name:P(o.name,`entities[${a}].name`),icon_url:P(o.icon_url,`entities[${a}].icon_url`),kind:P(o.kind,`entities[${a}].kind`)};if(c.id!==e.thesis.entity_ids[a])throw p("entities must preserve thesis.entity_ids order");return c});return{thesis:e.thesis,author:i,entities:s}}r(ar,"thesisGetResponse");function cr(t,e,n){if(!g(t)||!g(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw p("invalid Signal history response");let i=t.research,s={state:P(i.state,"research.state"),pending_work:et(i.pending_work,"research.pending_work"),read_complete:tt(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(s.last_attempt_ms=et(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(s.last_completed_ms=et(i.last_completed_ms,"research.last_completed_ms"));let o=t.entries.map(c=>{if(!g(c)||!g(c.signal)||!g(c.signal.source))throw p("entry must include a Signal and source");let u=c.signal,d=u.source,m=v(u.thesis_id,"signal.thesis_id");if(m!==e)throw p("Signal belongs to another Thesis");let f=Rt(c.cursor,"entry.cursor"),T={title:P(d.title,"source.title")};d.url!==void 0&&(T.url=P(d.url,"source.url")),d.published_at_ms!==void 0&&(T.published_at_ms=et(d.published_at_ms,"source.published_at_ms"));let x={id:v(u.id,"signal.id"),thesis_id:m,author_version_id:v(u.author_version_id,"signal.author_version_id"),statement_snapshot:Rt(u.statement_snapshot,"signal.statement_snapshot"),stance:P(u.stance,"signal.stance"),explanation:P(u.explanation,"signal.explanation"),information_kind:P(u.information_kind,"signal.information_kind"),source:T};if(u.evidence_excerpt!==void 0){if(!g(u.evidence_excerpt))throw p("invalid evidence excerpt");x.evidence_excerpt={text:Rt(u.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:tt(u.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:tt(u.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:v(c.feed_entry_id,"feed_entry_id"),cursor:f,signal:x}}),a=P(t.next_cursor,"next_cursor");if(a&&a!==o[o.length-1]?.cursor)throw p("next_cursor must match the final entry");return{research:s,entries:o,next_cursor:a}}r(cr,"thesisSignalsResponse");function et(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw p(e+" must be a nonnegative safe integer");return t}r(et,"responseNonnegativeInteger");function Rt(t,e){let n=P(t,e);if(!n.trim())throw p(e+" must be nonempty");return n}r(Rt,"responseNonemptyText");function hn(t){if(!nr.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw y("request_id must be a non-zero RFC 4122 UUID");return t}r(hn,"requireRequestID");function S(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw y(`${e} must be a positive int64 decimal string`);if(BigInt(t)>tr)throw y(`${e} must be a positive int64 decimal string`);return t}r(S,"requireID");var fe=100;function fn(t,e){if(!Array.isArray(t))throw y(`${e} must be an array`);if(t.length>fe)throw y(`${e} must contain at most ${fe} IDs`);return t.map((n,i)=>S(n,`${e}[${i}]`))}r(fn,"requireIDs");function ur(t){if(!Array.isArray(t))throw y("tickers must be an array");if(t.length>100)throw y("tickers must contain at most 100 values");return t.map((e,n)=>{let i=G(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw y(`tickers[${n}] must be non-empty`);return i})}r(ur,"requireTickers");function ye(t){let e=G(t,"body");if(e.trim().length===0)throw y("body must not be blank");if(mn.encode(e).byteLength>65536)throw y("body must be at most 65536 UTF-8 bytes");return e}r(ye,"requireBody");function kt(t){let e=G(t,"title");if(mn.encode(e).byteLength>500)throw y("title must be at most 500 UTF-8 bytes");return e}r(kt,"requireTitle");function nt(t){let e=G(t,"visibility");if(e!=="public"&&e!=="private")throw y("visibility must be public or private");return e}r(nt,"requireVisibility");function lr(t){let e=G(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw y("mode must be reformat, shorten, or enrich")}r(lr,"requireRewriteMode");function G(t,e){if(typeof t!="string")throw y(`${e} must be a string`);if(ir.test(t))throw y(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw y(`${e} must not contain NUL`);return t}r(G,"requireText");function v(t,e){if(typeof t=="number")throw p(`${e} must be a decimal string; numeric IDs are unsafe`);try{return S(t,e)}catch{throw p(`${e} must be a positive int64 decimal string`)}}r(v,"responseID");function dr(t,e){if(!Array.isArray(t))throw p(`${e} must be an array`);if(t.length>fe)throw p(`${e} must contain at most ${fe} IDs`);return t.map((n,i)=>v(n,`${e}[${i}]`))}r(dr,"responseIDs");function P(t,e){try{return G(t,e)}catch{throw p(`${e} must be valid text`)}}r(P,"responseText");function pr(t){try{return G(t,"note")}catch{throw p("thesis.closing_note must be valid text")}}r(pr,"responseClosingNote");function tt(t,e){if(typeof t!="boolean")throw p(`${e} must be boolean`);return t}r(tt,"responseBoolean");function mr(t){try{return nt(t)}catch{throw p("thesis.visibility must be public or private")}}r(mr,"responseVisibility");function yn(t){try{return ye(t)}catch{throw p("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}r(yn,"responseBody");function hr(t){try{return kt(t)}catch{throw p("response title must be valid text at most 500 UTF-8 bytes")}}r(hr,"responseTitle");function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(g,"isRecord");function y(t){return new l("INVALID_ARGUMENT",t,400)}r(y,"invalidArgument");function p(t){return new l("INVALID_RESPONSE",t,502)}r(p,"invalidResponse");var fr="https://api-llm.prd.alva.ai",yr="https://data-tools.prd.space.id";function wt(t){return typeof t=="object"&&t!==null}r(wt,"isRecord");function it(t,e){if(!wt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}r(it,"stringField");function gr(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let i=it(t,"code");i&&(e.code=i)}else if(wt(t)){let i=it(t,"code"),s=it(t,"name"),o=it(t,"message");i&&(e.code=i),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(i=>!!i);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}r(gr,"describeCause");function br(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",n={};t instanceof Error?(n.name=t.name,n.message=t.message):n.message=String(t);let{message:i,details:s}=gr(wt(t)?t.cause:void 0);return s&&(n.cause=s),{message:i?`${e}; cause: ${i}`:e,details:n}}r(br,"describeFetchFailure");var rt=class{static{r(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;originInboxPath;_fs;_run;_deploy;_serviceAccount;_release;_feed;_forYou;_automation;_playbooks;_secrets;_sdk;_dataSkills;_playbookSkills;_comments;_remix;_screenshot;_user;_trading;_portfolio;_arraysJwt;_notifications;_notificationPreferences;_subscriptions;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_steward;_tradingPairs;_theses;constructor(e){this.baseUrl=e.baseUrl??fr,this.arraysBaseUrl=e.arraysBaseUrl??yr,this.viewer_token=e.viewer_token,this.pbsvToken=e.pbsvToken,this.apiKey=e.apiKey,this.gaClientId=e.gaClientId,this.gaSessionId=e.gaSessionId,this.utmParams=e.utmParams,this.signal=e.signal,this.originSessionId=e.originSessionId,this.originSessionKind=e.originSessionKind,this.originInboxPath=e.originInboxPath}get fs(){return this._fs??=new ke(this)}get run(){return this._run??=new we(this)}get deploy(){return this._deploy??=new Se(this)}get serviceAccount(){return this._serviceAccount??=new Te(this)}get release(){return this._release??=new Ae(this)}get feed(){return this._feed??=new Ee(this)}get automation(){return this._automation??=new Q(this)}get playbooks(){return this._playbooks??=new qe(this)}get secrets(){return this._secrets??=new xe(this)}get sdk(){return this._sdk??=new Ne(this)}get dataSkills(){return this._dataSkills??=new De(this)}get playbookSkills(){return this._playbookSkills??=new Ue(this)}get comments(){return this._comments??=new Fe(this)}get remix(){return this._remix??=new Ge(this)}get screenshot(){return this._screenshot??=new Le(this)}get user(){return this._user??=new Oe(this)}get trading(){return this._trading??=new Me(this)}get portfolio(){return this._portfolio??=new $e(this)}get arraysJwt(){return this._arraysJwt??=new je(this)}get notifications(){return this._notifications??=new Be(this)}get notificationPreferences(){return this._notificationPreferences??=new Qe(this)}get subscriptions(){return this._subscriptions??=new Ve(this)}get alerts(){return this._alerts??=new V(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new We(this)}get feedback(){return this._feedback??=new Ye(this)}get functions(){return this._functions??=new He(this)}get credits(){return this._credits??=new Ke(this)}get markets(){return this._markets??=new W(this)}get tradingPairs(){return this._tradingPairs??=new K(this)}get schedules(){return this._schedules??=new Y(this)}get steward(){return this._steward??=new H(this)}get theses(){return this._theses??=new J(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new l("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get forYou(){return this._forYou??=new B(this)}async _request(e,n,i){let o=`${i?.baseUrl??this.baseUrl}${n}`;if(i?.query){let C=new URLSearchParams;for(let[N,st]of Object.entries(i.query))st!=null&&C.set(N,String(st));let O=C.toString();O&&(o+=`?${O}`)}let a={};i?.noAuth||(this.pbsvToken?(a.Authorization=`Bearer ${this.pbsvToken}`,a["X-Pbsv"]="1"):this.viewer_token?a["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(a["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(a["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(a["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(a["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!i?.noAuth&&(a["X-Alva-Origin-Session-Id"]=this.originSessionId);let c;i?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",c=i.rawBody):i?.jsonBody!==void 0?(a["Content-Type"]="application/json",c=i.jsonBody):i?.body!==void 0&&(a["Content-Type"]="application/json",c=JSON.stringify(i.body));let u,d=i?.timeoutMs,m=i?.signal??this.signal;if(m?.aborted)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let f=d!==void 0?new AbortController:void 0,T=!1,x,ge;f&&d!==void 0&&(m&&(ge=r(()=>f.abort(m.reason),"abortListener"),m.addEventListener("abort",ge,{once:!0})),x=setTimeout(()=>{T=!0,f.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let St={method:e,headers:a,body:c,signal:f?.signal??m};d!==void 0&&(St.timeout=d);try{u=await fetch(o,St)}catch(C){if(m?.aborted&&!T)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(T)throw new l("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let O=br(C);throw new l("NETWORK_ERROR",O.message,0,{method:e,path:n,...O.details})}finally{ge&&m&&m.removeEventListener("abort",ge),x!==void 0&&clearTimeout(x)}if(!u.ok){let C="";try{C=await Promise.resolve(u.text())}catch{C=""}if((u.headers.get("content-type")??"").includes("application/json")&&C)try{let N=JSON.parse(C);if(N.error)throw new l(N.error.code??"UNKNOWN",N.error.message??`HTTP ${u.status}`,u.status)}catch(N){if(N instanceof l)throw N}throw new l("UNKNOWN",`HTTP ${u.status}: ${C.slice(0,200)}`,u.status)}if(u.status===204)return;let Tt=(u.headers.get("content-type")??"").toLowerCase();return Tt.includes("application/json")||Tt.includes("+json")?u.json():u.arrayBuffer()}};var _r="0.31.0";dt();return kn(Pr);})();
|
|
290
329
|
//# sourceMappingURL=browser.global.js.map
|