@alva-ai/toolkit 0.28.0-beta.0 → 0.28.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.
@@ -250,5 +250,5 @@ mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
250
250
  }`.trim(),Un=`
251
251
  query ToolkitAgentChannel {
252
252
  viewer { channels { id kind } }
253
- }`.trim(),Gn=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Ln=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Dn=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,On={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},L=class{constructor(e){this.client=e}client;static{i(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=Xe(e.channelId),r=[],s=null,o=new Set;for(;;){let a=(await this.graphql(Fn,{channelId:n,after:s})).viewer?.channel?.schedules;if(!a?.edges)throw Ft();for(let d of a.edges){if(!d?.node)throw y();r.push(Ke(d.node))}if(a.pageInfo?.hasNextPage!==!0)return r;let u=a.pageInfo.endCursor;if(!u||o.has(u))throw y();o.add(u),s=u}}async put(e){this.client._requireAuth();let n={channelId:Xe(e.channelId),name:Gt(e.name),definition:{...Mn(e.rule,e.bounds),message:{text:Bn(e.text)}}},s=(await this.graphql(Je,{input:n})).updateChannelSchedule?.schedule;if(!s)throw y();return Ke(s)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.graphql(Je,{input:{...Nt(e),lifecycle:"REMOVED"}})).updateChannelSchedule?.deleted!==!0)throw y()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(Un)).viewer?.channels?.find(r=>r.kind==="AGENT")?.id;if(!n)throw Ft();return n}async manage(e,n){this.client._requireAuth();let s=(await this.graphql(Je,{input:{...Nt(n),lifecycle:e}})).updateChannelSchedule?.schedule;if(!s)throw y();return Ke(s)}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors?.length){let s=r.errors.map(d=>d.extensions?.code),l=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=l?On[l]:void 0,u=l!==void 0&&a!==void 0?l:"GRAPHQL_ERROR";throw new c(u,r.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",a??502,{errors:r.errors})}if(!r.data)throw y();return r.data}};function Mn(t,e){let n=jn(e);switch(t.kind){case"after":if(n)throw h("after does not accept recurring bounds");let r=Date.now()+Lt(t.duration,1),s=Math.ceil(r/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw h("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw h("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:Ze(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:Qn(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw h("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}i(Mn,"ruleInput");function jn(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=Ze(t.startsAt)),t.until!==void 0&&(e.untilMs=Ze(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw h("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}i(jn,"boundsInput");function Ke(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw y();let r=t.bounds??{},s=t.message??{},o={name:t.name,rule:$n(t.rule),bounds:{...r.startsAtMs!=null?{startsAt:T(r.startsAtMs,!0)}:{},...r.untilMs!=null?{until:T(r.untilMs,!0)}:{},...r.maxOccurrences!=null?{maxOccurrences:et(r.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:et(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:T(t.nextFireAtMs,!0)}:{},createdAt:T(t.createdAtMs),updatedAt:T(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw y();let a={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!a)throw y();o.failure={code:a,...t.failureAtMs!=null?{at:T(t.failureAtMs)}:{}}}return o}i(Ke,"fromWireSchedule");function $n(t){switch(t.kind){case"AT":if(t.atMs==null)throw y();return{kind:"at",timestamp:T(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw y();return{kind:"every",interval:`PT${et(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw y();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw y()}i($n,"fromWireRule");function Nt(t){return{channelId:Xe(t.channelId),name:Gt(t.name)}}i(Nt,"managementInput");function Xe(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw h("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 h("channelId must be a positive integer");return e}i(Xe,"channelID");function Gt(t){if(!Gn.test(t))throw h("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}i(Gt,"requireName");function Bn(t){let e=Wn(t);if(e===void 0||!t.trim()||e>16*1024)throw h("text must be 1..16384 UTF-8 bytes");return t}i(Bn,"requireText");function Qn(t){let e=Lt(t,60);if(e%1e3!==0)throw h("duration must resolve to whole seconds");return e/1e3}i(Qn,"durationSeconds");function Lt(t,e){let n=Dn.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 h("duration must be a positive ISO 8601 day/time duration");let[r,s,o,l]=n.slice(1,5).map(d=>BigInt(d??"0")),a=((r*24n+s)*60n+o)*60n+l;if(a<BigInt(e))throw h(`duration must be at least ${e} whole seconds`);let u=Number(a*1000n);if(!Number.isSafeInteger(u))throw h("duration is out of range");return u}i(Lt,"durationMilliseconds");function Ze(t){let e=Ln.exec(t);if(!e)throw h("timestamp must be RFC3339 with a timezone");let[n,r,s,o,l,a]=e.slice(1,7).map(Number),u=Number(e[8]??0),d=Number(e[9]??0),p=new Date(Date.UTC(n,r,0)).getUTCDate(),_=Date.parse(t);if(!Number.isFinite(_)||n<1||n>9999||r<1||r>12||s<1||s>p||o>23||l>59||a>59||u>23||d>59)throw h("timestamp must be RFC3339 with a timezone");return _}i(Ze,"timestampMilliseconds");function T(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw y();let n=new Date(t);if(Number.isNaN(n.getTime()))throw y();return n.toISOString()}i(T,"timestampString");function et(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw h(`${e} exceeds JavaScript safe integer range`);return n}i(et,"safeInteger");function h(t){return new c("INVALID_ARGUMENT",t,400)}i(h,"invalid");function Wn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}i(Wn,"utf8Size");function Ft(){return new c("NOT_FOUND","channel schedule target not found",404)}i(Ft,"scheduleNotFound");function y(){return new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}i(y,"scheduleEmptyResponse");function A(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(A,"isRecord");function m(t){return typeof t=="string"&&t.trim()!==""?t:void 0}i(m,"stringValue");function Fe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}i(Fe,"numberValue");function Ge(t){return t===void 0?void 0:t.trim().toUpperCase()}i(Ge,"upper");function Ot(t){return t.split("_")}i(Ot,"pairParts");function Yn(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":Ot(e)[1]?.toLowerCase()??""}i(Yn,"inferInstrumentType");function Vn(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}i(Vn,"inferUnderlyingType");function Dt(t,e){let n=m(t.trading_pair)??m(t.tradingPair)??m(t.symbol);if(n===void 0)return;let r=m(t.type),s=Ot(n),o=m(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),l=m(t.market)??m(t.exchange)??s[0]??"",a=m(t.quote)??s[s.length-1]??"",u=m(t.instrument_type)??m(t.instrumentType)??Yn(r,n),d=m(t.underlying_type)??m(t.underlyingType)??Vn(r);return{symbol:o,tradingPair:n,market:l,instrumentType:u,...d===void 0?{}:{underlyingType:d},quote:a,...r===void 0?{}:{type:r},...m(t.description)===void 0?{}:{description:m(t.description)},...Fe(t.fee_rate)===void 0?Fe(t.feeRate)===void 0?{}:{feeRate:Fe(t.feeRate)}:{feeRate:Fe(t.fee_rate)},...m(t.symbol_icon_url)===void 0?m(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:m(t.symbolIconUrl)}:{symbolIconUrl:m(t.symbol_icon_url)}}}i(Dt,"normalizeCandidate");function Hn(t){if(!A(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>A(s)?[Dt(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let r=[];for(let s of n){if(!A(s))continue;let o=m(s.symbol),l=s.trading_pairs;if(Array.isArray(l)){for(let a of l)if(!(!A(a)||!Array.isArray(a.pairs)))for(let u of a.pairs){if(!A(u))continue;let d=Dt({...u,instrument_type:u.instrument_type??a.instrument_type},o);d!==void 0&&r.push(d)}}}return r}i(Hn,"flattenResponse");function zn(t,e){let n=e.trim();return t.tradingPair===n?!0:Ge(t.symbol)===Ge(n)}i(zn,"matchesQuery");function Ue(t,e){return e===void 0||Ge(t)===Ge(e)}i(Ue,"matchesFilter");function Jn(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}i(Jn,"dedupe");function Kn(t){let e=A(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}}i(Kn,"resolveFilters");function Xn(t,e){let n=t.split("_"),r=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,l=n.at(-1);return!r||!s||!o||!l?{symbol:t,...e}:{symbol:o,market:e.market??r,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??l}}i(Xn,"pairSearchParams");var D=class{constructor(e){this.client=e}client;static{i(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=A(e)?e.symbol:void 0,r=typeof n=="string"?n.trim():"";if(!r)throw new c("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:r,strict:!0}}),o=Jn(Hn(s)).filter(a=>zn(a,r)).filter(a=>Ue(a.market,e.market)).filter(a=>Ue(a.instrumentType,e.instrumentType)).filter(a=>Ue(a.underlyingType,e.underlyingType)).filter(a=>Ue(a.quote,e.quote)),l=e.limit;return l!==void 0&&o.length>l?{query:r,candidates:o.slice(0,l),truncated:!0}:{query:r,candidates:o}}async resolve(e){let n=A(e)?e:{},r=typeof n.pair=="string"?n.pair.trim():void 0,s=Kn(e),o=r===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:Xn(r,s),l=await this.search(o),a=r===void 0?l.candidates:l.candidates.filter(u=>u.tradingPair===r);if(a.length!==1)throw new c(a.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",a.length===0?`no canonical trading pair matched "${r??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,a.length===0?404:409,{query:r??o.symbol,candidateCount:a.length,candidates:a.slice(0,50),...a.length>50?{truncated:!0}:{}});return a[0]}};var Zn="https://api-llm.prd.alva.ai",er="https://data-tools.prd.space.id";function tt(t){return typeof t=="object"&&t!==null}i(tt,"isRecord");function Le(t,e){if(!tt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}i(Le,"stringField");function tr(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let r=Le(t,"code");r&&(e.code=r)}else if(tt(t)){let r=Le(t,"code"),s=Le(t,"name"),o=Le(t,"message");r&&(e.code=r),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(r=>!!r);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}i(tr,"describeCause");function nr(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:r,details:s}=tr(tt(t)?t.cause:void 0);return s&&(n.cause=s),{message:r?`${e}; cause: ${r}`:e,details:n}}i(nr,"describeFetchFailure");var De=class{static{i(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;_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;_tradingPairs;constructor(e){this.baseUrl=e.baseUrl??Zn,this.arraysBaseUrl=e.arraysBaseUrl??er,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}get fs(){return this._fs??=new oe(this)}get run(){return this._run??=new ae(this)}get deploy(){return this._deploy??=new le(this)}get serviceAccount(){return this._serviceAccount??=new ce(this)}get release(){return this._release??=new ue(this)}get feed(){return this._feed??=new pe(this)}get automation(){return this._automation??=new F(this)}get playbooks(){return this._playbooks??=new ye(this)}get secrets(){return this._secrets??=new he(this)}get sdk(){return this._sdk??=new ge(this)}get dataSkills(){return this._dataSkills??=new be(this)}get playbookSkills(){return this._playbookSkills??=new ke(this)}get comments(){return this._comments??=new Pe(this)}get remix(){return this._remix??=new Re(this)}get screenshot(){return this._screenshot??=new _e(this)}get user(){return this._user??=new Ee(this)}get trading(){return this._trading??=new ve(this)}get portfolio(){return this._portfolio??=new Ae(this)}get arraysJwt(){return this._arraysJwt??=new Se(this)}get notifications(){return this._notifications??=new Te(this)}get notificationPreferences(){return this._notificationPreferences??=new we(this)}get subscriptions(){return this._subscriptions??=new Ce(this)}get alerts(){return this._alerts??=new U(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new qe(this)}get feedback(){return this._feedback??=new Ie(this)}get functions(){return this._functions??=new xe(this)}get credits(){return this._credits??=new Ne(this)}get markets(){return this._markets??=new G(this)}get tradingPairs(){return this._tradingPairs??=new D(this)}get schedules(){return this._schedules??=new L(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new c("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get forYou(){return this._forYou??=new N(this)}async _request(e,n,r){let o=`${r?.baseUrl??this.baseUrl}${n}`;if(r?.query){let P=new URLSearchParams;for(let[E,Oe]of Object.entries(r.query))Oe!=null&&P.set(E,String(Oe));let C=P.toString();C&&(o+=`?${C}`)}let l={};r?.noAuth||(this.pbsvToken?(l.Authorization=`Bearer ${this.pbsvToken}`,l["X-Pbsv"]="1"):this.viewer_token?l["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(l["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(l["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(l["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(l["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!r?.noAuth&&(l["X-Alva-Origin-Session-Id"]=this.originSessionId);let a;r?.rawBody!==void 0?(l["Content-Type"]="application/octet-stream",a=r.rawBody):r?.jsonBody!==void 0?(l["Content-Type"]="application/json",a=r.jsonBody):r?.body!==void 0&&(l["Content-Type"]="application/json",a=JSON.stringify(r.body));let u,d=r?.timeoutMs,p=r?.signal??this.signal;if(p?.aborted)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let _=d!==void 0?new AbortController:void 0,O=!1,w,te;_&&d!==void 0&&(p&&(te=i(()=>_.abort(p.reason),"abortListener"),p.addEventListener("abort",te,{once:!0})),w=setTimeout(()=>{O=!0,_.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let nt={method:e,headers:l,body:a,signal:_?.signal??p};d!==void 0&&(nt.timeout=d);try{u=await fetch(o,nt)}catch(P){if(p?.aborted&&!O)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(O)throw new c("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let C=nr(P);throw new c("NETWORK_ERROR",C.message,0,{method:e,path:n,...C.details})}finally{te&&p&&p.removeEventListener("abort",te),w!==void 0&&clearTimeout(w)}if(!u.ok){let P="";try{P=await Promise.resolve(u.text())}catch{P=""}if((u.headers.get("content-type")??"").includes("application/json")&&P)try{let E=JSON.parse(P);if(E.error)throw new c(E.error.code??"UNKNOWN",E.error.message??`HTTP ${u.status}`,u.status)}catch(E){if(E instanceof c)throw E}throw new c("UNKNOWN",`HTTP ${u.status}: ${P.slice(0,200)}`,u.status)}if(u.status===204)return;let rt=(u.headers.get("content-type")??"").toLowerCase();return rt.includes("application/json")||rt.includes("+json")?u.json():u.arrayBuffer()}};var rr="0.28.0-beta.0";We();return Wt(ir);})();
253
+ }`.trim(),Gn=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Ln=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Dn=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,On={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},L=class{constructor(e){this.client=e}client;static{i(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=Xe(e.channelId),r=[],s=null,o=new Set;for(;;){let a=(await this.graphql(Fn,{channelId:n,after:s})).viewer?.channel?.schedules;if(!a?.edges)throw Ft();for(let d of a.edges){if(!d?.node)throw y();r.push(Ke(d.node))}if(a.pageInfo?.hasNextPage!==!0)return r;let u=a.pageInfo.endCursor;if(!u||o.has(u))throw y();o.add(u),s=u}}async put(e){this.client._requireAuth();let n={channelId:Xe(e.channelId),name:Gt(e.name),definition:{...Mn(e.rule,e.bounds),message:{text:Bn(e.text)}}},s=(await this.graphql(Je,{input:n})).updateChannelSchedule?.schedule;if(!s)throw y();return Ke(s)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.graphql(Je,{input:{...Nt(e),lifecycle:"REMOVED"}})).updateChannelSchedule?.deleted!==!0)throw y()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(Un)).viewer?.channels?.find(r=>r.kind==="AGENT")?.id;if(!n)throw Ft();return n}async manage(e,n){this.client._requireAuth();let s=(await this.graphql(Je,{input:{...Nt(n),lifecycle:e}})).updateChannelSchedule?.schedule;if(!s)throw y();return Ke(s)}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors?.length){let s=r.errors.map(d=>d.extensions?.code),l=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=l?On[l]:void 0,u=l!==void 0&&a!==void 0?l:"GRAPHQL_ERROR";throw new c(u,r.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",a??502,{errors:r.errors})}if(!r.data)throw y();return r.data}};function Mn(t,e){let n=jn(e);switch(t.kind){case"after":if(n)throw h("after does not accept recurring bounds");let r=Date.now()+Lt(t.duration,1),s=Math.ceil(r/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw h("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw h("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:Ze(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:Qn(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw h("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}i(Mn,"ruleInput");function jn(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=Ze(t.startsAt)),t.until!==void 0&&(e.untilMs=Ze(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw h("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}i(jn,"boundsInput");function Ke(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw y();let r=t.bounds??{},s=t.message??{},o={name:t.name,rule:$n(t.rule),bounds:{...r.startsAtMs!=null?{startsAt:T(r.startsAtMs,!0)}:{},...r.untilMs!=null?{until:T(r.untilMs,!0)}:{},...r.maxOccurrences!=null?{maxOccurrences:et(r.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:et(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:T(t.nextFireAtMs,!0)}:{},createdAt:T(t.createdAtMs),updatedAt:T(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw y();let a={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!a)throw y();o.failure={code:a,...t.failureAtMs!=null?{at:T(t.failureAtMs)}:{}}}return o}i(Ke,"fromWireSchedule");function $n(t){switch(t.kind){case"AT":if(t.atMs==null)throw y();return{kind:"at",timestamp:T(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw y();return{kind:"every",interval:`PT${et(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw y();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw y()}i($n,"fromWireRule");function Nt(t){return{channelId:Xe(t.channelId),name:Gt(t.name)}}i(Nt,"managementInput");function Xe(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw h("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 h("channelId must be a positive integer");return e}i(Xe,"channelID");function Gt(t){if(!Gn.test(t))throw h("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}i(Gt,"requireName");function Bn(t){let e=Wn(t);if(e===void 0||!t.trim()||e>16*1024)throw h("text must be 1..16384 UTF-8 bytes");return t}i(Bn,"requireText");function Qn(t){let e=Lt(t,60);if(e%1e3!==0)throw h("duration must resolve to whole seconds");return e/1e3}i(Qn,"durationSeconds");function Lt(t,e){let n=Dn.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 h("duration must be a positive ISO 8601 day/time duration");let[r,s,o,l]=n.slice(1,5).map(d=>BigInt(d??"0")),a=((r*24n+s)*60n+o)*60n+l;if(a<BigInt(e))throw h(`duration must be at least ${e} whole seconds`);let u=Number(a*1000n);if(!Number.isSafeInteger(u))throw h("duration is out of range");return u}i(Lt,"durationMilliseconds");function Ze(t){let e=Ln.exec(t);if(!e)throw h("timestamp must be RFC3339 with a timezone");let[n,r,s,o,l,a]=e.slice(1,7).map(Number),u=Number(e[8]??0),d=Number(e[9]??0),p=new Date(Date.UTC(n,r,0)).getUTCDate(),_=Date.parse(t);if(!Number.isFinite(_)||n<1||n>9999||r<1||r>12||s<1||s>p||o>23||l>59||a>59||u>23||d>59)throw h("timestamp must be RFC3339 with a timezone");return _}i(Ze,"timestampMilliseconds");function T(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw y();let n=new Date(t);if(Number.isNaN(n.getTime()))throw y();return n.toISOString()}i(T,"timestampString");function et(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw h(`${e} exceeds JavaScript safe integer range`);return n}i(et,"safeInteger");function h(t){return new c("INVALID_ARGUMENT",t,400)}i(h,"invalid");function Wn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}i(Wn,"utf8Size");function Ft(){return new c("NOT_FOUND","channel schedule target not found",404)}i(Ft,"scheduleNotFound");function y(){return new c("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}i(y,"scheduleEmptyResponse");function A(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(A,"isRecord");function m(t){return typeof t=="string"&&t.trim()!==""?t:void 0}i(m,"stringValue");function Fe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}i(Fe,"numberValue");function Ge(t){return t===void 0?void 0:t.trim().toUpperCase()}i(Ge,"upper");function Ot(t){return t.split("_")}i(Ot,"pairParts");function Yn(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":Ot(e)[1]?.toLowerCase()??""}i(Yn,"inferInstrumentType");function Vn(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}i(Vn,"inferUnderlyingType");function Dt(t,e){let n=m(t.trading_pair)??m(t.tradingPair)??m(t.symbol);if(n===void 0)return;let r=m(t.type),s=Ot(n),o=m(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),l=m(t.market)??m(t.exchange)??s[0]??"",a=m(t.quote)??s[s.length-1]??"",u=m(t.instrument_type)??m(t.instrumentType)??Yn(r,n),d=m(t.underlying_type)??m(t.underlyingType)??Vn(r);return{symbol:o,tradingPair:n,market:l,instrumentType:u,...d===void 0?{}:{underlyingType:d},quote:a,...r===void 0?{}:{type:r},...m(t.description)===void 0?{}:{description:m(t.description)},...Fe(t.fee_rate)===void 0?Fe(t.feeRate)===void 0?{}:{feeRate:Fe(t.feeRate)}:{feeRate:Fe(t.fee_rate)},...m(t.symbol_icon_url)===void 0?m(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:m(t.symbolIconUrl)}:{symbolIconUrl:m(t.symbol_icon_url)}}}i(Dt,"normalizeCandidate");function Hn(t){if(!A(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>A(s)?[Dt(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let r=[];for(let s of n){if(!A(s))continue;let o=m(s.symbol),l=s.trading_pairs;if(Array.isArray(l)){for(let a of l)if(!(!A(a)||!Array.isArray(a.pairs)))for(let u of a.pairs){if(!A(u))continue;let d=Dt({...u,instrument_type:u.instrument_type??a.instrument_type},o);d!==void 0&&r.push(d)}}}return r}i(Hn,"flattenResponse");function zn(t,e){let n=e.trim();return t.tradingPair===n?!0:Ge(t.symbol)===Ge(n)}i(zn,"matchesQuery");function Ue(t,e){return e===void 0||Ge(t)===Ge(e)}i(Ue,"matchesFilter");function Jn(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}i(Jn,"dedupe");function Kn(t){let e=A(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}}i(Kn,"resolveFilters");function Xn(t,e){let n=t.split("_"),r=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,l=n.at(-1);return!r||!s||!o||!l?{symbol:t,...e}:{symbol:o,market:e.market??r,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??l}}i(Xn,"pairSearchParams");var D=class{constructor(e){this.client=e}client;static{i(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=A(e)?e.symbol:void 0,r=typeof n=="string"?n.trim():"";if(!r)throw new c("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:r,strict:!0}}),o=Jn(Hn(s)).filter(a=>zn(a,r)).filter(a=>Ue(a.market,e.market)).filter(a=>Ue(a.instrumentType,e.instrumentType)).filter(a=>Ue(a.underlyingType,e.underlyingType)).filter(a=>Ue(a.quote,e.quote)),l=e.limit;return l!==void 0&&o.length>l?{query:r,candidates:o.slice(0,l),truncated:!0}:{query:r,candidates:o}}async resolve(e){let n=A(e)?e:{},r=typeof n.pair=="string"?n.pair.trim():void 0,s=Kn(e),o=r===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:Xn(r,s),l=await this.search(o),a=r===void 0?l.candidates:l.candidates.filter(u=>u.tradingPair===r);if(a.length!==1)throw new c(a.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",a.length===0?`no canonical trading pair matched "${r??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,a.length===0?404:409,{query:r??o.symbol,candidateCount:a.length,candidates:a.slice(0,50),...a.length>50?{truncated:!0}:{}});return a[0]}};var Zn="https://api-llm.prd.alva.ai",er="https://data-tools.prd.space.id";function tt(t){return typeof t=="object"&&t!==null}i(tt,"isRecord");function Le(t,e){if(!tt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}i(Le,"stringField");function tr(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let r=Le(t,"code");r&&(e.code=r)}else if(tt(t)){let r=Le(t,"code"),s=Le(t,"name"),o=Le(t,"message");r&&(e.code=r),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(r=>!!r);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}i(tr,"describeCause");function nr(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:r,details:s}=tr(tt(t)?t.cause:void 0);return s&&(n.cause=s),{message:r?`${e}; cause: ${r}`:e,details:n}}i(nr,"describeFetchFailure");var De=class{static{i(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;_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;_tradingPairs;constructor(e){this.baseUrl=e.baseUrl??Zn,this.arraysBaseUrl=e.arraysBaseUrl??er,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}get fs(){return this._fs??=new oe(this)}get run(){return this._run??=new ae(this)}get deploy(){return this._deploy??=new le(this)}get serviceAccount(){return this._serviceAccount??=new ce(this)}get release(){return this._release??=new ue(this)}get feed(){return this._feed??=new pe(this)}get automation(){return this._automation??=new F(this)}get playbooks(){return this._playbooks??=new ye(this)}get secrets(){return this._secrets??=new he(this)}get sdk(){return this._sdk??=new ge(this)}get dataSkills(){return this._dataSkills??=new be(this)}get playbookSkills(){return this._playbookSkills??=new ke(this)}get comments(){return this._comments??=new Pe(this)}get remix(){return this._remix??=new Re(this)}get screenshot(){return this._screenshot??=new _e(this)}get user(){return this._user??=new Ee(this)}get trading(){return this._trading??=new ve(this)}get portfolio(){return this._portfolio??=new Ae(this)}get arraysJwt(){return this._arraysJwt??=new Se(this)}get notifications(){return this._notifications??=new Te(this)}get notificationPreferences(){return this._notificationPreferences??=new we(this)}get subscriptions(){return this._subscriptions??=new Ce(this)}get alerts(){return this._alerts??=new U(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new qe(this)}get feedback(){return this._feedback??=new Ie(this)}get functions(){return this._functions??=new xe(this)}get credits(){return this._credits??=new Ne(this)}get markets(){return this._markets??=new G(this)}get tradingPairs(){return this._tradingPairs??=new D(this)}get schedules(){return this._schedules??=new L(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new c("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get forYou(){return this._forYou??=new N(this)}async _request(e,n,r){let o=`${r?.baseUrl??this.baseUrl}${n}`;if(r?.query){let P=new URLSearchParams;for(let[E,Oe]of Object.entries(r.query))Oe!=null&&P.set(E,String(Oe));let C=P.toString();C&&(o+=`?${C}`)}let l={};r?.noAuth||(this.pbsvToken?(l.Authorization=`Bearer ${this.pbsvToken}`,l["X-Pbsv"]="1"):this.viewer_token?l["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(l["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(l["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(l["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(l["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!r?.noAuth&&(l["X-Alva-Origin-Session-Id"]=this.originSessionId);let a;r?.rawBody!==void 0?(l["Content-Type"]="application/octet-stream",a=r.rawBody):r?.jsonBody!==void 0?(l["Content-Type"]="application/json",a=r.jsonBody):r?.body!==void 0&&(l["Content-Type"]="application/json",a=JSON.stringify(r.body));let u,d=r?.timeoutMs,p=r?.signal??this.signal;if(p?.aborted)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let _=d!==void 0?new AbortController:void 0,O=!1,w,te;_&&d!==void 0&&(p&&(te=i(()=>_.abort(p.reason),"abortListener"),p.addEventListener("abort",te,{once:!0})),w=setTimeout(()=>{O=!0,_.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let nt={method:e,headers:l,body:a,signal:_?.signal??p};d!==void 0&&(nt.timeout=d);try{u=await fetch(o,nt)}catch(P){if(p?.aborted&&!O)throw new c("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(O)throw new c("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let C=nr(P);throw new c("NETWORK_ERROR",C.message,0,{method:e,path:n,...C.details})}finally{te&&p&&p.removeEventListener("abort",te),w!==void 0&&clearTimeout(w)}if(!u.ok){let P="";try{P=await Promise.resolve(u.text())}catch{P=""}if((u.headers.get("content-type")??"").includes("application/json")&&P)try{let E=JSON.parse(P);if(E.error)throw new c(E.error.code??"UNKNOWN",E.error.message??`HTTP ${u.status}`,u.status)}catch(E){if(E instanceof c)throw E}throw new c("UNKNOWN",`HTTP ${u.status}: ${P.slice(0,200)}`,u.status)}if(u.status===204)return;let rt=(u.headers.get("content-type")??"").toLowerCase();return rt.includes("application/json")||rt.includes("+json")?u.json():u.arrayBuffer()}};var rr="0.28.0";We();return Wt(ir);})();
254
254
  //# sourceMappingURL=browser.global.js.map