corsair 0.2.8 → 0.2.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-KUNMGJBS.js +68 -0
- package/dist/chunk-PQ2CF2OI.js +1 -0
- package/dist/connect-WQP2HEZK.js +1 -0
- package/dist/core.js +1 -1
- package/dist/http.d.ts +21 -2
- package/dist/http.js +1 -1
- package/dist/hub.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{loop-WKE7RM6V.js → loop-WZ4TYWHC.js} +1 -1
- package/dist/oauth.js +1 -1
- package/dist/orm.js +1 -1
- package/dist/{setup-HPBFZDKM.js → setup-NPC34BWA.js} +1 -1
- package/dist/{setup-introspect-KTU63HR6.js → setup-introspect-JLFD4CIT.js} +1 -1
- package/dist/setup.js +1 -1
- package/dist/tunnel.js +1 -1
- package/package.json +3 -3
- package/dist/chunk-QUO2PWXT.js +0 -1
- package/dist/chunk-ZO7W7OP2.js +0 -68
- package/dist/connect-NCLCRUFH.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as ue,e as de,f as le,g as ye}from"./chunk-XPXWKPFZ.js";var Je=Symbol.for("corsair:internal"),O=class extends Error{constructor(t="Invalid corsair instance"){super(t),this.name="InvalidCorsairInstanceError"}};function H(e){return typeof e=="object"&&e!==null}function fe(e){if(!H(e)||!Array.isArray(e.plugins)||typeof e.kek!="string"||typeof e.multiTenancy!="boolean")return!1;if(e.database===void 0)return!0;if(!H(e.database))return!1;let t=e.database.db;return typeof t=="object"&&t!==null&&typeof t.selectFrom=="function"}function ge(e){if(!e||typeof e!="object")return;let n=Object.getOwnPropertyDescriptor(e,Je)?.value;return fe(n)?n:void 0}function Qe(e,t){let n=ge(e);if(!n)throw t?.()??new O;return n}function pe(e,t){return e.plugins.find(n=>n.id===t)}function ze(e,t,n){let r=pe(e,t);if(!r)throw n(`Plugin '${t}' not found`);return r}function He(e){return"withTenant"in e&&typeof e.withTenant=="function"}function Ge(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="function"?(...r)=>Reflect.apply(n,e,r):void 0}var G={oauth_2:{integration:["client_id","client_secret","redirect_url"],account:["access_token","refresh_token","expires_at","scope","webhook_signature"]},api_key:{integration:[],account:["api_key","webhook_signature"]},bot_token:{integration:[],account:["bot_token","webhook_signature"]},managed:{integration:[],account:["access_token","refresh_token","expires_at","scope","webhook_signature"]},managed_pricing:{integration:[],account:[]}};function me(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"||e==="managed"||e==="managed_pricing"}function qe(e){let t=e.options?.authType;return me(t)?t:void 0}function jt(e){return e==="managed_pricing"}function Ye(e,t){let n=e.authConfig,r=G[t].account,i=n?.[t]?.account??[];return[...r,...i]}function Wt(e,t){let n=e.authConfig,r=G[t].integration,i=n?.[t]?.integration??[];return[...r,...i]}import{createCipheriv as we,createDecipheriv as be,randomBytes as v,scrypt as Xe}from"crypto";import{promisify as Ve}from"util";var he=Ve(Xe),$="aes-256-gcm",Ce=12,j=16,et=16,q=32;function Y(){return v(q).toString("base64")}async function X(e,t){let n=v(et),r=await he(t,n,q),i=v(Ce),o=we($,r,i,{authTagLength:j}),a=Buffer.concat([o.update(e,"utf8"),o.final()]),l=o.getAuthTag();return[n.toString("base64"),i.toString("base64"),l.toString("base64"),a.toString("base64")].join(":")}var tt=1024,B=new Map;async function F(e,t){let n=B.get(e);if(n&&n.kek===t)return n.dek;let r=await nt(e,t);return!B.has(e)&&B.size>=tt&&B.delete(B.keys().next().value),B.set(e,{kek:t,dek:r}),r}async function nt(e,t){let[n,r,i,o]=e.split(":");if(!n||!r||!i||!o)throw new Error("Invalid encrypted DEK format");let a=Buffer.from(n,"base64"),l=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),b=Buffer.from(o,"base64"),u=await he(t,a,q),s=be($,u,l,{authTagLength:j});return s.setAuthTag(p),Buffer.concat([s.update(b),s.final()]).toString("utf8")}function V(e,t){let n=Buffer.from(t,"base64"),r=v(Ce),i=we($,n,r,{authTagLength:j}),o=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[r.toString("base64"),a.toString("base64"),o.toString("base64")].join(":")}function ee(e,t){let[n,r,i]=e.split(":");if(!n||!r||!i)throw new Error("Invalid encrypted data format");let o=Buffer.from(t,"base64"),a=Buffer.from(n,"base64"),l=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),b=be($,o,a,{authTagLength:j});return b.setAuthTag(l),Buffer.concat([b.update(p),b.final()]).toString("utf8")}function te(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=V(i,t);return n}function W(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=ee(i,t);return n}function Jt(e,t,n){let r=W(e,t);return te(r,n)}import{v7 as rt}from"uuid";function P(){return rt()}function L(e,t){return e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t.tenantId).where("integration_id","=",t.integrationId).orderBy("created_at","asc").orderBy("id","asc")}async function K(e,t){return L(e,t).executeTakeFirst()}async function it(e){let t=!1;for(;;){let n=await e.database.db.selectFrom("corsair_integrations").selectAll().where("name","=",e.integrationName).executeTakeFirst();if(!n){if(!t&&e.ensureProvisioned){t=!0,await e.ensureProvisioned();continue}throw new Error(`Integration "${e.integrationName}" not found. Make sure to create the integration first.`)}let r={tenantId:e.tenantId,integrationId:n.id},i=e.account?await ct({db:e.database.db,kek:e.account.kek,...r,ref:e.account.ref}):await K(e.database.db,r);if(!i){if(!t&&e.ensureProvisioned){t=!0,await e.ensureProvisioned();continue}throw new Error(`Account not found for tenant "${e.tenantId}" and integration "${e.integrationName}". Make sure to create the account first.`)}return{integrationId:n.id,accountId:i.id,integration:{id:n.id,config:n.config,dek:n.dek??null},account:{id:i.id,config:i.config,dek:i.dek??null}}}}async function sn(e){let{integrationId:t,accountId:n}=await it(e);return{integrationId:t,accountId:n}}var S=class extends Error{code;accounts;constructor(t,n,r=[]){super(n),this.name="AccountSelectionError",this.code=t,this.accounts=r}};function ie(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e??{}}var re=e=>({id:e.id,config:e.config,dek:e.dek??null});async function U(e,t){let n=ie(e.config);if(!e.dek||!n?.account_ref)return{};try{let r=W(n,await F(e.dek,t));return{ref:r.account_ref,label:r.account_label}}catch{return{}}}async function cn(e,t,n){if(e.id===t)return!0;let{ref:r,label:i}=await U(e,n);return r===t||i?.toLowerCase()===t.toLowerCase()}async function un(e,t,n){let r=n?await e.selectFrom("corsair_accounts").select(["config","dek"]).where("id","=",t).executeTakeFirst():void 0;return{id:t,...r&&n?await U(r,n):{}}}function ot(e){let t=new Set(e),n=1;for(;t.has(`Account ${n}`);)n++;return`Account ${n}`}var Te=(e,t)=>Promise.all(e.map(async n=>({...re(n),...await U(n,t)})));async function Ae(e){return Te(await L(e.db,e).execute(),e.kek)}var at=e=>e.label??e.ref??e.id,M=({id:e,ref:t,label:n})=>({id:e,ref:t,label:n});async function dn(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();if(!t)return[];let n=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",e.tenantId).where("integration_id","=",t.id).execute();return n.length<2?n:(await Ae({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(i=>({id:i.id,label:i.label??i.ref}))}async function ln(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();return t?(await Ae({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(M):[]}async function st(e,t){return(await e.selectFrom("corsair_integrations").select("name").where("id","=",t).executeTakeFirst())?.name??t}async function ct(e){let t=await L(e.db,e).execute();if(t.length===0)return;if(!e.ref&&t.length===1)return re(t[0]);let n=e.ref?t.find(u=>u.id===e.ref):void 0;if(n)return re(n);let r=await Te(t,e.kek),i=e.ref?.toLowerCase(),o=e.ref?r.find(u=>u.ref===e.ref):void 0;if(o)return o;let a=e.ref?r.filter(u=>u.label?.toLowerCase()===i):[];if(a.length===1)return a[0];let l=await st(e.db,e.integrationId);if(a.length>1)throw new S("account_required",`Label "${e.ref}" matches ${a.length} accounts for "${l}" (tenant "${e.tenantId}"): ${a.map(u=>u.ref??u.id).join(", ")}. Name one by its id.`,a.map(M));let p=r.map(at).join(", "),b=r.map(M);throw e.ref?new S("account_not_found",`No account "${e.ref}" for "${l}" (tenant "${e.tenantId}"). Accounts: ${p}.`,b):new S("account_required",`Plugin "${l}" has ${r.length} accounts for tenant "${e.tenantId}": ${p}. Name one with withTenant(tenantId, { accounts: { ${l}: "<account>" } }).`,b)}var ut=5;async function yn(e){let{database:t,kek:n,tenantId:r}=e;return t.db.transaction().execute(async i=>{let o=i.selectFrom("corsair_integrations").select(["id"]).where("name","=",e.integrationName);t.isPg===!0&&(o=o.forUpdate());let a=await o.executeTakeFirst();if(!a)throw new Error(`Integration '${e.integrationName}' not found. Run setupCorsair first.`);let l=await L(i,{tenantId:r,integrationId:a.id}).execute();if(!e.identity)return l[0]?{accountId:l[0].id,created:!1}:ke(i,a.id,r,n);let p=await Promise.all(l.map(async w=>({row:w,...await U(w,n)}))),b=e.identity.label===void 0&&e.nameNew?{...e.identity,label:ot(p.map(w=>w.label))}:e.identity;if(e.rowId){let w=p.find(c=>c.row.id===e.rowId);if(!w)throw new S("account_not_found",`Account "${e.rowId}" is no longer connected for "${e.integrationName}" (tenant "${r}").`);return w.ref?{accountId:w.row.id,created:!1}:(await ne(i,w.row,b,n),{accountId:w.row.id,created:!1})}let u=p.filter(w=>!w.ref),s=e.hubAccounts?.[0];u.length===1&&Object.keys(ie(u[0].row.config)).length>0&&s&&s.id!==b.id&&!p.some(w=>w.ref===s.id)&&(await ne(i,u[0].row,s,n),u[0].ref=s.id,u[0].label=s.label);let y=p.find(w=>w.ref===b.id),m=y??p.find(w=>!w.ref)??(e.allowMany?void 0:p[0]);if(m){if(!y||b.label&&m.label!==b.label){let w=!y&&m.ref!==void 0;await ne(i,m.row,b,n,w)}return{accountId:m.row.id,created:!1}}if(l.length>=ut)throw new S("account_limit",`Account limit reached: tenant "${r}" already has ${l.length} accounts for "${e.integrationName}".`,p.map(({row:w,ref:c,label:d})=>M({id:w.id,ref:c,label:d})));return ke(i,a.id,r,n,b)})}async function xe(e,t,n){let{account_label:r,...i}=t;return te({...i,account_ref:n.id,...n.label?{account_label:n.label}:{}},e)}async function ne(e,t,n,r,i=!1){let o=t.dek?await F(t.dek,r):Y(),a=ie(t.config),l=i?{}:t.dek?W(a,o):a;await e.updateTable("corsair_accounts").set({config:await xe(o,l,n),dek:t.dek??await X(o,r),updated_at:new Date}).where("id","=",t.id).execute()}async function ke(e,t,n,r,i){let o=Y(),a=new Date,l=P();return await e.insertInto("corsair_accounts").values({id:l,created_at:a,updated_at:a,tenant_id:n,integration_id:t,config:i?await xe(o,{},i):{},dek:await X(o,r)}).execute(),{accountId:l,created:!0}}import{SqliteAdapter as dt,sql as Oe}from"kysely";import{z as A}from"zod";var oe="_corsair_enc";function Ee(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t[oe]=="string"&&Object.keys(t).length===1}function ae(e,t){return{[oe]:V(JSON.stringify(e),t)}}function se(e,t){let n=_e(e);return Ee(n)?JSON.parse(ee(n[oe],t)):n}async function mn(e,t,n){let r=await e.selectFrom("corsair_accounts").select("dek").where("id","=",t).executeTakeFirst();if(!r?.dek)throw new Error(`No DEK found for account "${t}". Initialize the account first.`);return F(r.dek,n)}async function wn(e,t,n,r){let i=await e.selectFrom("corsair_entities").select(["id","data"]).where("account_id","=",t).execute();for(let a of i){let l=Ie(a.data,n,r);l&&await e.updateTable("corsair_entities").set({data:l,updated_at:new Date}).where("id","=",a.id).execute()}let o=await e.selectFrom("corsair_events").select(["id","payload"]).where("account_id","=",t).execute();for(let a of o){let l=Ie(a.payload,n,r);l&&await e.updateTable("corsair_events").set({payload:l,updated_at:new Date}).where("id","=",a.id).execute()}}function Ie(e,t,n){let r=_e(e);if(Ee(r))return ae(se(r,t),n)}function _e(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}import{sql as _}from"kysely";function Z(e){return e.replace(/'/g,"''")}function De(e){let t=Z(e);return _`data->>'${_.raw(t)}'`}function Fe(e){let t=Z(e);return _`(data->>'${_.raw(t)}')::numeric`}function Pe(e){let t=Z(e);return _`(data->>'${_.raw(t)}')::boolean`}function Se(e){let t=Z(e);return _`(data->>'${_.raw(t)}')::timestamptz`}import{sql as J}from"kysely";function Re(e){return e.replace(/'/g,"''").replace(/\\/g,"\\\\")}function Be(e){let t=Re(e);return J`CAST(json_extract(data, '$.${J.raw(t)}') AS REAL)`}function Ke(e){let t=Re(e);return J`json_extract(data, '$.${J.raw(t)}')`}var lt={number:e=>Fe(e),booleanEquals:(e,t)=>Oe`${Pe(e)} = ${t}`,timestamp:e=>Se(e)},yt={number:e=>Be(e),booleanEquals:(e,t)=>Oe`json_extract(data, ${`$.${e}`}) = ${t?1:0}`,timestamp:e=>Ke(e)};function ft(e){return e.getExecutor().adapter instanceof dt?yt:lt}function gt(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function ve(e){let t=e;for(;t;){if(t instanceof A.ZodOptional||t instanceof A.ZodNullable){t=t._def.innerType;continue}if(t instanceof A.ZodDefault){t=t._def.innerType;continue}break}return t}function Ne(e){if(typeof e=="string")return"string";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}function ce(e){let[t]=e;return t&&e.every(n=>n===t)?t:void 0}function $e(e){let t=ve(e);if(t instanceof A.ZodString)return"string";if(t instanceof A.ZodNumber)return"number";if(t instanceof A.ZodBoolean)return"boolean";if(t instanceof A.ZodDate)return"date";if(t instanceof A.ZodEnum)return ce(t.options.map(Ne));if(t instanceof A.ZodLiteral)return ce([...t.values].map(Ne));if(t instanceof A.ZodUnion)return ce(t.options.filter(n=>!(n instanceof A.ZodNull)).map(n=>$e(n)))}function pt(e){let t=ve(e);if(!(t instanceof A.ZodObject))return{};let n=t.shape,r={};for(let[i,o]of Object.entries(n)){let a=$e(o);a&&(r[i]=a)}return r}function mt(e,t,n){if(typeof n=="string")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;"equals"in r&&typeof r.equals=="string"&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function wt(e,t,n){if(typeof n=="number")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="number"&&(e=e.where(t,"=",r.equals)),typeof r.gt=="number"&&(e=e.where(t,">",r.gt)),typeof r.gte=="number"&&(e=e.where(t,">=",r.gte)),typeof r.lt=="number"&&(e=e.where(t,"<",r.lt)),typeof r.lte=="number"&&(e=e.where(t,"<=",r.lte)),Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function bt(e,t,n){if(typeof n=="boolean")return e.where(t(n));if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="boolean"&&(e=e.where(t(r.equals)))}return e}function ht(e,t,n){if(n instanceof Date)return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;if(r.equals instanceof Date&&(e=e.where(t,"=",r.equals)),r.before instanceof Date&&(e=e.where(t,"<",r.before)),r.after instanceof Date&&(e=e.where(t,">",r.after)),Array.isArray(r.between)&&r.between.length===2){let[i,o]=r.between;i instanceof Date&&(e=e.where(t,">=",i)),o instanceof Date&&(e=e.where(t,"<=",o))}}return e}function Ct(e,t,n,r,i){return r==="number"?wt(e,t.number(n),i):r==="boolean"?bt(e,o=>t.booleanEquals(n,o),i):r==="date"?ht(e,t.timestamp(n),i):mt(e,De(n),i)}function kt(e,t,n){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;return"equals"in r&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in)),e}return e.where(t,"=",n)}function Tt(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function je(e,t){return Array.isArray(t)?e("account_id","in",t):e("account_id","=",t)}function R(e,t,n){let r=e.selectFrom("corsair_entities").selectAll().where(i=>je(i,t)).where("entity_type","=",n);return Array.isArray(t)?r.orderBy("created_at").orderBy("id"):r}function We(e,t,n,r,i,o,a){let l=pt(i),p=new Map,b=async c=>{if(!o?.kek)throw new Error("encryptDataAtRest requires kek");let d=await e.selectFrom("corsair_accounts").select("dek").where("id","=",c).executeTakeFirst();if(!d?.dek)throw new Error(`No DEK found for account "${c}". Initialize the account first.`);let f=p.get(c);if(f&&f.wrapped===d.dek)return f.dek;let g=await F(d.dek,o.kek);return p.set(c,{wrapped:d.dek,dek:g}),g};async function u(c,d){let f=gt(c.data);return o&&(f=se(f,d??await b(c.account_id))),{...c,data:i.parse(f)}}async function s(){let c=a?await a():[];return c.length<2?{ids:await t()}:{ids:c.map(d=>d.id),labels:new Map(c.map(d=>[d.id,d.label??d.id]))}}async function y(c){let{ids:d,labels:f}=await s(),C=await R(e,d,n).where("entity_id","=",c).execute();return Array.isArray(d)?(C.sort((x,I)=>d.indexOf(x.account_id)-d.indexOf(I.account_id)),{row:C[0],labels:f}):{row:C[0],labels:f}}async function m(c,d){let f=new Map;return o&&await Promise.all([...new Set(c.map(g=>g.account_id))].map(async g=>f.set(g,await b(g)))),Promise.all(c.map(async g=>{let C=await u(g,f.get(g.account_id)),x=d?.get(g.account_id);return x?{...C,account:x}:C}))}async function w(c,d){return o?ae(d,await b(c)):d}return{findByEntityId:async c=>{let{row:d,labels:f}=await y(c);return d?(await m([d],f))[0]:null},existsByEntityId:async c=>{let{ids:d}=await s();return await R(e,d,n).select("id").where("entity_id","=",c).executeTakeFirst()!==void 0},findIdByEntityId:async c=>{let{row:d}=await y(c);return d?.id??null},findById:async c=>{let{ids:d,labels:f}=await s(),g=await R(e,d,n).where("id","=",c).executeTakeFirst();return g?(await m([g],f))[0]:null},findManyByEntityIds:async c=>{if(c.length===0)return[];let{ids:d,labels:f}=await s(),g=await R(e,d,n).where("entity_id","in",c).execute();return m(g,f)},list:async c=>{let{ids:d,labels:f}=await s(),g=R(e,d,n);typeof c?.limit=="number"&&(g=g.limit(c.limit)),typeof c?.offset=="number"&&(g=g.offset(c.offset));let C=await g.execute();return m(C,f)},search:async c=>{if(o&&c.data&&typeof c.data=="object"&&Object.keys(c.data).length>0)throw new Error("Entity JSON field search cannot run while encryptDataAtRest is enabled. The stored document is ciphertext.");let{ids:d,labels:f}=await s(),g=R(e,d,n),C=new Set(["data","limit","offset"]);for(let[I,D]of Object.entries(c))C.has(I)||D===void 0||(g=kt(g,I,D));if(c.data&&typeof c.data=="object")for(let[I,D]of Object.entries(c.data)){if(D===void 0)continue;let z=l[I]??"string";g=Ct(g,ft(e),I,z,D)}typeof c.limit=="number"&&(g=g.limit(c.limit)),typeof c.offset=="number"&&(g=g.offset(c.offset));let x=await g.execute();return m(x,f)},upsertByEntityId:async(c,d)=>{let f=await t(),g=i.parse(d),C=await w(f,g),x=new Date,I=await R(e,f,n).select("id").where("entity_id","=",c).executeTakeFirst();if(I?.id){let Ze=await e.updateTable("corsair_entities").set({version:r,data:C,updated_at:x}).where("id","=",I.id).returningAll().executeTakeFirstOrThrow();return u(Ze)}let D=P(),z=await e.insertInto("corsair_entities").values({id:D,created_at:x,updated_at:x,account_id:f,entity_id:c,entity_type:n,version:r,data:C}).returningAll().executeTakeFirstOrThrow();return u(z)},deleteById:async c=>{let d=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",d).where("entity_type","=",n).where("id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},deleteByEntityId:async c=>{let d=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",d).where("entity_type","=",n).where("entity_id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},count:async()=>{let{ids:c}=await s(),d=await e.selectFrom("corsair_entities").select(f=>f.fn.countAll().as("count")).where(f=>je(f,c)).where("entity_type","=",n).executeTakeFirst();return Tt(d?.count)}}}var At={corsair_integrations:ue,corsair_accounts:de,corsair_entities:le,corsair_events:ye};function xt(e){return At[e]}function Me(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function h(e){if(!e)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function N(e){if(!e)return[];let t=[];for(let n in e){let r=n,i=e[r];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let o=i;"in"in o&&Array.isArray(o.in)?t.push({field:r,operator:"in",value:o.in}):"like"in o&&typeof o.like=="string"&&t.push({field:r,operator:"like",value:o.like})}else t.push({field:r,value:i})}return t}function E(e,t){if(!t?.length)return e;let n=e;for(let r of t){let i=r.operator??"=";n=n.where(r.field,i,r.value)}return n}function It(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function Q(e,t){let n=xt(t),r=()=>(h(e),e),i=()=>r().db.selectFrom(t),o=()=>r().db.insertInto(t),a=()=>r().db.updateTable(t),l=()=>r().db.deleteFrom(t);function p(u){let s={};for(let[y,m]of Object.entries(u))s[y]=Me(m);return n.parse(s)}function b(u){let s={};for(let[y,m]of Object.entries(u))s[y]=Me(m);return n.parse(s)}return{findById:async u=>{h(e);let s=i().selectAll();s=E(s,[{field:"id",value:u}]);let y=await s.executeTakeFirst();return y?p(y):null},findOne:async u=>{h(e);let s=i().selectAll();s=E(s,N(u));let y=await s.executeTakeFirst();return y?p(y):null},findMany:async u=>{h(e);let s=i().selectAll();return s=E(s,N(u?.where)),typeof u?.limit=="number"&&(s=s.limit(u.limit)),typeof u?.offset=="number"&&(s=s.offset(u.offset)),(await s.execute()).map(m=>p(m))},create:async u=>{h(e);let s=new Date,y={id:u.id??P(),created_at:s,updated_at:s,...u},m=await o().values(y).returningAll().executeTakeFirst();return m?p(m):b(y)},update:async(u,s)=>{h(e);let y={...s,updated_at:new Date},m=a().set(y).returningAll();m=E(m,[{field:"id",value:u}]);let w=await m.executeTakeFirst();return w?p(w):null},updateMany:async(u,s)=>{h(e);let y={...s,updated_at:new Date},m=i().select("id");m=E(m,N(u));let w=await m.execute();for(let c of w){let d=a().set(y);d=E(d,[{field:"id",value:c.id}]),await d.execute()}return w.length},delete:async u=>{h(e);let s=l();s=E(s,[{field:"id",value:u}]);let y=await s.executeTakeFirst();return Number(y?.numDeletedRows??0)>0},deleteMany:async u=>{h(e);let s=l();s=E(s,N(u));let y=await s.executeTakeFirst();return Number(y?.numDeletedRows??0)},count:async u=>{h(e);let s=i().select(m=>m.fn.countAll().as("count"));s=E(s,N(u));let y=await s.executeTakeFirst();return It(y?.count)}}}function Et(e){let t=Q(e,"corsair_integrations");return{...t,findByName:n=>t.findOne({name:n}),upsertByName:async(n,r)=>{let i=await t.findOne({name:n});return i?await t.update(i.id,r):t.create({...r,name:n})}}}function _t(e){let t=Q(e,"corsair_accounts");return{...t,findByTenantAndIntegration:async(n,r)=>{h(e);let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!i)return null;let o=await K(e.db,{tenantId:n,integrationId:i.id});return o?t.findOne({id:o.id,tenant_id:n,integration_id:i.id}):null},listByTenant:(n,r)=>t.findMany({where:{tenant_id:n},limit:r?.limit,offset:r?.offset}),upsertByTenantAndIntegration:async(n,r,i)=>{h(e);let o=await K(e.db,{tenantId:n,integrationId:r});return o?await t.update(o.id,i):t.create({...i,tenant_id:n,integration_id:r})}}}function Dt(e){let t=Q(e,"corsair_entities");return{...t,findByEntityId:({accountId:n,entityType:r,entityId:i})=>t.findOne({account_id:n,entity_type:r,entity_id:i}),findManyByEntityIds:async({accountId:n,entityType:r,entityIds:i})=>i.length===0?[]:(h(e),await e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","in",i).execute()),listByScope:({accountId:n,entityType:r,limit:i,offset:o})=>t.findMany({where:{account_id:n,entity_type:r},limit:i,offset:o}),searchByEntityId:async({accountId:n,entityType:r,query:i,limit:o,offset:a})=>{h(e);let l=e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","like",`%${i}%`);return typeof o=="number"&&(l=l.limit(o)),typeof a=="number"&&(l=l.offset(a)),await l.execute()},upsertByEntityId:async({accountId:n,entityType:r,entityId:i,version:o,data:a})=>{let l=await t.findOne({account_id:n,entity_type:r,entity_id:i});return l?await t.update(l.id,{version:o,data:a}):t.create({account_id:n,entity_type:r,entity_id:i,version:o,data:a})},deleteByEntityId:async({accountId:n,entityType:r,entityId:i})=>{h(e);let o=await e.db.deleteFrom("corsair_entities").where("account_id","=",n).where("entity_type","=",r).where("entity_id","=",i).executeTakeFirst();return Number(o.numDeletedRows)>0}}}function Ft(e){let t=Q(e,"corsair_events");return{...t,listByAccount:(n,r)=>t.findMany({where:{account_id:n},limit:r?.limit,offset:r?.offset}),listByStatus:(n,r)=>{let i={status:n};return r?.accountId&&(i.account_id=r.accountId),t.findMany({where:i,limit:r?.limit,offset:r?.offset})},listPending:n=>{let r={status:"pending"};return n?.accountId&&(r.account_id=n.accountId),t.findMany({where:r,limit:n?.limit??100})},updateStatus:(n,r)=>t.update(n,{status:r})}}function Le(e){return{integrations:Et(e),accounts:_t(e),entities:Dt(e),events:Ft(e)}}function Pt(e){if(e.encryptDataAtRest===!0)return{encryptDataAtRest:!0,kek:e.kek??""}}function St(e,t,n,r,i,o){let a=null;async function l(){if(a!==null)return a;h(e);let p=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t.integrationName).executeTakeFirst();if(!p)throw new Error(`Integration "${t.integrationName}" not found. Make sure to create the integration first.`);let b=await K(e.db,{tenantId:t.tenantId,integrationId:p.id});if(!b)throw new Error(`Account not found for tenant "${t.tenantId}" and integration "${t.integrationName}". Make sure to create the account first.`);return a=b.id,a}return h(e),We(e.db,l,n,r,i,o)}function Ue(e){let{database:t,integrationName:n,schema:r,tenantId:i}=e,o=Pt(e),a=Le(t),l={tenantId:i,integrationName:n},p=null;async function b(){if(p!==null)return p;h(t);let s=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!s)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let y=await K(t.db,{tenantId:i,integrationId:s.id});if(!y)throw new Error(`Account not found for tenant "${i}" and integration "${n}". Make sure to create the account first.`);return p=y.id,p}let u={};for(let[s,y]of Object.entries(r.entities))u[s]=St(t,l,s,r.version,y,o);return{...u,$orm:a,$integrationName:n,$tenantId:i,$getAccountId:b}}function jn(e,t){let n=Le(e);return{$tenantId:t,$orm:n,listAccounts:r=>n.accounts.listByTenant(t,r),findAccountByIntegration:r=>n.accounts.findByTenantAndIntegration(t,r),listEntities:async r=>{h(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(l=>l.id),a=e.db.selectFrom("corsair_entities").selectAll().where("account_id","in",o);return r?.entityType&&(a=a.where("entity_type","=",r.entityType)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},listEvents:async r=>{h(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(l=>l.id),a=e.db.selectFrom("corsair_events").selectAll().where("account_id","in",o);return r?.status&&(a=a.where("status","=",r.status)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},forIntegration:r=>Ue({database:e,integrationName:r.integrationName,schema:r.schema,tenantId:t,encryptDataAtRest:r.encryptDataAtRest,kek:r.kek})}}function Wn(e,t){return{forTenant:n=>Ue({database:e,integrationName:t.integrationName,schema:t.schema,tenantId:n,encryptDataAtRest:t.encryptDataAtRest,kek:t.kek})}}export{O as a,H as b,ge as c,Qe as d,ze as e,He as f,Ge as g,G as h,qe as i,jt as j,Ye as k,Wt as l,q as m,Y as n,X as o,F as p,V as q,ee as r,te as s,W as t,Jt as u,Ee as v,ae as w,se as x,mn as y,wn as z,P as A,K as B,sn as C,S as D,U as E,cn as F,un as G,dn as H,ln as I,ct as J,ut as K,yn as L,We as M,At as N,Le as O,Ue as P,jn as Q,Wn as R};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$ as b,_ as a,aa as c}from"./chunk-KUNMGJBS.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{c as createHubConnectSession,b as createHubConnectSessionForPlugin,a as postHubConnectSession};
|
package/dist/core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$b as P,Ab as E,Bb as F,Cb as G,D as n,Db as H,E as o,Eb as I,F as p,G as q,Sb as J,Tb as K,Ub as L,Vb as M,Wb as N,_b as O,a,ac as Q,b,ba as r,bb as B,bc as R,c,ca as s,cc as S,dc as T,ec as U,fa as t,fc as V,ga as u,gc as W,ha as v,hc as X,ia as w,ic as Y,ja as x,jc as Z,ka as y,kc as _,la as z,lc as $,ma as A,mc as aa,nc as ba,oc as ca,pc as da,qc as ea,rc as fa,sc as ga,yb as C,zb as D}from"./chunk-
|
|
1
|
+
import{$b as P,Ab as E,Bb as F,Cb as G,D as n,Db as H,E as o,Eb as I,F as p,G as q,Sb as J,Tb as K,Ub as L,Vb as M,Wb as N,_b as O,a,ac as Q,b,ba as r,bb as B,bc as R,c,ca as s,cc as S,dc as T,ec as U,fa as t,fc as V,ga as u,gc as W,ha as v,hc as X,ia as w,ic as Y,ja as x,jc as Z,ka as y,kc as _,la as z,lc as $,ma as A,mc as aa,nc as ba,oc as ca,pc as da,qc as ea,rc as fa,sc as ga,yb as C,zb as D}from"./chunk-KUNMGJBS.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import{D as m,h as d,n as e,o as f,p as g,q as h,r as i,s as j,t as k,u as l}from"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{m as AccountSelectionError,B as AuthMissingError,d as BASE_AUTH_FIELDS,da as CORSAIR_INTERNAL,H as CloudApiError,C as CorsairKekMissingError,D as DB_METHOD_RISK,R as MS_GRAPH_API_BASE,A as ManagementApiError,M as OAuthRefreshError,s as PermissionRequiredError,a as ProviderDisplayNames,t as ReadonlyForbiddenError,c as ReconnectRequiredError,v as activeMode,Y as asRecord,z as assertModeAllows,y as assertReadonlyAllowed,G as callPluginDb,V as collectPluginWebhookMatchers,I as corsairCloud,o as createAccountKeyManager,ea as createCorsair,n as createIntegrationKeyManager,F as decodeDbArgs,ca as decodePubSubData,k as decryptConfig,g as decryptDEK,i as decryptWithDEK,E as encodeDbArgs,j as encryptConfig,f as encryptDEK,h as encryptWithDEK,L as exchangeCodeForTokens,$ as extractMicrosoftGraphValidationToken,ba as firstString,O as formatDocSchemaShape,b as formatProviderDisplayName,e as generateDEK,W as getHeader,N as getOAuthAccessToken,Q as googleChannelSubscribe,q as initializeAccountDEK,p as initializeIntegrationDEK,P as introspectPluginForDocs,aa as isMicrosoftGraphValidationHandshake,x as isReadonlyScopeActive,J as logEvent,K as logEventFromContext,T as matchWebhookPlugin,U as matchWebhookPluginAndTenant,S as msGraphSubscribe,l as reEncryptConfig,Z as readBodyRecord,_ as readQueryParam,r as resolveConnectLink,w as runReadonly,u as runWithMode,fa as shouldStartTunnel,ga as superviseTunnel,X as toExternalId};
|
package/dist/http.d.ts
CHANGED
|
@@ -138,14 +138,33 @@ declare const FileOutputSchema: z.ZodObject<{
|
|
|
138
138
|
not_requested: "not_requested";
|
|
139
139
|
over_limit: "over_limit";
|
|
140
140
|
}>>;
|
|
141
|
+
fileId: z.ZodOptional<z.ZodString>;
|
|
141
142
|
}, z.core.$strip>;
|
|
142
143
|
type FileOutput = z.infer<typeof FileOutputSchema>;
|
|
143
144
|
/** Default most bytes returned inline: under the 1 MB a hosted script result may carry, once base64 adds a third. */
|
|
144
145
|
declare const FILE_OUTPUT_MAX_BYTES = 700000;
|
|
146
|
+
/**
|
|
147
|
+
* Where a host keeps a file too large to return inline. Called synchronously
|
|
148
|
+
* with the bytes; returns the id the output carries as `fileId`, or nothing to
|
|
149
|
+
* leave the content out as before. The host stores the file after the call
|
|
150
|
+
* returns: on Corsair it holds the bytes and swaps the id for a Files id.
|
|
151
|
+
*/
|
|
152
|
+
type FileSink = (file: {
|
|
153
|
+
bytes: Uint8Array;
|
|
154
|
+
contentType: string;
|
|
155
|
+
filename?: string;
|
|
156
|
+
}) => string | null | undefined;
|
|
157
|
+
/**
|
|
158
|
+
* For a host: how toFileOutput finds the sink for the operation it is running
|
|
159
|
+
* in, usually an AsyncLocalStorage's getStore. Core keeps no async context of
|
|
160
|
+
* its own, so this module stays free of Node-only imports.
|
|
161
|
+
*/
|
|
162
|
+
declare function setFileSink(find: () => FileSink | undefined): void;
|
|
145
163
|
/**
|
|
146
164
|
* Shapes downloaded bytes as a `FileOutput`. The content goes in when it was
|
|
147
165
|
* asked for and fits `maxBytes`; the size and type are always reported, so a
|
|
148
|
-
* caller that got no content still knows what it would be.
|
|
166
|
+
* caller that got no content still knows what it would be. Over the limit, a
|
|
167
|
+
* host's sink (setFileSink) may keep the file and the output carries its `fileId`.
|
|
149
168
|
*
|
|
150
169
|
* A text file in UTF-8 comes back as `text` instead of base64, so a caller can
|
|
151
170
|
* read a CSV or JSON file as it is. A file served as application/octet-stream
|
|
@@ -230,4 +249,4 @@ declare function verifyHmacSignatureWithPrefix(payload: string | Buffer, secret:
|
|
|
230
249
|
declare function verifyHmacSha256Signature(payload: string, secret: string, timestamp: string, signature: string, maxAgeSeconds?: number): boolean;
|
|
231
250
|
declare function verifySlackSignature(payload: string, secret: string, timestamp: string, signature: string, maxAgeSeconds?: number): boolean;
|
|
232
251
|
|
|
233
|
-
export { ApiError, type ApiRequestOptions, type ApiResult, type BaseHandleWebhookResult, BaseWebhookHandler, type BinaryResponse, type DownloadDeps, type DownloadOptions, FILE_OUTPUT_MAX_BYTES, type FileInput, FileInputSchema, type FileOutput, FileOutputSchema, type OpenAPIConfig, type PublicDownload, type RateLimitConfig, type ResolveFileOptions, type ResolvedFile, UnsafeUrlError, type WebhookEventHandler, downloadPublicFile, isBlockedAddress, request, resolveFileInput, toFileOutput, verifyHmacSha256Signature, verifyHmacSignature, verifyHmacSignatureWithPrefix, verifySlackSignature };
|
|
252
|
+
export { ApiError, type ApiRequestOptions, type ApiResult, type BaseHandleWebhookResult, BaseWebhookHandler, type BinaryResponse, type DownloadDeps, type DownloadOptions, FILE_OUTPUT_MAX_BYTES, type FileInput, FileInputSchema, type FileOutput, FileOutputSchema, type FileSink, type OpenAPIConfig, type PublicDownload, type RateLimitConfig, type ResolveFileOptions, type ResolvedFile, UnsafeUrlError, type WebhookEventHandler, downloadPublicFile, isBlockedAddress, request, resolveFileInput, setFileSink, toFileOutput, verifyHmacSha256Signature, verifyHmacSignature, verifyHmacSignatureWithPrefix, verifySlackSignature };
|
package/dist/http.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-SOY77BN4.js";var ce=new Set(["apikey","xapikey","key","appkey","appid","token","apitoken","accesstoken","authtoken","clientsecret","secret","password"]);function C(t){let e=t;try{e=decodeURIComponent(t)}catch{e=t}return ce.has(e.toLowerCase().replace(/[-_]/g,""))}function ue(t){let e=t.indexOf("?");if(e===-1)return t;let n=t.indexOf("#",e),r=t.slice(0,e+1),i=n===-1?t.slice(e+1):t.slice(e+1,n),s=n===-1?"":t.slice(n),o=!1,a=i.split("&").map(l=>{if(!l)return l;let c=l.indexOf("="),f=c===-1?l:l.slice(0,c);return C(f)?(o=!0,`${f}=[REDACTED]`):l}).join("&");return o?r+a+s:t}function H(t){if(!t)return t;try{let e=/^[a-z]+:\/\//i.test(t),n=e?void 0:"http://localhost",r=new URL(t,n),i=!1;for(let s of[...r.searchParams.keys()])C(s)&&(r.searchParams.set(s,"[REDACTED]"),i=!0);return i?e?r.toString():r.pathname+r.search+r.hash:t}catch{return ue(t)}}function fe(t){let e=H(t.url),n=!1,r=t.query;if(t.query){r={...t.query};for(let i of Object.keys(r))C(i)&&(r[i]="[REDACTED]",n=!0)}return!n&&e===t.url?t:{...t,url:e,...n?{query:r}:{}}}var h=class extends Error{url;status;statusText;body;request;retryAfter;rateLimitReset;rateLimitRemaining;rateLimitLimit;constructor(e,n,r,i){super(r),this.name="ApiError",this.url=H(n.url),this.status=n.status,this.statusText=n.statusText,this.body=n.body,this.request=fe(e),this.retryAfter=i?.retryAfter,this.rateLimitReset=i?.rateLimitReset,this.rateLimitRemaining=i?.rateLimitRemaining,this.rateLimitLimit=i?.rateLimitLimit}isRateLimitError(){return this.status===429}};import{z as d}from"zod";import{lookup as de}from"dns/promises";import*as V from"http";import*as X from"https";import{pipeline as me,Readable as pe}from"stream";import*as T from"zlib";var he=3e4,ye=25*1024*1024,W=3,be=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function v(t){let e=t.split(".");if(e.length!==4)return;let n=0;for(let r of e){if(!/^\d{1,3}$/.test(r))return;let i=Number(r);if(i>255)return;n=n*256+i}return n}function G(t){let e=v(t);return e===void 0?!0:be.some(([n,r])=>{let i=v(n);if(i===void 0)return!1;let s=r===0?0:4294967295<<32-r>>>0;return(e&s)===(i&s)})}function ge(t){let e=t,n=e.indexOf("%");n!==-1&&(e=e.slice(0,n));let r=e.lastIndexOf(":");if(r===-1)return;let i=e.slice(r+1);if(i.includes(".")){let u=v(i);if(u===void 0)return;e=`${e.slice(0,r+1)}${(u>>>16).toString(16)}:${(u&65535).toString(16)}`}let s=e.split("::");if(s.length>2)return;let o=u=>u===""?[]:u.split(":").filter(R=>R!==""),a=o(s[0]??""),l=s.length===2?o(s[1]??""):[];if(![...a,...l].every(u=>/^[0-9a-fA-F]{1,4}$/.test(u)))return;if(s.length===1)return a.length===8?a.map(u=>Number.parseInt(u,16)):void 0;let c=8-a.length-l.length;return c<1?void 0:[...a,...Array(c).fill("0"),...l].map(u=>Number.parseInt(u,16))}function Re(t){let e=ge(t);if(!e)return!0;if(e.slice(0,5).every(r=>r===0)&&(e[5]===65535||e[5]===0)){let r=`${e[6]>>8}.${e[6]&255}.${e[7]>>8}.${e[7]&255}`;if(G(r))return!0}return!!(e.every(r=>r===0)||e.slice(0,7).every(r=>r===0)&&e[7]===1||(e[0]&65024)===64512||(e[0]&65472)===65152||(e[0]&65472)===65216||(e[0]&65280)===65280||e[0]===8194||e[0]===100&&e[1]===65435&&e.slice(2,6).every(r=>r===0)||e[0]===100&&e[1]===65435&&e[2]===1)}function J(t){let e=t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t;return e.includes(":")?Re(e):G(e)}var m=class extends Error{constructor(e){super(e),this.name="UnsafeUrlError"}};async function Te(t){return(await de(t,{all:!0,verbatim:!0})).map(n=>n.address)}function xe(t){return((e,n,r)=>{let i=r,s=typeof n=="object"&&n!==null&&n.all===!0,o=t.map(l=>({address:l,family:l.includes(":")?6:4}));if(o.length===0){i(new Error("No address to connect to."),"",0);return}if(s){i(null,o);return}let a=o[0];i(null,a.address,a.family)})}var Ae=(t,e,n)=>{let r=t.protocol==="https:",i=t.hostname.replace(/^\[|\]$/g,""),s={method:"GET",protocol:t.protocol,hostname:i,port:t.port===""?void 0:Number(t.port),path:`${t.pathname}${t.search}`,headers:{Accept:"*/*","Accept-Encoding":"identity"},lookup:xe(e),agent:!1,signal:n};return r&&(s.servername=i),new Promise((o,a)=>{let c=(r?X.request:V.request)(s,f=>{o({status:f.statusCode??0,headers:f.headers,body:f,cancel:()=>f.destroy()})});c.on("error",a),c.end()})};function we(t,e){return e?e.aborted?Promise.reject(e.reason):new Promise((n,r)=>{let i=()=>r(e.reason);e.addEventListener("abort",i,{once:!0}),t.then(s=>{e.removeEventListener("abort",i),n(s)},s=>{e.removeEventListener("abort",i),r(s)})}):t}async function z(t,e={},n){let r;try{r=new URL(t)}catch{throw new m("The file URL must be an absolute URL.")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new m("The file URL must use http or https.");let i=r.hostname.replace(/^\[|\]$/g,"");if(i==="")throw new m("The file URL must include a host.");let o=i.includes(":")||v(i)!==void 0?[i]:await we((e.resolve??Te)(i).catch(()=>{throw new m(`Could not resolve ${i}.`)}),n);if(o.length===0)throw new m(`Could not resolve ${i}.`);for(let a of o)if(J(a))throw new m(`The file URL points at ${i}, which resolves to a private or reserved address. Use a publicly reachable URL.`);return{url:r,addresses:o}}function Y(t,e){try{let n=new URL(t).pathname.split("/").pop();return n&&n.includes(".")?n:e}catch{return e}}function A(t,e){let n=t[e];return Array.isArray(n)?n[0]:n}function P(t){return new m(`The file is larger than the ${Math.round(t/(1024*1024))} MB limit.`)}async function*Le(t,e){let n=0;for await(let r of t){if(n+=r.byteLength,n>e)throw P(e);yield r}}async function ve(t,e){let n=[],r=0;for await(let o of t){if(r+=o.byteLength,r>e)throw P(e);n.push(o)}let i=new Uint8Array(r),s=0;for(let o of n)i.set(o,s),s+=o.byteLength;return i}async function Ee(t,e,n){let r=e?.trim().toLowerCase();if(!r||r==="identity")return t;let i=r==="gzip"||r==="x-gzip"?T.createGunzip():r==="deflate"?T.createInflate():r==="br"?T.createBrotliDecompress():void 0;if(!i)throw new m(`The file was served with an unsupported Content-Encoding (${r}).`);return me(pe.from(Le(t,n)),i,s=>{s&&i.destroy(s)}),i}function E(t){if(t!==void 0&&!(Number.isSafeInteger(t)&&t>=0))throw new RangeError(`maxBytes must be a whole number of bytes, 0 or more; got ${t}.`)}function Oe(t){if(!t)return;let e=/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(t)?.[1];if(e)try{return decodeURIComponent(e.trim())}catch{}let n=/filename\s*=\s*("([^"]*)"|[^;]+)/.exec(t);return(n?.[2]??n?.[1]??"").trim()||void 0}async function I(t,e={},n={}){E(e.maxBytes);let r=e.maxBytes??ye,i=n.transport??Ae,s=AbortSignal.timeout(e.timeoutMs??he),o=await z(t,n,s);for(let a=0;;a++){let l=await i(o.url,o.addresses,s),c;try{let u=A(l.headers,"location");if(l.status>=300&&l.status<400&&u){if(l.cancel?.(),a>=W)throw new m(`The file URL redirected more than ${W} times.`);o=await z(new URL(u,o.url).toString(),n,s);continue}if(l.status<200||l.status>=300)throw new Error(`Could not download the file (${l.status}). Its URL must be publicly reachable.`);let R=Number(A(l.headers,"content-length"));if(Number.isFinite(R)&&R>r)throw P(r);c=await ve(await Ee(l.body,A(l.headers,"content-encoding"),r),r)}catch(u){throw l.cancel?.(),u}let f=Oe(A(l.headers,"content-disposition"));return{bytes:c,contentType:A(l.headers,"content-type")?.split(";")[0]?.trim()||"application/octet-stream",url:o.url.toString(),...f?{filename:f}:{}}}}var Q={filename:d.string().optional().describe("What to call the file. Defaults to the name in its URL."),contentType:d.string().optional().describe("Media type, for example application/pdf. Defaults to what the server states.")},Se=d.union([d.string().min(1).describe("A public http(s) URL to the file."),d.object({url:d.string().min(1).describe("A public http(s) URL to the file."),...Q}),d.object({base64:d.string().min(1).describe("The file, base64-encoded."),...Q})]).describe("A file: a public URL to it, or {url, filename?, contentType?}, or {base64, filename?, contentType?} for a small one.");function Ue(t){return typeof Blob<"u"&&t instanceof Blob}function O(t,e,n){return{bytes:t,filename:e,contentType:n,file:new File([new Uint8Array(t)],e,{type:n})}}var Ce=/^data:([^;,]*)((?:;[^;,=]+=[^;,]*)*)(;base64)?,(.*)$/is,x=t=>new Error(`The file is larger than the ${Math.round(t/(1024*1024))} MB limit.`);function D(t,e){if(t.byteLength===0)throw new Error("The file is empty.");if(e!==void 0&&t.byteLength>e)throw x(e);return t}function Pe(t,e){if(e!==void 0&&Math.ceil(t.length/3)>e)throw x(e);let n=new TextEncoder().encode(t),r=new Uint8Array(e===void 0?n.length:Math.min(n.length,e)),i=0;for(let s=0;s<n.length;s++){if(e!==void 0&&i===e)throw x(e);let o=n[s]===37?String.fromCharCode(n[s+1]??0,n[s+2]??0):"";/^[0-9a-fA-F]{2}$/.test(o)?(r[i++]=Number.parseInt(o,16),s+=2):r[i++]=n[s]}return i===r.length?r:r.slice(0,i)}var K=()=>new Error("The file is not valid base64."),Ie=new Set([9,10,11,12,13,32]);function De(t,e){if(!t.includes("%"))return t;let n=t.replace(/\s+/g,""),r=e===void 0?n.length:Math.min(n.length,Math.ceil(e/3)*4),i=new Uint8Array(r),s=0;for(let o=0;o<n.length;o++){let a=n.charCodeAt(o),l=a===37?n.slice(o+1,o+3):"";if(/^[0-9a-fA-F]{2}$/.test(l)&&(a=Number.parseInt(l,16),o+=2),!Ie.has(a)){if(a>127)throw K();if(s===r)throw x(e??r);i[s++]=a}}return Buffer.from(i.buffer,0,s).toString("latin1")}function Z(t,e){let n=t.replace(/\s+/g,"");if(n.length%4===0&&(n.endsWith("==")?n=n.slice(0,-2):n.endsWith("=")&&(n=n.slice(0,-1))),n.length===0||n.length%4===1||!/^[A-Za-z0-9+/_-]+$/.test(n))throw K();if(e!==void 0&&Math.floor(n.length*3/4)>e)throw x(e);return D(new Uint8Array(Buffer.from(n,"base64")),e)}async function ke(t,e={},n={}){E(e.maxBytes);let r=e.fallbackName??"file";if(Ue(t)){let a=typeof File<"u"&&t instanceof File&&t.name?t.name:r;if(e.maxBytes!==void 0&&t.size>e.maxBytes)throw x(e.maxBytes);return O(D(new Uint8Array(await t.arrayBuffer()),e.maxBytes),a,t.type||"application/octet-stream")}let i=typeof t=="string"?{url:t}:t;if("base64"in i)return O(Z(i.base64,e.maxBytes),i.filename??r,i.contentType??"application/octet-stream");let s=Ce.exec(i.url);if(s){let[,a,,l,c=""]=s,f=l?Z(De(c,e.maxBytes),e.maxBytes):D(Pe(c,e.maxBytes),e.maxBytes);return O(f,i.filename??r,i.contentType??(a||"application/octet-stream"))}let o=await I(i.url,e,n);return O(o.bytes,i.filename??o.filename??Y(o.url,r),i.contentType??o.contentType)}var Fe=d.object({contentBase64:d.string().optional().describe("The file, base64-encoded. Missing when the file came back as text or contentOmitted is set."),text:d.string().optional().describe("The file as text, in place of contentBase64, when it is a text file (CSV, JSON, Markdown, XML and the like) in UTF-8."),contentType:d.string().describe("Media type of the file, for example application/pdf."),byteLength:d.number().describe("Size of the file in bytes."),filename:d.string().optional().describe("The file name, when known."),contentOmitted:d.enum(["not_requested","over_limit"]).optional().describe("Set when the content was left out: the caller did not ask for it, or the file was over the limit.")}),ee=7e5,Be=new Set(["application/json","application/xml","application/javascript","application/ecmascript","application/x-javascript","application/yaml","application/x-yaml","application/toml","application/csv","application/ndjson","application/x-ndjson","application/sql","application/graphql","application/x-sh"]);function Ne(t){let e=t.toLowerCase();return e.startsWith("text/")||e.endsWith("+json")||e.endsWith("+xml")||Be.has(e)}var qe=new Set(["application/octet-stream","binary/octet-stream","application/unknown"]),$e=new Set(["txt","text","csv","tsv","md","markdown","json","jsonl","ndjson","xml","yaml","yml","toml","ini","log","html","htm","css","js","mjs","cjs","ts","tsx","jsx","sql","sh","py","rb","go","rs","java","svg","ics","vcf","srt","vtt"]);function je(t,e){if(Ne(t))return!0;if(!qe.has(t.toLowerCase()))return!1;let n=/\.([a-z0-9]+)$/.exec(e?.toLowerCase()??"")?.[1];return n!==void 0&&$e.has(n)}function Me(t){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{return}}function _e(t,e,n={}){E(n.maxBytes);let r={contentType:e?.split(";")[0]?.trim()||"application/octet-stream",byteLength:t.byteLength,...n.filename?{filename:n.filename}:{}};if(n.includeContent===!1)return{...r,contentOmitted:"not_requested"};if(t.byteLength>(n.maxBytes??ee))return{...r,contentOmitted:"over_limit"};let i=n.text!==!1&&je(r.contentType,n.filename)?Me(t):void 0;return i!==void 0?{...r,text:i}:{...r,contentBase64:Buffer.from(t).toString("base64")}}var k=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},S=class{#t;#n;#e;#r;#s;#o;#i;constructor(e){this.#t=!1,this.#n=!1,this.#e=!1,this.#r=[],this.#s=new Promise((n,r)=>{this.#o=n,this.#i=r;let i=a=>{this.#t||this.#n||this.#e||(this.#t=!0,this.#o&&this.#o(a))},s=a=>{this.#t||this.#n||this.#e||(this.#n=!0,this.#i&&this.#i(a))},o=a=>{this.#t||this.#n||this.#e||this.#r.push(a)};return Object.defineProperty(o,"isResolved",{get:()=>this.#t}),Object.defineProperty(o,"isRejected",{get:()=>this.#n}),Object.defineProperty(o,"isCancelled",{get:()=>this.#e}),e(i,s,o)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,n){return this.#s.then(e,n)}catch(e){return this.#s.catch(e)}finally(e){return this.#s.finally(e)}cancel(){if(!(this.#t||this.#n||this.#e)){if(this.#e=!0,this.#r.length)try{for(let e of this.#r)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#r.length=0,this.#i&&this.#i(new k("Request aborted"))}}get isCancelled(){return this.#e}};var te={enabled:!0,maxRetries:3,initialRetryDelay:1e3,backoffMultiplier:2,headerNames:{retryAfter:"retry-after",resetTime:"x-ratelimit-reset",remaining:"x-ratelimit-remaining",limit:"x-ratelimit-limit"}};function ne(t,e){let n={};if(e.headerNames.retryAfter){let r=t.headers.get(e.headerNames.retryAfter);if(r){let i=parseInt(r,10);isNaN(i)||(n.retryAfter=i*1e3)}}if(e.headerNames.resetTime){let r=t.headers.get(e.headerNames.resetTime);if(r){let i=parseInt(r,10);if(!isNaN(i)){let s=Date.now(),o=i>1e12?i:i*1e3;n.rateLimitReset=o,o>s&&(n.retryAfter=o-s)}}}if(e.headerNames.remaining){let r=t.headers.get(e.headerNames.remaining);if(r){let i=parseInt(r,10);isNaN(i)||(n.rateLimitRemaining=i)}}if(e.headerNames.limit){let r=t.headers.get(e.headerNames.limit);if(r){let i=parseInt(r,10);isNaN(i)||(n.rateLimitLimit=i)}}return n}function re(t,e,n){return n.enabled?t===429?!0:n.isRateLimitError?n.isRateLimitError(t,e):!1:!1}function F(t,e,n){if(e.retryAfter)return e.retryAfter;let r=n.initialRetryDelay*Math.pow(n.backoffMultiplier,t-1);return Math.min(r,6e4)}async function B(t){return new Promise(e=>setTimeout(e,t))}var q=t=>t!=null,w=t=>typeof t=="string",N=t=>w(t)&&t!=="",$=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),se=t=>t instanceof FormData,He=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},We=t=>{let e=[],n=(i,s)=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(s))}`)},r=(i,s)=>{q(s)&&(Array.isArray(s)?s.forEach(o=>{r(i,o)}):typeof s=="object"?Object.entries(s).forEach(([o,a])=>{r(`${i}[${o}]`,a)}):n(i,s))};return Object.entries(t).forEach(([i,s])=>{r(i,s)}),e.length>0?`?${e.join("&")}`:""},ze=(t,e)=>{let n=t.ENCODE_PATH||encodeURI,r=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(a,l)=>e.path?.hasOwnProperty(l)?n(String(e.path[l])):a),i=t.BASE.endsWith("/")?t.BASE.slice(0,-1):t.BASE,s=r.startsWith("/")?r.slice(1):r,o=`${i}/${s}`;return e.query?`${o}${We(e.query)}`:o},Ve=t=>{if(t.formData){let e=new FormData,n=(r,i)=>{w(i)||$(i)?e.append(r,i):e.append(r,JSON.stringify(i))};return Object.entries(t.formData).filter(([r,i])=>q(i)).forEach(([r,i])=>{Array.isArray(i)?i.forEach(s=>n(r,s)):n(r,i)}),e}},U=async(t,e)=>typeof e=="function"?e(t):e,Xe=async(t,e)=>{let[n,r,i,s]=await Promise.all([U(e,t.TOKEN),U(e,t.USERNAME),U(e,t.PASSWORD),U(e,t.HEADERS)]),o=Object.entries({Accept:"application/json",...s,...e.headers}).filter(([a,l])=>q(l)).reduce((a,[l,c])=>({...a,[l]:String(c)}),{});if(N(n)&&(o.Authorization=`Bearer ${n}`),N(r)&&N(i)){let a=He(`${r}:${i}`);o.Authorization=`Basic ${a}`}return e.body!==void 0&&(e.mediaType?o["Content-Type"]=e.mediaType:$(e.body)?o["Content-Type"]=e.body.type||"application/octet-stream":w(e.body)?o["Content-Type"]="text/plain":se(e.body)||(o["Content-Type"]="application/json")),new Headers(o)},Ge=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):w(t.body)||$(t.body)||se(t.body)?t.body:JSON.stringify(t.body)},Je=async(t,e,n,r,i,s,o)=>{let a=new AbortController,l=t.TIMEOUT??2e4,c={headers:s,body:r??i,method:e.method,signal:AbortSignal.any([a.signal,AbortSignal.timeout(l)])};return t.WITH_CREDENTIALS&&(c.credentials=t.CREDENTIALS),o(()=>a.abort()),await fetch(n,c)},Ye=(t,e)=>{if(e){let n=t.headers.get(e);if(w(n))return n}},Qe=async(t,e)=>{if(e?.responseType==="binary"&&t.status===204)return{bytes:new Uint8Array(0),contentType:t.headers.get("Content-Type")};if(t.status!==204){if(e?.responseType==="binary"&&t.ok)return{bytes:new Uint8Array(await t.arrayBuffer()),contentType:t.headers.get("Content-Type")};try{let n=t.headers.get("Content-Type");if(n)return["application/json","application/problem+json"].some(s=>n.toLowerCase().startsWith(s))?await t.json():await t.text()}catch(n){console.error(n)}}},ie=(t,e,n)=>{let i={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(i)throw new h(t,e,i,n);if(!e.ok){let s=e.status??"unknown",o=e.statusText??"unknown",a=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})(),l=e.body?.message||e.body?.error||e.body?.detail||`Generic Error: status: ${s}; status text: ${o}; body: ${a}`;throw new h(t,e,l,n)}},Ze=(t,e,n)=>{let r=n?.rateLimitConfig||te;return new S(async(i,s,o)=>{let a=0,l=r.maxRetries+1;for(;a<l;){a++;try{let c=ze(t,e),f=Ve(e),u=Ge(e),R=await Xe(t,e);if(o.isCancelled)return;let p=await Je(t,e,c,u,f,R,o),M=await Qe(p,e),ae=Ye(p,e.responseHeader),L={url:c,ok:p.ok,status:p.status,statusText:p.statusText,body:p.ok?ae??M:M};if(r.enabled&&re(p.status,L.body,r)){let _=ne(p,r);if(a<l){let le=F(a,_,r);await B(le);continue}ie(e,L,_)}ie(e,L),i(L.body);return}catch(c){if(c instanceof h&&c.isRateLimitError()&&a<l){let f=c.retryAfter?c.retryAfter:F(a,{retryAfter:c.retryAfter,rateLimitReset:c.rateLimitReset},r);await B(f);continue}if(a>=l){s(c);return}if(c instanceof h&&c.isRateLimitError())continue;s(c);return}}})};var j=class{handlers=new Map;on(e,n){let r=this.handlers.get(e)||[];return r.push(n),this.handlers.set(e,r),this}off(e,n){let r=this.handlers.get(e)||[],i=r.indexOf(n);return i!==-1&&(r.splice(i,1),this.handlers.set(e,r)),this}getRegisteredEvents(){return Array.from(this.handlers.keys())}hasHandlers(e){let n=this.handlers.get(e);return!!n&&n.length>0}clearHandlers(e){return e?this.handlers.delete(e):this.handlers.clear(),this}async executeHandlers(e,n){let r=this.handlers.get(e)||[];for(let i of r)await i(n)}};import*as g from"crypto";function Ke(t,e,n,r="sha256"){if(!n||!e)return!1;let i=g.createHmac(r,e).update(t).digest("hex");try{return g.timingSafeEqual(Buffer.from(n),Buffer.from(i))}catch{return!1}}function et(t,e,n,r,i="sha256"){if(!n||!e||!n.startsWith(r))return!1;let s=n.slice(r.length),o=g.createHmac(i,e).update(t).digest("hex");try{return g.timingSafeEqual(Buffer.from(s),Buffer.from(o))}catch{return!1}}function oe(t,e,n,r,i=300){if(!e||!r||!n)return!1;let s=Math.floor(Date.now()/1e3),o=parseInt(n,10);if(Math.abs(s-o)>i)return!1;let a=`v0:${n}:${t}`,l="v0="+g.createHmac("sha256",e).update(a).digest("hex");try{return g.timingSafeEqual(Buffer.from(r),Buffer.from(l))}catch{return!1}}function tt(t,e,n,r,i=300){return oe(t,e,n,r,i)}export{h as ApiError,j as BaseWebhookHandler,ee as FILE_OUTPUT_MAX_BYTES,Se as FileInputSchema,Fe as FileOutputSchema,m as UnsafeUrlError,I as downloadPublicFile,J as isBlockedAddress,Ze as request,ke as resolveFileInput,_e as toFileOutput,oe as verifyHmacSha256Signature,Ke as verifyHmacSignature,et as verifyHmacSignatureWithPrefix,tt as verifySlackSignature};
|
|
1
|
+
import"./chunk-SOY77BN4.js";var ue=new Set(["apikey","xapikey","key","appkey","appid","token","apitoken","accesstoken","authtoken","clientsecret","secret","password"]);function C(t){let e=t;try{e=decodeURIComponent(t)}catch{e=t}return ue.has(e.toLowerCase().replace(/[-_]/g,""))}function fe(t){let e=t.indexOf("?");if(e===-1)return t;let n=t.indexOf("#",e),r=t.slice(0,e+1),i=n===-1?t.slice(e+1):t.slice(e+1,n),s=n===-1?"":t.slice(n),o=!1,a=i.split("&").map(l=>{if(!l)return l;let c=l.indexOf("="),f=c===-1?l:l.slice(0,c);return C(f)?(o=!0,`${f}=[REDACTED]`):l}).join("&");return o?r+a+s:t}function H(t){if(!t)return t;try{let e=/^[a-z]+:\/\//i.test(t),n=e?void 0:"http://localhost",r=new URL(t,n),i=!1;for(let s of[...r.searchParams.keys()])C(s)&&(r.searchParams.set(s,"[REDACTED]"),i=!0);return i?e?r.toString():r.pathname+r.search+r.hash:t}catch{return fe(t)}}function de(t){let e=H(t.url),n=!1,r=t.query;if(t.query){r={...t.query};for(let i of Object.keys(r))C(i)&&(r[i]="[REDACTED]",n=!0)}return!n&&e===t.url?t:{...t,url:e,...n?{query:r}:{}}}var h=class extends Error{url;status;statusText;body;request;retryAfter;rateLimitReset;rateLimitRemaining;rateLimitLimit;constructor(e,n,r,i){super(r),this.name="ApiError",this.url=H(n.url),this.status=n.status,this.statusText=n.statusText,this.body=n.body,this.request=de(e),this.retryAfter=i?.retryAfter,this.rateLimitReset=i?.rateLimitReset,this.rateLimitRemaining=i?.rateLimitRemaining,this.rateLimitLimit=i?.rateLimitLimit}isRateLimitError(){return this.status===429}};import{z as d}from"zod";import{lookup as me}from"dns/promises";import*as V from"http";import*as X from"https";import{pipeline as pe,Readable as he}from"stream";import*as x from"zlib";var ye=3e4,be=25*1024*1024,W=3,ge=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function L(t){let e=t.split(".");if(e.length!==4)return;let n=0;for(let r of e){if(!/^\d{1,3}$/.test(r))return;let i=Number(r);if(i>255)return;n=n*256+i}return n}function G(t){let e=L(t);return e===void 0?!0:ge.some(([n,r])=>{let i=L(n);if(i===void 0)return!1;let s=r===0?0:4294967295<<32-r>>>0;return(e&s)===(i&s)})}function Re(t){let e=t,n=e.indexOf("%");n!==-1&&(e=e.slice(0,n));let r=e.lastIndexOf(":");if(r===-1)return;let i=e.slice(r+1);if(i.includes(".")){let u=L(i);if(u===void 0)return;e=`${e.slice(0,r+1)}${(u>>>16).toString(16)}:${(u&65535).toString(16)}`}let s=e.split("::");if(s.length>2)return;let o=u=>u===""?[]:u.split(":").filter(R=>R!==""),a=o(s[0]??""),l=s.length===2?o(s[1]??""):[];if(![...a,...l].every(u=>/^[0-9a-fA-F]{1,4}$/.test(u)))return;if(s.length===1)return a.length===8?a.map(u=>Number.parseInt(u,16)):void 0;let c=8-a.length-l.length;return c<1?void 0:[...a,...Array(c).fill("0"),...l].map(u=>Number.parseInt(u,16))}function xe(t){let e=Re(t);if(!e)return!0;if(e.slice(0,5).every(r=>r===0)&&(e[5]===65535||e[5]===0)){let r=`${e[6]>>8}.${e[6]&255}.${e[7]>>8}.${e[7]&255}`;if(G(r))return!0}return!!(e.every(r=>r===0)||e.slice(0,7).every(r=>r===0)&&e[7]===1||(e[0]&65024)===64512||(e[0]&65472)===65152||(e[0]&65472)===65216||(e[0]&65280)===65280||e[0]===8194||e[0]===100&&e[1]===65435&&e.slice(2,6).every(r=>r===0)||e[0]===100&&e[1]===65435&&e[2]===1)}function J(t){let e=t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t;return e.includes(":")?xe(e):G(e)}var m=class extends Error{constructor(e){super(e),this.name="UnsafeUrlError"}};async function Te(t){return(await me(t,{all:!0,verbatim:!0})).map(n=>n.address)}function we(t){return((e,n,r)=>{let i=r,s=typeof n=="object"&&n!==null&&n.all===!0,o=t.map(l=>({address:l,family:l.includes(":")?6:4}));if(o.length===0){i(new Error("No address to connect to."),"",0);return}if(s){i(null,o);return}let a=o[0];i(null,a.address,a.family)})}var Ae=(t,e,n)=>{let r=t.protocol==="https:",i=t.hostname.replace(/^\[|\]$/g,""),s={method:"GET",protocol:t.protocol,hostname:i,port:t.port===""?void 0:Number(t.port),path:`${t.pathname}${t.search}`,headers:{Accept:"*/*","Accept-Encoding":"identity"},lookup:we(e),agent:!1,signal:n};return r&&(s.servername=i),new Promise((o,a)=>{let c=(r?X.request:V.request)(s,f=>{o({status:f.statusCode??0,headers:f.headers,body:f,cancel:()=>f.destroy()})});c.on("error",a),c.end()})};function ve(t,e){return e?e.aborted?Promise.reject(e.reason):new Promise((n,r)=>{let i=()=>r(e.reason);e.addEventListener("abort",i,{once:!0}),t.then(s=>{e.removeEventListener("abort",i),n(s)},s=>{e.removeEventListener("abort",i),r(s)})}):t}async function z(t,e={},n){let r;try{r=new URL(t)}catch{throw new m("The file URL must be an absolute URL.")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new m("The file URL must use http or https.");let i=r.hostname.replace(/^\[|\]$/g,"");if(i==="")throw new m("The file URL must include a host.");let o=i.includes(":")||L(i)!==void 0?[i]:await ve((e.resolve??Te)(i).catch(()=>{throw new m(`Could not resolve ${i}.`)}),n);if(o.length===0)throw new m(`Could not resolve ${i}.`);for(let a of o)if(J(a))throw new m(`The file URL points at ${i}, which resolves to a private or reserved address. Use a publicly reachable URL.`);return{url:r,addresses:o}}function Y(t,e){try{let n=new URL(t).pathname.split("/").pop();return n&&n.includes(".")?n:e}catch{return e}}function w(t,e){let n=t[e];return Array.isArray(n)?n[0]:n}function I(t){return new m(`The file is larger than the ${Math.round(t/(1024*1024))} MB limit.`)}async function*Le(t,e){let n=0;for await(let r of t){if(n+=r.byteLength,n>e)throw I(e);yield r}}async function Ee(t,e){let n=[],r=0;for await(let o of t){if(r+=o.byteLength,r>e)throw I(e);n.push(o)}let i=new Uint8Array(r),s=0;for(let o of n)i.set(o,s),s+=o.byteLength;return i}async function Oe(t,e,n){let r=e?.trim().toLowerCase();if(!r||r==="identity")return t;let i=r==="gzip"||r==="x-gzip"?x.createGunzip():r==="deflate"?x.createInflate():r==="br"?x.createBrotliDecompress():void 0;if(!i)throw new m(`The file was served with an unsupported Content-Encoding (${r}).`);return pe(he.from(Le(t,n)),i,s=>{s&&i.destroy(s)}),i}function E(t){if(t!==void 0&&!(Number.isSafeInteger(t)&&t>=0))throw new RangeError(`maxBytes must be a whole number of bytes, 0 or more; got ${t}.`)}function Se(t){if(!t)return;let e=/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(t)?.[1];if(e)try{return decodeURIComponent(e.trim())}catch{}let n=/filename\s*=\s*("([^"]*)"|[^;]+)/.exec(t);return(n?.[2]??n?.[1]??"").trim()||void 0}async function P(t,e={},n={}){E(e.maxBytes);let r=e.maxBytes??be,i=n.transport??Ae,s=AbortSignal.timeout(e.timeoutMs??ye),o=await z(t,n,s);for(let a=0;;a++){let l=await i(o.url,o.addresses,s),c;try{let u=w(l.headers,"location");if(l.status>=300&&l.status<400&&u){if(l.cancel?.(),a>=W)throw new m(`The file URL redirected more than ${W} times.`);o=await z(new URL(u,o.url).toString(),n,s);continue}if(l.status<200||l.status>=300)throw new Error(`Could not download the file (${l.status}). Its URL must be publicly reachable.`);let R=Number(w(l.headers,"content-length"));if(Number.isFinite(R)&&R>r)throw I(r);c=await Ee(await Oe(l.body,w(l.headers,"content-encoding"),r),r)}catch(u){throw l.cancel?.(),u}let f=Se(w(l.headers,"content-disposition"));return{bytes:c,contentType:w(l.headers,"content-type")?.split(";")[0]?.trim()||"application/octet-stream",url:o.url.toString(),...f?{filename:f}:{}}}}var Q={filename:d.string().optional().describe("What to call the file. Defaults to the name in its URL."),contentType:d.string().optional().describe("Media type, for example application/pdf. Defaults to what the server states.")},Ue=d.union([d.string().min(1).describe("A public http(s) URL to the file."),d.object({url:d.string().min(1).describe("A public http(s) URL to the file."),...Q}),d.object({base64:d.string().min(1).describe("The file, base64-encoded."),...Q})]).describe("A file: a public URL to it, or {url, filename?, contentType?}, or {base64, filename?, contentType?} for a small one.");function Ce(t){return typeof Blob<"u"&&t instanceof Blob}function O(t,e,n){return{bytes:t,filename:e,contentType:n,file:new File([new Uint8Array(t)],e,{type:n})}}var Ie=/^data:([^;,]*)((?:;[^;,=]+=[^;,]*)*)(;base64)?,(.*)$/is,T=t=>new Error(`The file is larger than the ${Math.round(t/(1024*1024))} MB limit.`);function k(t,e){if(t.byteLength===0)throw new Error("The file is empty.");if(e!==void 0&&t.byteLength>e)throw T(e);return t}function Pe(t,e){if(e!==void 0&&Math.ceil(t.length/3)>e)throw T(e);let n=new TextEncoder().encode(t),r=new Uint8Array(e===void 0?n.length:Math.min(n.length,e)),i=0;for(let s=0;s<n.length;s++){if(e!==void 0&&i===e)throw T(e);let o=n[s]===37?String.fromCharCode(n[s+1]??0,n[s+2]??0):"";/^[0-9a-fA-F]{2}$/.test(o)?(r[i++]=Number.parseInt(o,16),s+=2):r[i++]=n[s]}return i===r.length?r:r.slice(0,i)}var K=()=>new Error("The file is not valid base64."),ke=new Set([9,10,11,12,13,32]);function De(t,e){if(!t.includes("%"))return t;let n=t.replace(/\s+/g,""),r=e===void 0?n.length:Math.min(n.length,Math.ceil(e/3)*4),i=new Uint8Array(r),s=0;for(let o=0;o<n.length;o++){let a=n.charCodeAt(o),l=a===37?n.slice(o+1,o+3):"";if(/^[0-9a-fA-F]{2}$/.test(l)&&(a=Number.parseInt(l,16),o+=2),!ke.has(a)){if(a>127)throw K();if(s===r)throw T(e??r);i[s++]=a}}return Buffer.from(i.buffer,0,s).toString("latin1")}function Z(t,e){let n=t.replace(/\s+/g,"");if(n.length%4===0&&(n.endsWith("==")?n=n.slice(0,-2):n.endsWith("=")&&(n=n.slice(0,-1))),n.length===0||n.length%4===1||!/^[A-Za-z0-9+/_-]+$/.test(n))throw K();if(e!==void 0&&Math.floor(n.length*3/4)>e)throw T(e);return k(new Uint8Array(Buffer.from(n,"base64")),e)}async function Fe(t,e={},n={}){E(e.maxBytes);let r=e.fallbackName??"file";if(Ce(t)){let a=typeof File<"u"&&t instanceof File&&t.name?t.name:r;if(e.maxBytes!==void 0&&t.size>e.maxBytes)throw T(e.maxBytes);return O(k(new Uint8Array(await t.arrayBuffer()),e.maxBytes),a,t.type||"application/octet-stream")}let i=typeof t=="string"?{url:t}:t;if("base64"in i)return O(Z(i.base64,e.maxBytes),i.filename??r,i.contentType??"application/octet-stream");let s=Ie.exec(i.url);if(s){let[,a,,l,c=""]=s,f=l?Z(De(c,e.maxBytes),e.maxBytes):k(Pe(c,e.maxBytes),e.maxBytes);return O(f,i.filename??r,i.contentType??(a||"application/octet-stream"))}let o=await P(i.url,e,n);return O(o.bytes,i.filename??o.filename??Y(o.url,r),i.contentType??o.contentType)}var Be=d.object({contentBase64:d.string().optional().describe("The file, base64-encoded. Missing when the file came back as text or contentOmitted is set."),text:d.string().optional().describe("The file as text, in place of contentBase64, when it is a text file (CSV, JSON, Markdown, XML and the like) in UTF-8."),contentType:d.string().describe("Media type of the file, for example application/pdf."),byteLength:d.number().describe("Size of the file in bytes."),filename:d.string().optional().describe("The file name, when known."),contentOmitted:d.enum(["not_requested","over_limit"]).optional().describe("Set when the content was left out: the caller did not ask for it, or the file was over the limit."),fileId:d.string().optional().describe("Where the host saved the file, in place of its content, when it was over the limit. On Corsair it is a Files id (fil_\u2026): pass it to another app wherever that app takes a file URL, or read a text file or PDF with files.read_text.")}),ee=7e5,te=()=>{};function Ne(t){te=t}var qe=new Set(["application/json","application/xml","application/javascript","application/ecmascript","application/x-javascript","application/yaml","application/x-yaml","application/toml","application/csv","application/ndjson","application/x-ndjson","application/sql","application/graphql","application/x-sh"]);function $e(t){let e=t.toLowerCase();return e.startsWith("text/")||e.endsWith("+json")||e.endsWith("+xml")||qe.has(e)}var je=new Set(["application/octet-stream","binary/octet-stream","application/unknown"]),_e=new Set(["txt","text","csv","tsv","md","markdown","json","jsonl","ndjson","xml","yaml","yml","toml","ini","log","html","htm","css","js","mjs","cjs","ts","tsx","jsx","sql","sh","py","rb","go","rs","java","svg","ics","vcf","srt","vtt"]);function Me(t,e){if($e(t))return!0;if(!je.has(t.toLowerCase()))return!1;let n=/\.([a-z0-9]+)$/.exec(e?.toLowerCase()??"")?.[1];return n!==void 0&&_e.has(n)}function He(t){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{return}}function We(t,e,n={}){E(n.maxBytes);let r={contentType:e?.split(";")[0]?.trim()||"application/octet-stream",byteLength:t.byteLength,...n.filename?{filename:n.filename}:{}};if(n.includeContent===!1)return{...r,contentOmitted:"not_requested"};if(t.byteLength>(n.maxBytes??ee)){let s=te()?.({...r,bytes:t});return s?{...r,fileId:s}:{...r,contentOmitted:"over_limit"}}let i=n.text!==!1&&Me(r.contentType,n.filename)?He(t):void 0;return i!==void 0?{...r,text:i}:{...r,contentBase64:Buffer.from(t).toString("base64")}}var D=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},S=class{#t;#n;#e;#r;#s;#o;#i;constructor(e){this.#t=!1,this.#n=!1,this.#e=!1,this.#r=[],this.#s=new Promise((n,r)=>{this.#o=n,this.#i=r;let i=a=>{this.#t||this.#n||this.#e||(this.#t=!0,this.#o&&this.#o(a))},s=a=>{this.#t||this.#n||this.#e||(this.#n=!0,this.#i&&this.#i(a))},o=a=>{this.#t||this.#n||this.#e||this.#r.push(a)};return Object.defineProperty(o,"isResolved",{get:()=>this.#t}),Object.defineProperty(o,"isRejected",{get:()=>this.#n}),Object.defineProperty(o,"isCancelled",{get:()=>this.#e}),e(i,s,o)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,n){return this.#s.then(e,n)}catch(e){return this.#s.catch(e)}finally(e){return this.#s.finally(e)}cancel(){if(!(this.#t||this.#n||this.#e)){if(this.#e=!0,this.#r.length)try{for(let e of this.#r)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#r.length=0,this.#i&&this.#i(new D("Request aborted"))}}get isCancelled(){return this.#e}};var ne={enabled:!0,maxRetries:3,initialRetryDelay:1e3,backoffMultiplier:2,headerNames:{retryAfter:"retry-after",resetTime:"x-ratelimit-reset",remaining:"x-ratelimit-remaining",limit:"x-ratelimit-limit"}};function re(t,e){let n={};if(e.headerNames.retryAfter){let r=t.headers.get(e.headerNames.retryAfter);if(r){let i=parseInt(r,10);isNaN(i)||(n.retryAfter=i*1e3)}}if(e.headerNames.resetTime){let r=t.headers.get(e.headerNames.resetTime);if(r){let i=parseInt(r,10);if(!isNaN(i)){let s=Date.now(),o=i>1e12?i:i*1e3;n.rateLimitReset=o,o>s&&(n.retryAfter=o-s)}}}if(e.headerNames.remaining){let r=t.headers.get(e.headerNames.remaining);if(r){let i=parseInt(r,10);isNaN(i)||(n.rateLimitRemaining=i)}}if(e.headerNames.limit){let r=t.headers.get(e.headerNames.limit);if(r){let i=parseInt(r,10);isNaN(i)||(n.rateLimitLimit=i)}}return n}function ie(t,e,n){return n.enabled?t===429?!0:n.isRateLimitError?n.isRateLimitError(t,e):!1:!1}function F(t,e,n){if(e.retryAfter)return e.retryAfter;let r=n.initialRetryDelay*Math.pow(n.backoffMultiplier,t-1);return Math.min(r,6e4)}async function B(t){return new Promise(e=>setTimeout(e,t))}var q=t=>t!=null,A=t=>typeof t=="string",N=t=>A(t)&&t!=="",$=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),oe=t=>t instanceof FormData,ze=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Ve=t=>{let e=[],n=(i,s)=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(s))}`)},r=(i,s)=>{q(s)&&(Array.isArray(s)?s.forEach(o=>{r(i,o)}):typeof s=="object"?Object.entries(s).forEach(([o,a])=>{r(`${i}[${o}]`,a)}):n(i,s))};return Object.entries(t).forEach(([i,s])=>{r(i,s)}),e.length>0?`?${e.join("&")}`:""},Xe=(t,e)=>{let n=t.ENCODE_PATH||encodeURI,r=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(a,l)=>e.path?.hasOwnProperty(l)?n(String(e.path[l])):a),i=t.BASE.endsWith("/")?t.BASE.slice(0,-1):t.BASE,s=r.startsWith("/")?r.slice(1):r,o=`${i}/${s}`;return e.query?`${o}${Ve(e.query)}`:o},Ge=t=>{if(t.formData){let e=new FormData,n=(r,i)=>{A(i)||$(i)?e.append(r,i):e.append(r,JSON.stringify(i))};return Object.entries(t.formData).filter(([r,i])=>q(i)).forEach(([r,i])=>{Array.isArray(i)?i.forEach(s=>n(r,s)):n(r,i)}),e}},U=async(t,e)=>typeof e=="function"?e(t):e,Je=async(t,e)=>{let[n,r,i,s]=await Promise.all([U(e,t.TOKEN),U(e,t.USERNAME),U(e,t.PASSWORD),U(e,t.HEADERS)]),o=Object.entries({Accept:"application/json",...s,...e.headers}).filter(([a,l])=>q(l)).reduce((a,[l,c])=>({...a,[l]:String(c)}),{});if(N(n)&&(o.Authorization=`Bearer ${n}`),N(r)&&N(i)){let a=ze(`${r}:${i}`);o.Authorization=`Basic ${a}`}return e.body!==void 0&&(e.mediaType?o["Content-Type"]=e.mediaType:$(e.body)?o["Content-Type"]=e.body.type||"application/octet-stream":A(e.body)?o["Content-Type"]="text/plain":oe(e.body)||(o["Content-Type"]="application/json")),new Headers(o)},Ye=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):A(t.body)||$(t.body)||oe(t.body)?t.body:JSON.stringify(t.body)},Qe=async(t,e,n,r,i,s,o)=>{let a=new AbortController,l=t.TIMEOUT??2e4,c={headers:s,body:r??i,method:e.method,signal:AbortSignal.any([a.signal,AbortSignal.timeout(l)])};return t.WITH_CREDENTIALS&&(c.credentials=t.CREDENTIALS),o(()=>a.abort()),await fetch(n,c)},Ze=(t,e)=>{if(e){let n=t.headers.get(e);if(A(n))return n}},Ke=async(t,e)=>{if(e?.responseType==="binary"&&t.status===204)return{bytes:new Uint8Array(0),contentType:t.headers.get("Content-Type")};if(t.status!==204){if(e?.responseType==="binary"&&t.ok)return{bytes:new Uint8Array(await t.arrayBuffer()),contentType:t.headers.get("Content-Type")};try{let n=t.headers.get("Content-Type");if(n)return["application/json","application/problem+json"].some(s=>n.toLowerCase().startsWith(s))?await t.json():await t.text()}catch(n){console.error(n)}}},se=(t,e,n)=>{let i={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(i)throw new h(t,e,i,n);if(!e.ok){let s=e.status??"unknown",o=e.statusText??"unknown",a=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})(),l=e.body?.message||e.body?.error||e.body?.detail||`Generic Error: status: ${s}; status text: ${o}; body: ${a}`;throw new h(t,e,l,n)}},et=(t,e,n)=>{let r=n?.rateLimitConfig||ne;return new S(async(i,s,o)=>{let a=0,l=r.maxRetries+1;for(;a<l;){a++;try{let c=Xe(t,e),f=Ge(e),u=Ye(e),R=await Je(t,e);if(o.isCancelled)return;let p=await Qe(t,e,c,u,f,R,o),_=await Ke(p,e),le=Ze(p,e.responseHeader),v={url:c,ok:p.ok,status:p.status,statusText:p.statusText,body:p.ok?le??_:_};if(r.enabled&&ie(p.status,v.body,r)){let M=re(p,r);if(a<l){let ce=F(a,M,r);await B(ce);continue}se(e,v,M)}se(e,v),i(v.body);return}catch(c){if(c instanceof h&&c.isRateLimitError()&&a<l){let f=c.retryAfter?c.retryAfter:F(a,{retryAfter:c.retryAfter,rateLimitReset:c.rateLimitReset},r);await B(f);continue}if(a>=l){s(c);return}if(c instanceof h&&c.isRateLimitError())continue;s(c);return}}})};var j=class{handlers=new Map;on(e,n){let r=this.handlers.get(e)||[];return r.push(n),this.handlers.set(e,r),this}off(e,n){let r=this.handlers.get(e)||[],i=r.indexOf(n);return i!==-1&&(r.splice(i,1),this.handlers.set(e,r)),this}getRegisteredEvents(){return Array.from(this.handlers.keys())}hasHandlers(e){let n=this.handlers.get(e);return!!n&&n.length>0}clearHandlers(e){return e?this.handlers.delete(e):this.handlers.clear(),this}async executeHandlers(e,n){let r=this.handlers.get(e)||[];for(let i of r)await i(n)}};import*as g from"crypto";function tt(t,e,n,r="sha256"){if(!n||!e)return!1;let i=g.createHmac(r,e).update(t).digest("hex");try{return g.timingSafeEqual(Buffer.from(n),Buffer.from(i))}catch{return!1}}function nt(t,e,n,r,i="sha256"){if(!n||!e||!n.startsWith(r))return!1;let s=n.slice(r.length),o=g.createHmac(i,e).update(t).digest("hex");try{return g.timingSafeEqual(Buffer.from(s),Buffer.from(o))}catch{return!1}}function ae(t,e,n,r,i=300){if(!e||!r||!n)return!1;let s=Math.floor(Date.now()/1e3),o=parseInt(n,10);if(Math.abs(s-o)>i)return!1;let a=`v0:${n}:${t}`,l="v0="+g.createHmac("sha256",e).update(a).digest("hex");try{return g.timingSafeEqual(Buffer.from(r),Buffer.from(l))}catch{return!1}}function rt(t,e,n,r,i=300){return ae(t,e,n,r,i)}export{h as ApiError,j as BaseWebhookHandler,ee as FILE_OUTPUT_MAX_BYTES,Ue as FileInputSchema,Be as FileOutputSchema,m as UnsafeUrlError,P as downloadPublicFile,J as isBlockedAddress,et as request,Fe as resolveFileInput,Ne as setFileSink,We as toFileOutput,ae as verifyHmacSha256Signature,tt as verifyHmacSignature,nt as verifyHmacSignatureWithPrefix,rt as verifySlackSignature};
|
package/dist/hub.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$a as ca,A as z,Aa as T,B as A,Ba as U,C as B,Ca as V,Da as W,L as C,Qa as X,Ra as Y,Sa as Z,Xa as _,Ya as $,Za as aa,_a as ba,aa as D,ab as da,b as a,cb as ea,d as b,da as E,db as fa,e as c,ea as F,eb as ga,f as d,fb as ha,g as e,gb as ia,h as f,hb as ja,i as g,ib as ka,j as i,jb as la,k as j,kb as ma,l as k,lb as na,m as l,mb as oa,n as m,na as G,nb as pa,o as n,oa as H,ob as qa,p as o,pa as I,pb as ra,q as p,qa as J,qb as sa,r as q,ra as K,rb as ta,s as r,sa as L,sb as ua,t as s,ta as M,tb as va,u as t,ua as N,ub as wa,v as u,va as O,vb as xa,w as v,wa as P,wb as ya,x as w,xa as Q,xb as za,y as x,ya as R,z as y,za as S}from"./chunk-
|
|
1
|
+
import{$a as ca,A as z,Aa as T,B as A,Ba as U,C as B,Ca as V,Da as W,L as C,Qa as X,Ra as Y,Sa as Z,Xa as _,Ya as $,Za as aa,_a as ba,aa as D,ab as da,b as a,cb as ea,d as b,da as E,db as fa,e as c,ea as F,eb as ga,f as d,fb as ha,g as e,gb as ia,h as f,hb as ja,i as g,ib as ka,j as i,jb as la,k as j,kb as ma,l as k,lb as na,m as l,mb as oa,n as m,na as G,nb as pa,o as n,oa as H,ob as qa,p as o,pa as I,pb as ra,q as p,qa as J,qb as sa,r as q,ra as K,rb as ta,s as r,sa as L,sb as ua,t as s,ta as M,tb as va,u as t,ua as N,ub as wa,v as u,va as O,vb as xa,w as v,wa as P,wb as ya,x as w,xa as Q,xb as za,y as x,ya as R,z as y,za as S}from"./chunk-KUNMGJBS.js";import{a as h,b as Aa,c as Ba,d as Ca,e as Da,f as Ea}from"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{m as BROWSER_DELIVERY_TTL_MS,Ba as CORSAIR_TUNNEL_PATH,Aa as CORSAIR_TUNNEL_ZONE,u as DEFAULT_HUB_API_URL,Ca as FRPC_VERSION,w as HubCredentialsMissingError,v as HubNotConfiguredError,V as ManagedOAuthDeliveryError,n as SIGNED_TUNNEL_REPLAY_WINDOW_MS,fa as attachManagedRefreshAuth,p as buildBrowserDeliveryRedirectUrl,s as buildClientBridgeBrowserDeliveryUrl,la as createConnectSessionJti,qa as createConnectTokenJti,D as createHubConnectSession,E as createHubPermissionSession,ka as createHubRouteHandlers,ia as createManagedPricingCredentialCache,wa as createPermissionSessionJti,o as createSignedTokenJti,pa as decodeConnectSessionTokenFromPath,va as decodeConnectTokenFromPath,za as decodePermissionTokenFromPath,Q as deliverConnectCreateLink,U as deliverSignedEnvelope,S as describeDeliveryNetworkError,ua as encodeConnectTokenForPath,O as extractConnectLinkFromDeliveryAck,H as extractProbeFromDeliveryAck,G as extractRunFromDeliveryAck,N as extractSyncFromDeliveryAck,F as formatHubApprovalMessage,a as formatProviderDisplayName,T as formatServerDeliveryError,Da as frpcPlatformKey,ma as getConnectSessionExpiryMs,X as getConnectStatusForTenant,ra as getConnectTokenExpiryMs,z as getHubConfig,ea as getManagedAccessToken,ha as getManagedPricingApiKey,_ as handleHubDeliveryGet,$ as handleHubDeliveryPost,ba as handleHubDeliveryRequest,aa as hubDeliveryToResponse,B as inferHubEnvironmentSlug,i as isLoopbackUrl,M as isServerDeliveryAckSuccessful,Y as listHubProjectConnections,x as normalizeHubConfig,P as parseConnectLinkFromDeliveryBody,b as parseConnectSessionResponse,f as parseConnectStatusResponse,g as parseHubApiErrorBody,Z as parseManagedPricingCredentialsResponse,e as parseOAuthRefreshResponse,d as parsePermissionSessionResponse,c as parseProjectConnectionsResponse,L as parseServerDeliveryAckBody,R as parseSyncFromDeliveryBody,t as prepareClientBridgeDeliveryTransport,W as processManagedOAuthDelivery,C as registerHubWebhookTenantLink,ga as requireHubForManagedPricing,j as resolveDeliveryTransport,Ea as resolveFrpcBinary,y as resolveHubConfigInput,h as resolveHubDeliveryUrl,A as resolveHubOAuthCallbackUrl,ja as resolveManagedPricingApiKey,ca as respondToHubDelivery,da as respondToHubDeliveryFromRequest,q as signBrowserDeliveryToken,na as signConnectSessionToken,sa as signConnectToken,I as signDeliveryEnvelope,xa as signPermissionToken,k as usesBrowserDelivery,l as validateProductionDeliveryUrl,r as verifyBrowserDeliveryToken,oa as verifyConnectSessionToken,ta as verifyConnectToken,J as verifyDeliveryEnvelope,ya as verifyPermissionToken,K as verifySignedTunnelDelivery};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Db as J,Ea as q,Eb as Y,Fb as K,Gb as G,H as O,Hb as X,Ib as Q,Jb as V,Kb as nn,Lb as en,M as A,Ma as N,Mb as tn,N as L,Nb as rn,O as E,Ob as on,P as v,Pb as sn,Qb as an,Rb as un,Ta as j,Ua as B,Va as D,Wa as U,Xb as w,Yb as P,Zb as T,_b as x,ba as F,bb as Z,c as S,ca as M,dc as cn,ec as pn,fa as $,fc as ln,ga as _,gc as dn,hc as mn,ia as H,ic as gn,jc as Cn,ma as W,nc as fn,oc as yn,pc as I,qc as kn,yb as z}from"./chunk-
|
|
1
|
+
import{Db as J,Ea as q,Eb as Y,Fb as K,Gb as G,H as O,Hb as X,Ib as Q,Jb as V,Kb as nn,Lb as en,M as A,Ma as N,Mb as tn,N as L,Nb as rn,O as E,Ob as on,P as v,Pb as sn,Qb as an,Rb as un,Ta as j,Ua as B,Va as D,Wa as U,Xb as w,Yb as P,Zb as T,_b as x,ba as F,bb as Z,c as S,ca as M,dc as cn,ec as pn,fa as $,fc as ln,ga as _,gc as dn,hc as mn,ia as H,ic as gn,jc as Cn,ma as W,nc as fn,oc as yn,pc as I,qc as kn,yb as z}from"./chunk-KUNMGJBS.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";import{z as p}from"zod";function C(e){let t=e[I];if(!t)throw new Error("listOperations / getSchema: invalid corsair instance. Pass the value returned by createCorsair() or corsair.withTenant().");return t.plugins}function y(e,t){let o=P(C(e),t);return typeof o=="string"?o:Array.isArray(o)?o.join(`
|
|
2
2
|
`):Object.values(o).flat().join(`
|
|
3
3
|
`)}function hn(e,t){return T(C(e),t)}function k(e,t){return w(C(e),t)}function h(e,t){let o=C(e),n=t.toLowerCase(),i=n.indexOf(".");if(i===-1)return null;let u=n.slice(0,i),r=n.slice(i+1),s=o.find(c=>c.id===u);if(!s?.endpointSchemas)return null;let a=r;a.startsWith("api.")&&(a=a.slice(4));for(let[c,l]of Object.entries(s.endpointSchemas))if(c.toLowerCase()===a)return l.input??null;return null}function f(e){let t=wn(e);return e.description&&(t=t.describe(e.description)),e.optional&&(t=t.optional()),t}function wn(e){switch(e.kind){case"string":return e.enum&&e.enum.length>0?p.enum(e.enum):p.string();case"number":return p.number();case"boolean":return p.boolean();case"literal":return p.literal(e.value);case"object":{let t={};for(let[o,n]of Object.entries(e.fields))t[o]=f(n);return p.object(t)}case"array":return p.array(f(e.items));case"unknown":return p.unknown()}}function Pn(e,t){let o=t?.tenantId?In(e,t.tenantId):e;return(t?.operations??Tn(y(o,{plugin:t?.plugin,type:"api"}))).map(i=>{let u=k(o,i),s=h(o,i)??(u?.input?f(u.input):p.object({}));return{name:xn(i),operation:i,description:u?.description??i,schema:s,execute:a=>Rn(o,i,a??{})}})}function Tn(e){return e.split(`
|
|
4
4
|
`).map(t=>t.trim()).filter(Boolean)}function xn(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function In(e,t){let o=e.withTenant;return typeof o=="function"?o.call(e,t):e}async function Rn(e,t,o){let n=t.split("."),i=n.pop();if(!i)throw new Error(`Invalid operation path: ${t}`);let u=e;for(let s of n)if(u=u?.[s],u==null)throw new Error(`Unknown operation path: ${t}`);let r=u[i];if(typeof r!="function")throw new Error(`Operation is not callable: ${t}`);return r.call(u,o)}var d=class extends Error{status;code;extra;constructor(t,o,n,i={}){super(n),this.name="CorsairClientError",this.status=t,this.code=o,this.extra=i}};function bn(e){return e.endsWith("/")?e.slice(0,-1):e}async function R(e){let t={};try{t=await e.json()}catch{}let o=typeof t.error=="string"?t.error:"request_failed",n=typeof t.message=="string"?t.message:`Request failed (${e.status})`,{error:i,message:u,...r}=t;return new d(e.status,o,n,r)}function Sn(e){let t=bn(e.baseURL),o=e.fetch??((...r)=>globalThis.fetch(...r));async function n(r,s){let a=s&&Object.keys(s).length?`?${new URLSearchParams(s).toString()}`:"",c=await o(`${t}${r}${a}`,{method:"GET"});if(!c.ok)throw await R(c);return await c.json()}async function i(r,s){let a=await o(`${t}${r}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw await R(a);return await a.json()}let u=encodeURIComponent;return{ok:()=>n("/ok"),tenants:{list:()=>n("/tenants"),create:r=>i("/tenants",r),get:r=>n(`/tenants/${u(r)}`)},plugins:{list:()=>n("/plugins"),get:r=>n(`/plugins/${u(r)}`)},connectionStatus:{get:r=>{let s={};return r?.tenantId&&(s.tenantId=r.tenantId),n("/connection-status",s)}},permissions:{get:r=>"id"in r?n(`/permissions/${u(r.id)}`):i("/permissions/lookup-by-token",{token:r.token})},connect:{createLink:r=>i("/connect/links",r),resolve:r=>n("/connect/resolve",{state:r}),oauthCallback:r=>i("/connect/oauth/callback",r)},connectRequest:{get:r=>{let s={};return r?.tenantId&&(s.tenantId=r.tenantId),n("/connect/request",s)},clear:r=>i("/connect/request/clear",r??{})},call(r,s,a,c){return i(`/${u(a)}/${u(r)}/call/${u(s)}`,{args:c}).then(l=>l.data)}}}var On=Symbol.for("corsair:internal");function An(e,t){let o=e;for(let n of t){if(!o||typeof o!="object")return null;o=o[n]}return typeof o=="function"?o:null}function b(e){return e[On]?.database}async function Ln(e,t){let o=new Date().toISOString(),n=await e.permissions.find_by_token(t);if(!n)return console.error("executePermission: no permission found for token."),{error:"executePermission: no permission found for token."};if(n.status!=="approved")return console.error(`executePermission: permission '${n.id}' is '${n.status}', expected 'approved'.`),{endpoint:n.endpoint,plugin:n.plugin,result:null,error:`executePermission: permission '${n.id}' is '${n.status}', expected 'approved'.`};if(n.expires_at<o){let a=b(e);return a&&await a.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",n.id).execute(),console.error(`executePermission: permission '${n.id}' has expired.`),{error:`executePermission: permission '${n.id}' has expired.`,endpoint:n.endpoint,plugin:n.plugin,result:null}}let i=n.tenant_id??"default",r=(e.withTenant?e.withTenant(i):e)[n.plugin];if(!r?.api)return console.error(`executePermission: plugin '${n.plugin}' not found or has no API on this corsair instance.`),{error:`executePermission: plugin '${n.plugin}' not found or has no API on this corsair instance.`,plugin:n.plugin,endpoint:n.endpoint,result:null};let s=An(r.api,n.endpoint.split("."));if(!s)return console.error(`executePermission: endpoint '${n.endpoint}' not found in plugin '${n.plugin}'.`),{endpoint:n.endpoint,plugin:n.plugin,result:null,error:`executePermission: endpoint '${n.endpoint}' not found in plugin '${n.plugin}'.`};await e.permissions.set_executing(n.id);try{let a=typeof n.args=="string"?JSON.parse(n.args):n.args,c=await s(a);return await e.permissions.set_completed(n.id),{plugin:n.plugin,endpoint:n.endpoint,result:c}}catch(a){let c=a instanceof Error?a.message:String(a),l=b(e);return l&&await l.db.updateTable("corsair_permissions").set({status:"failed",error:c,updated_at:new Date}).where("id","=",n.id).execute(),{plugin:n.plugin,endpoint:n.endpoint,result:null,error:c}}}export{Z as AuthMissingError,J as CloudApiError,d as CorsairClientError,z as CorsairKekMissingError,B as DEFAULT_BODY_STALL_TIMEOUT_MS,j as DEFAULT_MAX_BODY_BYTES,W as ManagementApiError,M as PermissionRequiredError,$ as ReadonlyForbiddenError,S as ReconnectRequiredError,gn as asRecord,Pn as buildCorsairTools,ln as collectPluginWebhookMatchers,Y as corsairCloud,kn as createCorsair,Sn as createCorsairClient,yn as decodePubSubData,Ln as executePermission,fn as firstString,f as formFieldToZod,x as formatDocSchemaShape,dn as getHeader,h as getInputSchema,hn as getSchema,k as getStructuredSchema,y as listOperations,K as managementHandler,cn as matchWebhookPlugin,pn as matchWebhookPluginAndTenant,N as processCorsair,q as processWebhook,Cn as readBodyRecord,X as registerCorsairRawBodyParser,L as resolveAccountFromWebhookLink,U as resolveBodyStallTimeoutMs,F as resolveConnectLink,D as resolveMaxBodyBytes,v as resolveTenantFromWebhookLink,E as resolveTenantIdFromWebhookLink,H as runReadonly,_ as runWithMode,A as setWebhookTenantLink,O as setupCorsair,on as toAstroHandler,G as toExpressHandler,mn as toExternalId,Q as toFastifyHandler,V as toHonoHandler,nn as toNextJsHandler,en as toNodeHandler,an as toNuxtHandler,rn as toRemixHandler,tn as toSvelteKitHandler,sn as toTanStackHandler,un as toWebHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Na as a,Oa as b,Pa as c}from"./chunk-
|
|
1
|
+
import{Na as a,Oa as b,Pa as c}from"./chunk-KUNMGJBS.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{a as deriveAck,b as pollOnce,c as startConnectLoop};
|
package/dist/oauth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{J as a,K as b,Q as c,R as d,S as e,T as f,U as g,V as h}from"./chunk-
|
|
1
|
+
import{J as a,K as b,Q as c,R as d,S as e,T as f,U as g,V as h}from"./chunk-KUNMGJBS.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{d as OAuthCallbackError,c as buildOAuthAuthorizeUrl,b as decodeOAuthState,a as encodeOAuthState,e as generateOAuthUrl,f as processOAuthCallback,g as renewSubscriptions,h as startSubscriptionRenewal};
|
package/dist/orm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-B6OSDOR5.js";import{O as o,P as e,Q as n,R as s}from"./chunk-
|
|
1
|
+
import"./chunk-B6OSDOR5.js";import{O as o,P as e,Q as n,R as s}from"./chunk-PQ2CF2OI.js";import{d as r,e as t,f as i,g as a}from"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{t as CorsairAccountsSchema,i as CorsairEntitiesSchema,a as CorsairEventsSchema,r as CorsairIntegrationsSchema,o as createCorsairOrm,e as createPluginOrm,s as createPluginOrmFactory,n as createTenantScopedOrm};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{H as a,I as b}from"./chunk-
|
|
1
|
+
import{H as a,I as b}from"./chunk-KUNMGJBS.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{b as applySetupCredentials,a as setupCorsair};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{W as a,X as b,Y as c,Z as d}from"./chunk-
|
|
1
|
+
import{W as a,X as b,Y as c,Z as d}from"./chunk-KUNMGJBS.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{b as buildConnectPluginManifest,a as buildConnectPluginManifestFromContext,d as ensureConnectAccountRows,c as ensureConnectAccountRowsFromContext};
|
package/dist/setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{H as a,I as b}from"./chunk-
|
|
1
|
+
import{H as a,I as b}from"./chunk-KUNMGJBS.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{b as applySetupCredentials,a as setupCorsair};
|
package/dist/tunnel.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Fa as f,Ga as g,Ha as h,Ia as i,Ja as j,Ka as k,La as l,M as b,Ma as m,N as c,O as d,P as e,s as a}from"./chunk-
|
|
1
|
+
import{Fa as f,Ga as g,Ha as h,Ia as i,Ja as j,Ka as k,La as l,M as b,Ma as m,N as c,O as d,P as e,s as a}from"./chunk-KUNMGJBS.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-PQ2CF2OI.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{l as applyPermissionDecision,f as executeWorkflowRun,h as isAuthCredentialsBrowserDelivery,k as isByoOAuthBrowserDelivery,j as isManagedBrowserDelivery,i as isPermissionBrowserDelivery,m as processCorsair,c as resolveAccountFromWebhookLink,e as resolveTenantFromWebhookLink,d as resolveTenantIdFromWebhookLink,g as runReadonlyProbe,b as setWebhookTenantLink,a as verifyBrowserDeliveryToken};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "corsair",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.10",
|
|
4
4
|
"description": "Open-source integration layer for AI agents and apps. Managed OAuth, webhooks, and one API for 350+ integrations, with credentials that stay in your own database.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -89,11 +89,11 @@
|
|
|
89
89
|
},
|
|
90
90
|
"optionalDependencies": {
|
|
91
91
|
"@corsair-dev/frpc-darwin-arm64": "0.1.117",
|
|
92
|
+
"@corsair-dev/frpc-linux-arm64": "0.1.117",
|
|
92
93
|
"@corsair-dev/frpc-darwin-x64": "0.1.117",
|
|
93
94
|
"@corsair-dev/frpc-linux-x64": "0.1.117",
|
|
94
95
|
"@corsair-dev/frpc-win32-arm64": "0.1.117",
|
|
95
|
-
"@corsair-dev/frpc-win32-x64": "0.1.117"
|
|
96
|
-
"@corsair-dev/frpc-linux-arm64": "0.1.117"
|
|
96
|
+
"@corsair-dev/frpc-win32-x64": "0.1.117"
|
|
97
97
|
},
|
|
98
98
|
"devDependencies": {
|
|
99
99
|
"@testing-library/react": "^16.3.2",
|
package/dist/chunk-QUO2PWXT.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as ce,e as ue,f as de,g as le}from"./chunk-XPXWKPFZ.js";var Ze=Symbol.for("corsair:internal"),K=class extends Error{constructor(t="Invalid corsair instance"){super(t),this.name="InvalidCorsairInstanceError"}};function z(e){return typeof e=="object"&&e!==null}function ye(e){if(!z(e)||!Array.isArray(e.plugins)||typeof e.kek!="string"||typeof e.multiTenancy!="boolean")return!1;if(e.database===void 0)return!0;if(!z(e.database))return!1;let t=e.database.db;return typeof t=="object"&&t!==null&&typeof t.selectFrom=="function"}function fe(e){if(!e||typeof e!="object")return;let n=Object.getOwnPropertyDescriptor(e,Ze)?.value;return ye(n)?n:void 0}function Je(e,t){let n=fe(e);if(!n)throw t?.()??new K;return n}function ge(e,t){return e.plugins.find(n=>n.id===t)}function Qe(e,t,n){let r=ge(e,t);if(!r)throw n(`Plugin '${t}' not found`);return r}function ze(e){return"withTenant"in e&&typeof e.withTenant=="function"}function He(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="function"?(...r)=>Reflect.apply(n,e,r):void 0}var H={oauth_2:{integration:["client_id","client_secret","redirect_url"],account:["access_token","refresh_token","expires_at","scope","webhook_signature"]},api_key:{integration:[],account:["api_key","webhook_signature"]},bot_token:{integration:[],account:["bot_token","webhook_signature"]},managed:{integration:[],account:["access_token","refresh_token","expires_at","scope","webhook_signature"]},managed_pricing:{integration:[],account:[]}};function pe(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"||e==="managed"||e==="managed_pricing"}function Ge(e){let t=e.options?.authType;return pe(t)?t:void 0}function Ot(e){return e==="managed_pricing"}function qe(e,t){let n=e.authConfig,r=H[t].account,i=n?.[t]?.account??[];return[...r,...i]}function vt(e,t){let n=e.authConfig,r=H[t].integration,i=n?.[t]?.integration??[];return[...r,...i]}import{createCipheriv as me,createDecipheriv as we,randomBytes as O,scrypt as Ye}from"crypto";import{promisify as Xe}from"util";var be=Xe(Ye),v="aes-256-gcm",he=12,$=16,Ve=16,G=32;function q(){return O(G).toString("base64")}async function Y(e,t){let n=O(Ve),r=await be(t,n,G),i=O(he),o=me(v,r,i,{authTagLength:$}),a=Buffer.concat([o.update(e,"utf8"),o.final()]),l=o.getAuthTag();return[n.toString("base64"),i.toString("base64"),l.toString("base64"),a.toString("base64")].join(":")}async function F(e,t){let[n,r,i,o]=e.split(":");if(!n||!r||!i||!o)throw new Error("Invalid encrypted DEK format");let a=Buffer.from(n,"base64"),l=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),b=Buffer.from(o,"base64"),u=await be(t,a,G),s=we(v,u,l,{authTagLength:$});return s.setAuthTag(p),Buffer.concat([s.update(b),s.final()]).toString("utf8")}function X(e,t){let n=Buffer.from(t,"base64"),r=O(he),i=me(v,n,r,{authTagLength:$}),o=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[r.toString("base64"),a.toString("base64"),o.toString("base64")].join(":")}function V(e,t){let[n,r,i]=e.split(":");if(!n||!r||!i)throw new Error("Invalid encrypted data format");let o=Buffer.from(t,"base64"),a=Buffer.from(n,"base64"),l=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),b=we(v,o,a,{authTagLength:$});return b.setAuthTag(l),Buffer.concat([b.update(p),b.final()]).toString("utf8")}function ee(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=X(i,t);return n}function j(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=V(i,t);return n}function Lt(e,t,n){let r=j(e,t);return ee(r,n)}import{v7 as et}from"uuid";function P(){return et()}function M(e,t){return e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t.tenantId).where("integration_id","=",t.integrationId).orderBy("created_at","asc").orderBy("id","asc")}async function B(e,t){return M(e,t).executeTakeFirst()}async function tt(e){let t=!1;for(;;){let n=await e.database.db.selectFrom("corsair_integrations").selectAll().where("name","=",e.integrationName).executeTakeFirst();if(!n){if(!t&&e.ensureProvisioned){t=!0,await e.ensureProvisioned();continue}throw new Error(`Integration "${e.integrationName}" not found. Make sure to create the integration first.`)}let r={tenantId:e.tenantId,integrationId:n.id},i=e.account?await ot({db:e.database.db,kek:e.account.kek,...r,ref:e.account.ref}):await B(e.database.db,r);if(!i){if(!t&&e.ensureProvisioned){t=!0,await e.ensureProvisioned();continue}throw new Error(`Account not found for tenant "${e.tenantId}" and integration "${e.integrationName}". Make sure to create the account first.`)}return{integrationId:n.id,accountId:i.id,integration:{id:n.id,config:n.config,dek:n.dek??null},account:{id:i.id,config:i.config,dek:i.dek??null}}}}async function rn(e){let{integrationId:t,accountId:n}=await tt(e);return{integrationId:t,accountId:n}}var S=class extends Error{code;accounts;constructor(t,n,r=[]){super(n),this.name="AccountSelectionError",this.code=t,this.accounts=r}};function re(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e??{}}var ne=e=>({id:e.id,config:e.config,dek:e.dek??null});async function L(e,t){let n=re(e.config);if(!e.dek||!n?.account_ref)return{};try{let r=j(n,await F(e.dek,t));return{ref:r.account_ref,label:r.account_label}}catch{return{}}}async function on(e,t,n){if(e.id===t)return!0;let{ref:r,label:i}=await L(e,n);return r===t||i?.toLowerCase()===t.toLowerCase()}async function an(e,t,n){let r=n?await e.selectFrom("corsair_accounts").select(["config","dek"]).where("id","=",t).executeTakeFirst():void 0;return{id:t,...r&&n?await L(r,n):{}}}function nt(e){let t=new Set(e),n=1;for(;t.has(`Account ${n}`);)n++;return`Account ${n}`}var ke=(e,t)=>Promise.all(e.map(async n=>({...ne(n),...await L(n,t)})));async function Te(e){return ke(await M(e.db,e).execute(),e.kek)}var rt=e=>e.label??e.ref??e.id,W=({id:e,ref:t,label:n})=>({id:e,ref:t,label:n});async function sn(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();if(!t)return[];let n=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",e.tenantId).where("integration_id","=",t.id).execute();return n.length<2?n:(await Te({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(i=>({id:i.id,label:i.label??i.ref}))}async function cn(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();return t?(await Te({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(W):[]}async function it(e,t){return(await e.selectFrom("corsair_integrations").select("name").where("id","=",t).executeTakeFirst())?.name??t}async function ot(e){let t=await M(e.db,e).execute();if(t.length===0)return;if(!e.ref&&t.length===1)return ne(t[0]);let n=e.ref?t.find(u=>u.id===e.ref):void 0;if(n)return ne(n);let r=await ke(t,e.kek),i=e.ref?.toLowerCase(),o=e.ref?r.find(u=>u.ref===e.ref):void 0;if(o)return o;let a=e.ref?r.filter(u=>u.label?.toLowerCase()===i):[];if(a.length===1)return a[0];let l=await it(e.db,e.integrationId);if(a.length>1)throw new S("account_required",`Label "${e.ref}" matches ${a.length} accounts for "${l}" (tenant "${e.tenantId}"): ${a.map(u=>u.ref??u.id).join(", ")}. Name one by its id.`,a.map(W));let p=r.map(rt).join(", "),b=r.map(W);throw e.ref?new S("account_not_found",`No account "${e.ref}" for "${l}" (tenant "${e.tenantId}"). Accounts: ${p}.`,b):new S("account_required",`Plugin "${l}" has ${r.length} accounts for tenant "${e.tenantId}": ${p}. Name one with withTenant(tenantId, { accounts: { ${l}: "<account>" } }).`,b)}var at=5;async function un(e){let{database:t,kek:n,tenantId:r}=e;return t.db.transaction().execute(async i=>{let o=i.selectFrom("corsair_integrations").select(["id"]).where("name","=",e.integrationName);t.isPg===!0&&(o=o.forUpdate());let a=await o.executeTakeFirst();if(!a)throw new Error(`Integration '${e.integrationName}' not found. Run setupCorsair first.`);let l=await M(i,{tenantId:r,integrationId:a.id}).execute();if(!e.identity)return l[0]?{accountId:l[0].id,created:!1}:Ce(i,a.id,r,n);let p=await Promise.all(l.map(async w=>({row:w,...await L(w,n)}))),b=e.identity.label===void 0&&e.nameNew?{...e.identity,label:nt(p.map(w=>w.label))}:e.identity;if(e.rowId){let w=p.find(c=>c.row.id===e.rowId);if(!w)throw new S("account_not_found",`Account "${e.rowId}" is no longer connected for "${e.integrationName}" (tenant "${r}").`);return w.ref?{accountId:w.row.id,created:!1}:(await te(i,w.row,b,n),{accountId:w.row.id,created:!1})}let u=p.filter(w=>!w.ref),s=e.hubAccounts?.[0];u.length===1&&Object.keys(re(u[0].row.config)).length>0&&s&&s.id!==b.id&&!p.some(w=>w.ref===s.id)&&(await te(i,u[0].row,s,n),u[0].ref=s.id,u[0].label=s.label);let y=p.find(w=>w.ref===b.id),m=y??p.find(w=>!w.ref)??(e.allowMany?void 0:p[0]);if(m){if(!y||b.label&&m.label!==b.label){let w=!y&&m.ref!==void 0;await te(i,m.row,b,n,w)}return{accountId:m.row.id,created:!1}}if(l.length>=at)throw new S("account_limit",`Account limit reached: tenant "${r}" already has ${l.length} accounts for "${e.integrationName}".`,p.map(({row:w,ref:c,label:d})=>W({id:w.id,ref:c,label:d})));return Ce(i,a.id,r,n,b)})}async function Ae(e,t,n){let{account_label:r,...i}=t;return ee({...i,account_ref:n.id,...n.label?{account_label:n.label}:{}},e)}async function te(e,t,n,r,i=!1){let o=t.dek?await F(t.dek,r):q(),a=re(t.config),l=i?{}:t.dek?j(a,o):a;await e.updateTable("corsair_accounts").set({config:await Ae(o,l,n),dek:t.dek??await Y(o,r),updated_at:new Date}).where("id","=",t.id).execute()}async function Ce(e,t,n,r,i){let o=q(),a=new Date,l=P();return await e.insertInto("corsair_accounts").values({id:l,created_at:a,updated_at:a,tenant_id:n,integration_id:t,config:i?await Ae(o,{},i):{},dek:await Y(o,r)}).execute(),{accountId:l,created:!0}}import{SqliteAdapter as st,sql as Ke}from"kysely";import{z as A}from"zod";var ie="_corsair_enc";function Ie(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t[ie]=="string"&&Object.keys(t).length===1}function oe(e,t){return{[ie]:X(JSON.stringify(e),t)}}function ae(e,t){let n=Ee(e);return Ie(n)?JSON.parse(V(n[ie],t)):n}async function fn(e,t,n){let r=await e.selectFrom("corsair_accounts").select("dek").where("id","=",t).executeTakeFirst();if(!r?.dek)throw new Error(`No DEK found for account "${t}". Initialize the account first.`);return F(r.dek,n)}async function gn(e,t,n,r){let i=await e.selectFrom("corsair_entities").select(["id","data"]).where("account_id","=",t).execute();for(let a of i){let l=xe(a.data,n,r);l&&await e.updateTable("corsair_entities").set({data:l,updated_at:new Date}).where("id","=",a.id).execute()}let o=await e.selectFrom("corsair_events").select(["id","payload"]).where("account_id","=",t).execute();for(let a of o){let l=xe(a.payload,n,r);l&&await e.updateTable("corsair_events").set({payload:l,updated_at:new Date}).where("id","=",a.id).execute()}}function xe(e,t,n){let r=Ee(e);if(Ie(r))return oe(ae(r,t),n)}function Ee(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}import{sql as D}from"kysely";function U(e){return e.replace(/'/g,"''")}function _e(e){let t=U(e);return D`data->>'${D.raw(t)}'`}function De(e){let t=U(e);return D`(data->>'${D.raw(t)}')::numeric`}function Fe(e){let t=U(e);return D`(data->>'${D.raw(t)}')::boolean`}function Pe(e){let t=U(e);return D`(data->>'${D.raw(t)}')::timestamptz`}import{sql as Z}from"kysely";function Se(e){return e.replace(/'/g,"''").replace(/\\/g,"\\\\")}function Re(e){let t=Se(e);return Z`CAST(json_extract(data, '$.${Z.raw(t)}') AS REAL)`}function Be(e){let t=Se(e);return Z`json_extract(data, '$.${Z.raw(t)}')`}var ct={number:e=>De(e),booleanEquals:(e,t)=>Ke`${Fe(e)} = ${t}`,timestamp:e=>Pe(e)},ut={number:e=>Re(e),booleanEquals:(e,t)=>Ke`json_extract(data, ${`$.${e}`}) = ${t?1:0}`,timestamp:e=>Be(e)};function dt(e){return e.getExecutor().adapter instanceof st?ut:ct}function lt(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function Oe(e){let t=e;for(;t;){if(t instanceof A.ZodOptional||t instanceof A.ZodNullable){t=t._def.innerType;continue}if(t instanceof A.ZodDefault){t=t._def.innerType;continue}break}return t}function Ne(e){if(typeof e=="string")return"string";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}function se(e){let[t]=e;return t&&e.every(n=>n===t)?t:void 0}function ve(e){let t=Oe(e);if(t instanceof A.ZodString)return"string";if(t instanceof A.ZodNumber)return"number";if(t instanceof A.ZodBoolean)return"boolean";if(t instanceof A.ZodDate)return"date";if(t instanceof A.ZodEnum)return se(t.options.map(Ne));if(t instanceof A.ZodLiteral)return se([...t.values].map(Ne));if(t instanceof A.ZodUnion)return se(t.options.filter(n=>!(n instanceof A.ZodNull)).map(n=>ve(n)))}function yt(e){let t=Oe(e);if(!(t instanceof A.ZodObject))return{};let n=t.shape,r={};for(let[i,o]of Object.entries(n)){let a=ve(o);a&&(r[i]=a)}return r}function ft(e,t,n){if(typeof n=="string")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;"equals"in r&&typeof r.equals=="string"&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function gt(e,t,n){if(typeof n=="number")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="number"&&(e=e.where(t,"=",r.equals)),typeof r.gt=="number"&&(e=e.where(t,">",r.gt)),typeof r.gte=="number"&&(e=e.where(t,">=",r.gte)),typeof r.lt=="number"&&(e=e.where(t,"<",r.lt)),typeof r.lte=="number"&&(e=e.where(t,"<=",r.lte)),Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function pt(e,t,n){if(typeof n=="boolean")return e.where(t(n));if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="boolean"&&(e=e.where(t(r.equals)))}return e}function mt(e,t,n){if(n instanceof Date)return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;if(r.equals instanceof Date&&(e=e.where(t,"=",r.equals)),r.before instanceof Date&&(e=e.where(t,"<",r.before)),r.after instanceof Date&&(e=e.where(t,">",r.after)),Array.isArray(r.between)&&r.between.length===2){let[i,o]=r.between;i instanceof Date&&(e=e.where(t,">=",i)),o instanceof Date&&(e=e.where(t,"<=",o))}}return e}function wt(e,t,n,r,i){return r==="number"?gt(e,t.number(n),i):r==="boolean"?pt(e,o=>t.booleanEquals(n,o),i):r==="date"?mt(e,t.timestamp(n),i):ft(e,_e(n),i)}function bt(e,t,n){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;return"equals"in r&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in)),e}return e.where(t,"=",n)}function ht(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function $e(e,t){return Array.isArray(t)?e("account_id","in",t):e("account_id","=",t)}function R(e,t,n){let r=e.selectFrom("corsair_entities").selectAll().where(i=>$e(i,t)).where("entity_type","=",n);return Array.isArray(t)?r.orderBy("created_at").orderBy("id"):r}function je(e,t,n,r,i,o,a){let l=yt(i),p=new Map,b=async c=>{if(!o?.kek)throw new Error("encryptDataAtRest requires kek");let d=await e.selectFrom("corsair_accounts").select("dek").where("id","=",c).executeTakeFirst();if(!d?.dek)throw new Error(`No DEK found for account "${c}". Initialize the account first.`);let f=p.get(c);if(f&&f.wrapped===d.dek)return f.dek;let g=await F(d.dek,o.kek);return p.set(c,{wrapped:d.dek,dek:g}),g};async function u(c,d){let f=lt(c.data);return o&&(f=ae(f,d??await b(c.account_id))),{...c,data:i.parse(f)}}async function s(){let c=a?await a():[];return c.length<2?{ids:await t()}:{ids:c.map(d=>d.id),labels:new Map(c.map(d=>[d.id,d.label??d.id]))}}async function y(c){let{ids:d,labels:f}=await s(),C=await R(e,d,n).where("entity_id","=",c).execute();return Array.isArray(d)?(C.sort((I,x)=>d.indexOf(I.account_id)-d.indexOf(x.account_id)),{row:C[0],labels:f}):{row:C[0],labels:f}}async function m(c,d){let f=new Map;return o&&await Promise.all([...new Set(c.map(g=>g.account_id))].map(async g=>f.set(g,await b(g)))),Promise.all(c.map(async g=>{let C=await u(g,f.get(g.account_id)),I=d?.get(g.account_id);return I?{...C,account:I}:C}))}async function w(c,d){return o?oe(d,await b(c)):d}return{findByEntityId:async c=>{let{row:d,labels:f}=await y(c);return d?(await m([d],f))[0]:null},existsByEntityId:async c=>{let{ids:d}=await s();return await R(e,d,n).select("id").where("entity_id","=",c).executeTakeFirst()!==void 0},findIdByEntityId:async c=>{let{row:d}=await y(c);return d?.id??null},findById:async c=>{let{ids:d,labels:f}=await s(),g=await R(e,d,n).where("id","=",c).executeTakeFirst();return g?(await m([g],f))[0]:null},findManyByEntityIds:async c=>{if(c.length===0)return[];let{ids:d,labels:f}=await s(),g=await R(e,d,n).where("entity_id","in",c).execute();return m(g,f)},list:async c=>{let{ids:d,labels:f}=await s(),g=R(e,d,n);typeof c?.limit=="number"&&(g=g.limit(c.limit)),typeof c?.offset=="number"&&(g=g.offset(c.offset));let C=await g.execute();return m(C,f)},search:async c=>{if(o&&c.data&&typeof c.data=="object"&&Object.keys(c.data).length>0)throw new Error("Entity JSON field search cannot run while encryptDataAtRest is enabled. The stored document is ciphertext.");let{ids:d,labels:f}=await s(),g=R(e,d,n),C=new Set(["data","limit","offset"]);for(let[x,_]of Object.entries(c))C.has(x)||_===void 0||(g=bt(g,x,_));if(c.data&&typeof c.data=="object")for(let[x,_]of Object.entries(c.data)){if(_===void 0)continue;let Q=l[x]??"string";g=wt(g,dt(e),x,Q,_)}typeof c.limit=="number"&&(g=g.limit(c.limit)),typeof c.offset=="number"&&(g=g.offset(c.offset));let I=await g.execute();return m(I,f)},upsertByEntityId:async(c,d)=>{let f=await t(),g=i.parse(d),C=await w(f,g),I=new Date,x=await R(e,f,n).select("id").where("entity_id","=",c).executeTakeFirst();if(x?.id){await e.updateTable("corsair_entities").set({version:r,data:C,updated_at:I}).where("id","=",x.id).execute();let Ue=await e.selectFrom("corsair_entities").selectAll().where("id","=",x.id).executeTakeFirst();return u(Ue)}let _=P();await e.insertInto("corsair_entities").values({id:_,created_at:I,updated_at:I,account_id:f,entity_id:c,entity_type:n,version:r,data:C}).execute();let Q=await e.selectFrom("corsair_entities").selectAll().where("id","=",_).executeTakeFirst();return u(Q)},deleteById:async c=>{let d=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",d).where("entity_type","=",n).where("id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},deleteByEntityId:async c=>{let d=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",d).where("entity_type","=",n).where("entity_id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},count:async()=>{let{ids:c}=await s(),d=await e.selectFrom("corsair_entities").select(f=>f.fn.countAll().as("count")).where(f=>$e(f,c)).where("entity_type","=",n).executeTakeFirst();return ht(d?.count)}}}var Ct={corsair_integrations:ce,corsair_accounts:ue,corsair_entities:de,corsair_events:le};function kt(e){return Ct[e]}function We(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function h(e){if(!e)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function N(e){if(!e)return[];let t=[];for(let n in e){let r=n,i=e[r];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let o=i;"in"in o&&Array.isArray(o.in)?t.push({field:r,operator:"in",value:o.in}):"like"in o&&typeof o.like=="string"&&t.push({field:r,operator:"like",value:o.like})}else t.push({field:r,value:i})}return t}function E(e,t){if(!t?.length)return e;let n=e;for(let r of t){let i=r.operator??"=";n=n.where(r.field,i,r.value)}return n}function Tt(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function J(e,t){let n=kt(t),r=()=>(h(e),e),i=()=>r().db.selectFrom(t),o=()=>r().db.insertInto(t),a=()=>r().db.updateTable(t),l=()=>r().db.deleteFrom(t);function p(u){let s={};for(let[y,m]of Object.entries(u))s[y]=We(m);return n.parse(s)}function b(u){let s={};for(let[y,m]of Object.entries(u))s[y]=We(m);return n.parse(s)}return{findById:async u=>{h(e);let s=i().selectAll();s=E(s,[{field:"id",value:u}]);let y=await s.executeTakeFirst();return y?p(y):null},findOne:async u=>{h(e);let s=i().selectAll();s=E(s,N(u));let y=await s.executeTakeFirst();return y?p(y):null},findMany:async u=>{h(e);let s=i().selectAll();return s=E(s,N(u?.where)),typeof u?.limit=="number"&&(s=s.limit(u.limit)),typeof u?.offset=="number"&&(s=s.offset(u.offset)),(await s.execute()).map(m=>p(m))},create:async u=>{h(e);let s=new Date,y={id:u.id??P(),created_at:s,updated_at:s,...u},m=await o().values(y).returningAll().executeTakeFirst();return m?p(m):b(y)},update:async(u,s)=>{h(e);let y={...s,updated_at:new Date},m=a().set(y).returningAll();m=E(m,[{field:"id",value:u}]);let w=await m.executeTakeFirst();return w?p(w):null},updateMany:async(u,s)=>{h(e);let y={...s,updated_at:new Date},m=i().select("id");m=E(m,N(u));let w=await m.execute();for(let c of w){let d=a().set(y);d=E(d,[{field:"id",value:c.id}]),await d.execute()}return w.length},delete:async u=>{h(e);let s=l();s=E(s,[{field:"id",value:u}]);let y=await s.executeTakeFirst();return Number(y?.numDeletedRows??0)>0},deleteMany:async u=>{h(e);let s=l();s=E(s,N(u));let y=await s.executeTakeFirst();return Number(y?.numDeletedRows??0)},count:async u=>{h(e);let s=i().select(m=>m.fn.countAll().as("count"));s=E(s,N(u));let y=await s.executeTakeFirst();return Tt(y?.count)}}}function At(e){let t=J(e,"corsair_integrations");return{...t,findByName:n=>t.findOne({name:n}),upsertByName:async(n,r)=>{let i=await t.findOne({name:n});return i?await t.update(i.id,r):t.create({...r,name:n})}}}function xt(e){let t=J(e,"corsair_accounts");return{...t,findByTenantAndIntegration:async(n,r)=>{h(e);let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!i)return null;let o=await B(e.db,{tenantId:n,integrationId:i.id});return o?t.findOne({id:o.id,tenant_id:n,integration_id:i.id}):null},listByTenant:(n,r)=>t.findMany({where:{tenant_id:n},limit:r?.limit,offset:r?.offset}),upsertByTenantAndIntegration:async(n,r,i)=>{h(e);let o=await B(e.db,{tenantId:n,integrationId:r});return o?await t.update(o.id,i):t.create({...i,tenant_id:n,integration_id:r})}}}function It(e){let t=J(e,"corsair_entities");return{...t,findByEntityId:({accountId:n,entityType:r,entityId:i})=>t.findOne({account_id:n,entity_type:r,entity_id:i}),findManyByEntityIds:async({accountId:n,entityType:r,entityIds:i})=>i.length===0?[]:(h(e),await e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","in",i).execute()),listByScope:({accountId:n,entityType:r,limit:i,offset:o})=>t.findMany({where:{account_id:n,entity_type:r},limit:i,offset:o}),searchByEntityId:async({accountId:n,entityType:r,query:i,limit:o,offset:a})=>{h(e);let l=e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","like",`%${i}%`);return typeof o=="number"&&(l=l.limit(o)),typeof a=="number"&&(l=l.offset(a)),await l.execute()},upsertByEntityId:async({accountId:n,entityType:r,entityId:i,version:o,data:a})=>{let l=await t.findOne({account_id:n,entity_type:r,entity_id:i});return l?await t.update(l.id,{version:o,data:a}):t.create({account_id:n,entity_type:r,entity_id:i,version:o,data:a})},deleteByEntityId:async({accountId:n,entityType:r,entityId:i})=>{h(e);let o=await e.db.deleteFrom("corsair_entities").where("account_id","=",n).where("entity_type","=",r).where("entity_id","=",i).executeTakeFirst();return Number(o.numDeletedRows)>0}}}function Et(e){let t=J(e,"corsair_events");return{...t,listByAccount:(n,r)=>t.findMany({where:{account_id:n},limit:r?.limit,offset:r?.offset}),listByStatus:(n,r)=>{let i={status:n};return r?.accountId&&(i.account_id=r.accountId),t.findMany({where:i,limit:r?.limit,offset:r?.offset})},listPending:n=>{let r={status:"pending"};return n?.accountId&&(r.account_id=n.accountId),t.findMany({where:r,limit:n?.limit??100})},updateStatus:(n,r)=>t.update(n,{status:r})}}function Me(e){return{integrations:At(e),accounts:xt(e),entities:It(e),events:Et(e)}}function _t(e){if(e.encryptDataAtRest===!0)return{encryptDataAtRest:!0,kek:e.kek??""}}function Dt(e,t,n,r,i,o){let a=null;async function l(){if(a!==null)return a;h(e);let p=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t.integrationName).executeTakeFirst();if(!p)throw new Error(`Integration "${t.integrationName}" not found. Make sure to create the integration first.`);let b=await B(e.db,{tenantId:t.tenantId,integrationId:p.id});if(!b)throw new Error(`Account not found for tenant "${t.tenantId}" and integration "${t.integrationName}". Make sure to create the account first.`);return a=b.id,a}return h(e),je(e.db,l,n,r,i,o)}function Le(e){let{database:t,integrationName:n,schema:r,tenantId:i}=e,o=_t(e),a=Me(t),l={tenantId:i,integrationName:n},p=null;async function b(){if(p!==null)return p;h(t);let s=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!s)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let y=await B(t.db,{tenantId:i,integrationId:s.id});if(!y)throw new Error(`Account not found for tenant "${i}" and integration "${n}". Make sure to create the account first.`);return p=y.id,p}let u={};for(let[s,y]of Object.entries(r.entities))u[s]=Dt(t,l,s,r.version,y,o);return{...u,$orm:a,$integrationName:n,$tenantId:i,$getAccountId:b}}function On(e,t){let n=Me(e);return{$tenantId:t,$orm:n,listAccounts:r=>n.accounts.listByTenant(t,r),findAccountByIntegration:r=>n.accounts.findByTenantAndIntegration(t,r),listEntities:async r=>{h(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(l=>l.id),a=e.db.selectFrom("corsair_entities").selectAll().where("account_id","in",o);return r?.entityType&&(a=a.where("entity_type","=",r.entityType)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},listEvents:async r=>{h(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(l=>l.id),a=e.db.selectFrom("corsair_events").selectAll().where("account_id","in",o);return r?.status&&(a=a.where("status","=",r.status)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},forIntegration:r=>Le({database:e,integrationName:r.integrationName,schema:r.schema,tenantId:t,encryptDataAtRest:r.encryptDataAtRest,kek:r.kek})}}function vn(e,t){return{forTenant:n=>Le({database:e,integrationName:t.integrationName,schema:t.schema,tenantId:n,encryptDataAtRest:t.encryptDataAtRest,kek:t.kek})}}export{K as a,z as b,fe as c,Je as d,Qe as e,ze as f,He as g,H as h,Ge as i,Ot as j,qe as k,vt as l,G as m,q as n,Y as o,F as p,X as q,V as r,ee as s,j as t,Lt as u,Ie as v,oe as w,ae as x,fn as y,gn as z,P as A,B,rn as C,S as D,L as E,on as F,an as G,sn as H,cn as I,ot as J,at as K,un as L,je as M,Ct as N,Me as O,Le as P,On as Q,vn as R};
|