corsair 0.1.52 → 0.1.54

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.
@@ -0,0 +1 @@
1
+ import{a as t}from"./chunk-QAIKSQAD.js";import{Kysely as r,PostgresDialect as o,SqliteDialect as s}from"kysely";function i(e){return typeof e.query=="function"&&typeof e.connect=="function"}function n(e){let a=e;return typeof a.prepare=="function"&&typeof a.exec=="function"&&typeof a.close=="function"&&!("query"in e)}function y(e){return typeof e.selectFrom=="function"}function p(e){if(y(e))return{db:e};if(n(e))return{db:new r({dialect:new s({database:e}),plugins:[new t]})};if(i(e))return{db:new r({dialect:new o({pool:e})})};throw new Error("Unsupported database input. Expected a pg Pool, better-sqlite3 Database, or a Kysely instance.")}export{p as a};
@@ -0,0 +1 @@
1
+ import{OperationNodeTransformer as a}from"kysely";function n(r){return r instanceof Date?r.toISOString():r!==null&&typeof r=="object"&&!Buffer.isBuffer(r)?JSON.stringify(r):r}var s=class extends a{transformValue(e){let t=n(e.value);return t===e.value?e:{...e,value:t}}transformPrimitiveValueList(e){let t=e.values.map(n);return t.some((u,i)=>u!==e.values[i])?{...e,values:t}:e}},l=new s,o=class{transformQuery(e){return l.transformNode(e.node)}async transformResult(e){return e.result}};export{o as a};
@@ -1,4 +1,4 @@
1
- import{q as k,r as w}from"./chunk-ZWWGVPSP.js";import{a as m}from"./chunk-7IH5DNUL.js";import{ZodBoolean as h,ZodDate as _,ZodEffects as $,ZodEnum as P,ZodNullable as K,ZodNumber as M,ZodObject as T,ZodOptional as v,ZodRecord as A,ZodString as j}from"zod";var b={slack:{channels:{list:{}},users:{list:{}}},linear:{projects:{list:{}},issues:{list:{}},users:{list:{}}},github:{issues:{list:{}},pullRequests:{list:{}},repositories:{list:{}}},discord:{guilds:{list:{}},channels:{list:{}}},hubspot:{contacts:{getMany:{}},companies:{getMany:{}},deals:{getMany:{}}},gmail:{messages:{list:{}},labels:{list:{}},drafts:{list:{}},threads:{list:{}}},googlecalendar:{events:{getMany:{}}},googledrive:{files:{list:{}},folders:{list:{}},sharedDrives:{list:{}}},notion:{databases:{getManyDatabases:{}},databasePages:{getManyDatabasePages:{}},users:{getManyUsers:{}}},airtable:{bases:{getMany:{}}},todoist:{projects:{getMany:{}},tasks:{getMany:{}}},cal:{bookings:{list:{}}}};async function Y(e,c){let l=[],r=t=>{l.push(t),console.log(t)},o=t=>{l.push(t),console.warn(t)},g=c?.caller??"script",s=e[k];if(!s)throw new Error("setupCorsair: invalid corsair instance");if(s.multiTenancy)throw new Error("setupCorsair: multi-tenancy instances are not supported. Create your corsair instance without multiTenancy: true.");if(!s.database)throw new Error("setupCorsair: a database must be configured on the corsair instance");let u=s.database.db,n=w({plugins:s.plugins,database:s.database.db,kek:s.kek});await D(u,o),await E(u,n,s.plugins,r),c?.credentials&&Object.keys(c.credentials).length>0&&await I(n,c.credentials,r,o);let a=await Z(n,s.plugins,r,g);return c?.backfill&&(r("[corsair:setup] Starting backfill..."),await L(n,s.plugins,a,r,o),r("[corsair:setup] Backfill complete.")),l.join(`
1
+ import{q as k,r as w}from"./chunk-YE7LLFD4.js";import{a as m}from"./chunk-7IH5DNUL.js";import{ZodBoolean as h,ZodDate as _,ZodEffects as $,ZodEnum as P,ZodNullable as K,ZodNumber as M,ZodObject as T,ZodOptional as v,ZodRecord as A,ZodString as j}from"zod";var b={slack:{channels:{list:{}},users:{list:{}}},linear:{projects:{list:{}},issues:{list:{}},users:{list:{}}},github:{issues:{list:{}},pullRequests:{list:{}},repositories:{list:{}}},discord:{guilds:{list:{}},channels:{list:{}}},hubspot:{contacts:{getMany:{}},companies:{getMany:{}},deals:{getMany:{}}},gmail:{messages:{list:{}},labels:{list:{}},drafts:{list:{}},threads:{list:{}}},googlecalendar:{events:{getMany:{}}},googledrive:{files:{list:{}},folders:{list:{}},sharedDrives:{list:{}}},notion:{databases:{getManyDatabases:{}},databasePages:{getManyDatabasePages:{}},users:{getManyUsers:{}}},airtable:{bases:{getMany:{}}},todoist:{projects:{getMany:{}},tasks:{getMany:{}}},cal:{bookings:{list:{}}}};async function Y(e,c){let l=[],r=t=>{l.push(t),console.log(t)},o=t=>{l.push(t),console.warn(t)},g=c?.caller??"script",s=e[k];if(!s)throw new Error("setupCorsair: invalid corsair instance");if(s.multiTenancy)throw new Error("setupCorsair: multi-tenancy instances are not supported. Create your corsair instance without multiTenancy: true.");if(!s.database)throw new Error("setupCorsair: a database must be configured on the corsair instance");let u=s.database.db,n=w({plugins:s.plugins,database:s.database.db,kek:s.kek});await D(u,o),await E(u,n,s.plugins,r),c?.credentials&&Object.keys(c.credentials).length>0&&await I(n,c.credentials,r,o);let a=await Z(n,s.plugins,r,g);return c?.backfill&&(r("[corsair:setup] Starting backfill..."),await L(n,s.plugins,a,r,o),r("[corsair:setup] Backfill complete.")),l.join(`
2
2
  `)}var O={...m};function p(e){if(e instanceof T){let c={};for(let[l,r]of Object.entries(e.shape))c[l]=p(r);return c}return e instanceof $?p(e.innerType()):e instanceof K?`${p(e.unwrap())} | null`:e instanceof v?`${p(e.unwrap())} | undefined`:e instanceof P?e.options.join(" | "):e instanceof j?"string":e instanceof M?"number":e instanceof h?"boolean":e instanceof _?"date":e instanceof A?"jsonb":"unknown"}async function D(e,c){let l=await e.introspection.getTables(),r=new Set(l.map(o=>o.name));for(let[o,g]of Object.entries(O))r.has(o)||c(`[corsair:setup] Table "${o}" does not exist. Run your database migrations before calling setupCorsair.
3
3
  Schema: ${JSON.stringify(p(g),null,2)}`)}var C="default";async function E(e,c,l,r){let o=new Date,g=c.keys,s=c;for(let u of l){let n=u.id,a=await e.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!a){let f=crypto.randomUUID();await e.insertInto("corsair_integrations").values({id:f,name:n,config:{},created_at:o,updated_at:o}).execute(),a=await e.selectFrom("corsair_integrations").selectAll().where("id","=",f).executeTakeFirst(),r(`[corsair:setup] Created integration: ${n}`)}let t=g[n];if(a&&!a.dek&&t&&(await t.issue_new_dek(),r(`[corsair:setup] Issued integration DEK: ${n}`)),!a)continue;let i=await e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",C).where("integration_id","=",a.id).executeTakeFirst();if(!i){let f=crypto.randomUUID();await e.insertInto("corsair_accounts").values({id:f,tenant_id:C,integration_id:a.id,config:{},created_at:o,updated_at:o}).execute(),i=await e.selectFrom("corsair_accounts").selectAll().where("id","=",f).executeTakeFirst(),r(`[corsair:setup] Created account: ${n}`)}let d=s[n]?.keys;i&&!i.dek&&d&&(await d.issue_new_dek(),r(`[corsair:setup] Issued account DEK: ${n}`))}}async function I(e,c,l,r){let o=e.keys,g=e;for(let[s,u]of Object.entries(c)){let n=o[s],a=g[s]?.keys;for(let[t,i]of Object.entries(u)){let d=`set_${t}`;n&&typeof n[d]=="function"?(await n[d](i),l(`[corsair:setup] Set integration credential: ${s}.${t}`)):a&&typeof a[d]=="function"?(await a[d](i),l(`[corsair:setup] Set account credential: ${s}.${t}`)):r(`[corsair:setup] No setter found for '${s}.${t}' \u2014 skipping.`)}}}var S=new Set(["webhook_signature","expires_at","scope","redirect_url"]);async function x(e,c,l,r,o,g){let s=[],u=[];for(let a of Object.keys(l)){if(!a.startsWith("set_"))continue;let t=a.slice(4);if(S.has(t))continue;let i=l[`get_${t}`];if(!i)continue;let d=null;try{d=await i()}catch{}d||s.push(t)}for(let a of Object.keys(r)){if(!a.startsWith("set_"))continue;let t=a.slice(4);if(S.has(t))continue;let i=r[`get_${t}`];if(!i)continue;let d=null;try{d=await i()}catch{}d||u.push(t)}let n=s.length===0&&u.length===0;if(n)o(`[corsair:setup] '${e}' (${c}) is configured \u2713`);else{let a=[...s,...u];if(g==="cli"){let t=a.map(i=>`${i}=VALUE`).join(" ");o(`[corsair:setup] '${e}' (${c}) needs credentials. Run:
4
4
  corsair setup --${e} ${t}`)}else{let t=[`[corsair:setup] '${e}' (${c}) needs credentials. Call:`];for(let i of s)t.push(` await corsair.keys.${e}.set_${i}(value)`);for(let i of u)t.push(` await corsair.${e}.keys.set_${i}(value)`);o(t.join(`
@@ -1,4 +1,4 @@
1
- import{a as pe,b as Q}from"./chunk-2PB34FTK.js";import{a as ge}from"./chunk-73HYPGOI.js";import{createCipheriv as fe,createDecipheriv as ye,randomBytes as H,scrypt as Ke}from"crypto";import{promisify as $e}from"util";var he=$e(Ke),U="aes-256-gcm",me=12,q=16,Me=16,B=32;function O(){return H(B).toString("base64")}async function K(e,t){let n=H(Me),r=await he(t,n,B),o=H(me),i=fe(U,r,o,{authTagLength:q}),s=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[n.toString("base64"),o.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function D(e,t){let[n,r,o,i]=e.split(":");if(!n||!r||!o||!i)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(n,"base64"),a=Buffer.from(r,"base64"),d=Buffer.from(o,"base64"),g=Buffer.from(i,"base64"),f=await he(t,s,B),c=ye(U,f,a,{authTagLength:q});return c.setAuthTag(d),Buffer.concat([c.update(g),c.final()]).toString("utf8")}function X(e,t){let n=Buffer.from(t,"base64"),r=H(me),o=fe(U,n,r,{authTagLength:q}),i=Buffer.concat([o.update(e,"utf8"),o.final()]),s=o.getAuthTag();return[r.toString("base64"),s.toString("base64"),i.toString("base64")].join(":")}function ee(e,t){let[n,r,o]=e.split(":");if(!n||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(t,"base64"),s=Buffer.from(n,"base64"),a=Buffer.from(r,"base64"),d=Buffer.from(o,"base64"),g=ye(U,i,s,{authTagLength:q});return g.setAuthTag(a),Buffer.concat([g.update(d),g.final()]).toString("utf8")}function F(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=X(o,t);return n}function $(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=ee(o,t);return n}function S(e,t,n){let r=$(e,t);return F(r,n)}function z(e,t){let n=[];e||n.push("database"),t||n.push("kek");let r={};return new Proxy(r,{get(o,i){let s=n.length>1;throw new Error(`corsair.keys.${String(i)}: Cannot access keys because ${n.join(" and ")} ${s?"are":"is"} not configured. Provide both 'database' and 'kek' in createCorsair() to enable key management.
1
+ import{a as pe,b as Q}from"./chunk-2PB34FTK.js";import{a as ge}from"./chunk-B6CM5Q2M.js";import{createCipheriv as fe,createDecipheriv as ye,randomBytes as H,scrypt as Ke}from"crypto";import{promisify as $e}from"util";var he=$e(Ke),U="aes-256-gcm",me=12,z=16,Me=16,B=32;function O(){return H(B).toString("base64")}async function K(e,t){let n=H(Me),r=await he(t,n,B),o=H(me),i=fe(U,r,o,{authTagLength:z}),s=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[n.toString("base64"),o.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function D(e,t){let[n,r,o,i]=e.split(":");if(!n||!r||!o||!i)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(n,"base64"),a=Buffer.from(r,"base64"),d=Buffer.from(o,"base64"),g=Buffer.from(i,"base64"),f=await he(t,s,B),c=ye(U,f,a,{authTagLength:z});return c.setAuthTag(d),Buffer.concat([c.update(g),c.final()]).toString("utf8")}function X(e,t){let n=Buffer.from(t,"base64"),r=H(me),o=fe(U,n,r,{authTagLength:z}),i=Buffer.concat([o.update(e,"utf8"),o.final()]),s=o.getAuthTag();return[r.toString("base64"),s.toString("base64"),i.toString("base64")].join(":")}function ee(e,t){let[n,r,o]=e.split(":");if(!n||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(t,"base64"),s=Buffer.from(n,"base64"),a=Buffer.from(r,"base64"),d=Buffer.from(o,"base64"),g=ye(U,i,s,{authTagLength:z});return g.setAuthTag(a),Buffer.concat([g.update(d),g.final()]).toString("utf8")}function F(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=X(o,t);return n}function $(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=ee(o,t);return n}function S(e,t,n){let r=$(e,t);return F(r,n)}function q(e,t){let n=[];e||n.push("database"),t||n.push("kek");let r={};return new Proxy(r,{get(o,i){let s=n.length>1;throw new Error(`corsair.keys.${String(i)}: Cannot access keys because ${n.join(" and ")} ${s?"are":"is"} not configured. Provide both 'database' and 'kek' in createCorsair() to enable key management.
2
2
 
3
3
  To generate a KEK, run: openssl rand -base64 ${B}`)}})}var Z={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"]}};function ke(e,t,n){let r={};for(let o of n)r[`get_${o}`]=async()=>(await e())[o]??null,r[`set_${o}`]=async i=>{let s=[null,void 0,""].includes(i)?null:i;await t({[o]:s})};return r}var ne=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};function G(e){let{authType:t,integrationName:n,kek:r,database:o,extraIntegrationFields:i=[]}=e,s=[...Z[t].integration,...i],a=null,d={kek:r,integrationName:n,getIntegration:async()=>{if(a)return a;let u=await o.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!u)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);return a={id:u.id,config:ne(u.config),dek:u.dek??null},a},updateIntegration:async u=>{let p=await d.getIntegration();await o.db.updateTable("corsair_integrations").set({...u.config!==void 0?{config:u.config}:{},...u.dek!==void 0?{dek:u.dek}:{},updated_at:new Date}).where("id","=",p.id).execute(),a=null}},g=null,f=async()=>{if(g)return g;let u=await d.getIntegration();if(!u.dek)throw new Error(`No DEK found for integration "${n}". Initialize the integration first.`);return g=await D(u.dek,r),g},c=async()=>{let u=await d.getIntegration(),p=await f(),m=u.config;return!m||Object.keys(m).length===0?{}:$(m,p)};return{get_dek:f,issue_new_dek:async()=>{let u=await d.getIntegration(),p=O(),m={};if(u.dek){let P=await D(u.dek,r),b=u.config;b&&Object.keys(b).length>0&&(m=S(b,P,p))}let w=await K(p,r);return await d.updateIntegration({config:m,dek:w}),g=p,p},...ke(c,async u=>{let p=await f(),m;try{m=await c()}catch(b){console.error(`[corsair] Failed to decrypt config for integration "${n}", starting fresh:`,b),m={}}let w={...m};for(let[b,l]of Object.entries(u))l===null?delete w[b]:w[b]=l;let P=F(w,p);await d.updateIntegration({config:P})},s)}}function V(e){let{authType:t,integrationName:n,tenantId:r,kek:o,database:i,extraAccountFields:s=[]}=e,a=[...Z[t].account,...s],d=null,g=null,f=async()=>{if(g)return g;let l=await i.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!l)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);return g={id:l.id,config:ne(l.config),dek:l.dek??null},g},c={kek:o,integrationName:n,tenantId:r,getIntegration:f,getAccount:async()=>{if(d)return d;let l=await f(),k=await i.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",r).where("integration_id","=",l.id).executeTakeFirst();if(!k)throw new Error(`Account not found for tenant "${r}" and integration "${n}". Make sure to create the account first.`);return d={id:k.id,config:ne(k.config),dek:k.dek??null},d},updateAccount:async l=>{let k=await c.getAccount();await i.db.updateTable("corsair_accounts").set({...l.config!==void 0?{config:l.config}:{},...l.dek!==void 0?{dek:l.dek}:{},updated_at:new Date}).where("id","=",k.id).execute(),d=null}},y=null,h=null,u=async()=>{if(y)return y;let l=await c.getAccount();if(!l.dek)throw new Error(`No DEK found for account (tenant: "${r}", integration: "${n}"). Initialize the account first.`);return y=await D(l.dek,o),y},p=async()=>{if(h)return h;let l=await c.getIntegration();if(!l.dek)throw new Error(`No DEK found for integration "${n}". Initialize the integration first.`);return h=await D(l.dek,o),h},m=async()=>{let l=await c.getAccount(),k=await u(),C=l.config;return!C||Object.keys(C).length===0?{}:$(C,k)},w=async()=>{let l=await c.getIntegration(),k=await p(),C=l.config;return!C||Object.keys(C).length===0?{}:$(C,k)},b={get_dek:u,issue_new_dek:async()=>{let l=await c.getAccount(),k=O(),C={};if(l.dek){let A=await D(l.dek,o),x=l.config;x&&Object.keys(x).length>0&&(C=S(x,A,k))}let I=await K(k,o);return await c.updateAccount({config:C,dek:I}),y=k,k},...ke(m,async l=>{let k=await u(),C;try{C=await m()}catch(x){console.error(`[corsair] Failed to decrypt config for account (tenant: "${r}", integration: "${n}"), starting fresh:`,x),C={}}let I={...C};for(let[x,T]of Object.entries(l))T===null?delete I[x]:I[x]=T;let A=F(I,k);await c.updateAccount({config:A})},a)};return t==="oauth_2"&&(b.get_integration_credentials=async()=>{let l=await w();return{client_id:l.client_id||null,client_secret:l.client_secret||null,redirect_url:l.redirect_url??null}}),b}async function be(e,t,n){let r=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!r)throw new Error(`Integration "${t}" not found.`);let o=O(),i=await K(o,n);return await e.db.updateTable("corsair_integrations").set({dek:i,updated_at:new Date}).where("id","=",r.id).execute(),o}async function we(e,t,n,r){let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!o)throw new Error(`Integration "${t}" not found.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${n}" and integration "${t}".`);let s=O(),a=await K(s,r);return await e.db.updateTable("corsair_accounts").set({dek:a,updated_at:new Date}).where("id","=",i.id).execute(),s}var Fe=async(e,t)=>(console.error(`[corsair:${t.pluginId}:${t.operation}]`,{error:e.message,input:t.input}),{maxRetries:0});async function Ce(e,t,n,r,o){let i={pluginId:t,operation:n,input:r,originalError:e},s=Object.keys(o).find(g=>o[g]?.match(e,i));return await(o[s||"DEFAULT"]?.handler||Fe)(e,i)}import{randomBytes as Ne}from"crypto";import{v4 as Be}from"uuid";var Se={open:{read:"allow",write:"allow",destructive:"allow"},cautious:{read:"allow",write:"allow",destructive:"require_approval"},strict:{read:"allow",write:"require_approval",destructive:"deny"},readonly:{read:"allow",write:"deny",destructive:"deny"}};function Ze(e,t,n){return n!==void 0?n:Se[t][e]}function Te(e){let t=/(\d+)(d|h|m|s)/g,n=0,r;for(;(r=t.exec(e))!==null;){let o=parseInt(r[1],10);switch(r[2]){case"d":n+=o*864e5;break;case"h":n+=o*36e5;break;case"m":n+=o*6e4;break;case"s":n+=o*1e3;break}}return n>0?n:600*1e3}function Pe(e){return{async find_by_permission_id(t){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("id","=",t).executeTakeFirst()},async find_by_token(t){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("token","=",t).executeTakeFirst()},async set_executing(t){e&&await e.db.updateTable("corsair_permissions").set({status:"executing",updated_at:new Date}).where("id","=",t).execute()},async set_completed(t){e&&await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",t).execute()}}}async function xe(e){let t=Ze(e.riskLevel,e.mode,e.override);if(t==="allow")return{result:"allow"};let n=e.meta?.irreversible?" (irreversible)":"",r=e.meta?.description?`${e.meta.description}${n}`:`${e.pluginId}.${e.endpointPath}${n}`;if(t==="deny"||!e.db)return console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 denied by permission mode '${e.mode}'.`,`
4
4
  Action: ${r}`,`
@@ -10,17 +10,17 @@ To generate a KEK, run: openssl rand -base64 ${B}`)}})}var Z={oauth_2:{integrati
10
10
  Permission ID: ${d}`,`
11
11
  Permission token: ${g}`,`
12
12
  Expires at: ${c}`,`
13
- Use the token to approve or deny this request.`),{result:"blocked"}}function je(e){return typeof e=="function"}function te({endpoints:e,hooks:t,ctx:n,tree:r,pluginId:o,errorHandlers:i,currentPath:s=[],keyBuilder:a,permissionsConfig:d,endpointMeta:g,database:f,approvalConfig:c,tenantId:y}){for(let[h,u]of Object.entries(e)){let p=t?.[h];if(je(u)){let m=p,w=[...s,h].join("."),P=async(b={})=>{let l;if(d){let T=g?.[w],{result:v,onComplete:E}=await xe({pluginId:o,endpointPath:w,args:b,mode:d.mode,override:d.overrides?.[w],riskLevel:T?.riskLevel??"write",meta:T,db:f,timeoutMs:c?Te(c.timeout):void 0,tenantId:y});if(v==="blocked")return null;l=E}let k=async(T,v,E)=>{try{return await u(v,E)}catch(N){if(N instanceof Error){let M=await Ce(N,o,w,typeof E=="object"&&E!==null?E:{args:E},i);if(T<(M.maxRetries||0)){let L=T+1;console.log(`Retrying (${L} / ${M.maxRetries})...`);let _;if(M.headersRetryAfterMs)_=M.headersRetryAfterMs;else switch(M.retryStrategy){case"exponential_backoff":_=Math.pow(2,L-1)*1e3;break;case"exponential_backoff_jitter":let Y=Math.pow(2,L-1)*1e3,Oe=(Math.random()-.5)*1e3;_=Math.max(0,Y+Oe);break;case"linear_1s":_=1e3;break;case"linear_2s":_=2e3;break;case"linear_3s":_=3e3;break;case"linear_4s":_=4e3;break;default:_=1e3;break}await new Promise(Y=>setTimeout(Y,_)),await k(L,v,E),console.log(`[corsair:${o}:${w}] Retry strategy:`,M)}}throw N}},C=a?await a(n,"endpoint"):void 0;if(!m?.before&&!m?.after){let T=await k(0,{...n,key:C},b);return await l?.(),T}let I={...n,key:C},A=m.before?await m.before(I,b):{ctx:I,args:b,continue:!0,passToAfter:void 0};if(A.continue===!1)return;let x=await k(0,A.ctx,A.args);return await m.after?.(A.ctx,x,A.passToAfter),await l?.(),x};r[h]=P}else if(u&&typeof u=="object"){let m={};te({endpoints:u,hooks:p,ctx:n,tree:m,pluginId:o,errorHandlers:i,currentPath:[...s,h],keyBuilder:a,permissionsConfig:d,endpointMeta:g,database:f,approvalConfig:c,tenantId:y}),r[h]=m}}}var Ae=["airtable","amplitude","asana","box","cal","calendly","discord","dropbox","exa","figma","fireflies","github","gmail","googlecalendar","googledrive","googlesheets","hackernews","hubspot","intercom","jira","linear","monday","notion","oura","pagerduty","posthog","resend","sentry","slack","spotify","stripe","tavily","teams","telegram","todoist","trello","twitter","twitterapiio","typeform","zoom"];var Ee=" ";function R(e){let t=e._def,n=t.typeName;switch(n){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodNull":return"null";case"ZodUnknown":case"ZodAny":return"any";case"ZodLiteral":return String(t.value);case"ZodEnum":return t.values.map(r=>String(r)).join(" | ");case"ZodOptional":return R(t.innerType);case"ZodNullable":return`${R(t.innerType)} | null`;case"ZodArray":{let r=t.type,i=r._def.typeName==="ZodUnion",s=R(r);return`${i?`(${s})`:s}[]`}case"ZodRecord":return"{}";case"ZodObject":{let r=t.shape(),o=Object.entries(r);return o.length===0?"{}":`{ ${o.map(([s,a])=>{let d=a._def.typeName;return`${d==="ZodOptional"||d==="ZodNullable"?s+"?":s}: ${R(a)}`}).join(", ")} }`}case"ZodUnion":return t.options.map(R).join(" | ");case"ZodIntersection":return`${R(t.left)} & ${R(t.right)}`;case"ZodEffects":return R(t.schema);default:return(n??"unknown").replace("Zod","").toLowerCase()}}function j(e,t){let n=e._def,r=n.typeName;if(r==="ZodOptional"||r==="ZodEffects")return j(r==="ZodOptional"?n.innerType:n.schema,t);if(r!=="ZodObject")return R(e);let o=n.shape(),i=Object.entries(o);if(i.length===0)return"{}";let s=Ee.repeat(t+1),a=Ee.repeat(t),d=[];for(let[g,f]of i){let c=f._def,y=c.typeName,u=y==="ZodOptional"||y==="ZodNullable"?`${g}?`:g,p=y==="ZodOptional"||y==="ZodNullable"?c.innerType:f,m=p?._def,w=m?.typeName,P=m?.description,b=P?` // ${P}`:"";w==="ZodObject"?d.push(`${s}${u}: ${j(p,t+1)}${b}`):d.push(`${s}${u}: ${R(f)}${b}`)}return`{
13
+ Use the token to approve or deny this request.`),{result:"blocked"}}function je(e){return typeof e=="function"}function te({endpoints:e,hooks:t,ctx:n,tree:r,pluginId:o,errorHandlers:i,currentPath:s=[],keyBuilder:a,permissionsConfig:d,endpointMeta:g,database:f,approvalConfig:c,tenantId:y}){for(let[h,u]of Object.entries(e)){let p=t?.[h];if(je(u)){let m=p,w=[...s,h].join("."),P=async(b={})=>{let l;if(d){let T=g?.[w],{result:v,onComplete:E}=await xe({pluginId:o,endpointPath:w,args:b,mode:d.mode,override:d.overrides?.[w],riskLevel:T?.riskLevel??"write",meta:T,db:f,timeoutMs:c?Te(c.timeout):void 0,tenantId:y});if(v==="blocked")return null;l=E}let k=async(T,v,E)=>{try{return await u(v,E)}catch(N){if(N instanceof Error){let M=await Ce(N,o,w,typeof E=="object"&&E!==null?E:{args:E},i);if(T<(M.maxRetries||0)){let L=T+1;console.log(`Retrying (${L} / ${M.maxRetries})...`);let _;if(M.headersRetryAfterMs)_=M.headersRetryAfterMs;else switch(M.retryStrategy){case"exponential_backoff":_=Math.pow(2,L-1)*1e3;break;case"exponential_backoff_jitter":let Y=Math.pow(2,L-1)*1e3,Oe=(Math.random()-.5)*1e3;_=Math.max(0,Y+Oe);break;case"linear_1s":_=1e3;break;case"linear_2s":_=2e3;break;case"linear_3s":_=3e3;break;case"linear_4s":_=4e3;break;default:_=1e3;break}await new Promise(Y=>setTimeout(Y,_)),await k(L,v,E),console.log(`[corsair:${o}:${w}] Retry strategy:`,M)}}throw N}},C=a?await a(n,"endpoint"):void 0;if(!m?.before&&!m?.after){let T=await k(0,{...n,key:C},b);return await l?.(),T}let I={...n,key:C},A=m.before?await m.before(I,b):{ctx:I,args:b,continue:!0,passToAfter:void 0};if(A.continue===!1)return;let x=await k(0,A.ctx,A.args);return await m.after?.(A.ctx,x,A.passToAfter),await l?.(),x};r[h]=P}else if(u&&typeof u=="object"){let m={};te({endpoints:u,hooks:p,ctx:n,tree:m,pluginId:o,errorHandlers:i,currentPath:[...s,h],keyBuilder:a,permissionsConfig:d,endpointMeta:g,database:f,approvalConfig:c,tenantId:y}),r[h]=m}}}var Ae=["airtable","amplitude","asana","box","cal","calendly","cursor","discord","dropbox","exa","figma","fireflies","github","gmail","googlecalendar","googledrive","googlesheets","hackernews","hubspot","intercom","jira","linear","monday","notion","onedrive","oura","outlook","pagerduty","posthog","razorpay","resend","sentry","sharepoint","slack","spotify","strava","stripe","tavily","teams","telegram","todoist","trello","twitter","twitterapiio","youtube","typeform","zoom"];var Ee=" ";function R(e){let t=e._def,n=t.typeName;switch(n){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodNull":return"null";case"ZodUnknown":case"ZodAny":return"any";case"ZodLiteral":return String(t.value);case"ZodEnum":return t.values.map(r=>String(r)).join(" | ");case"ZodOptional":return R(t.innerType);case"ZodNullable":return`${R(t.innerType)} | null`;case"ZodArray":{let r=t.type,i=r._def.typeName==="ZodUnion",s=R(r);return`${i?`(${s})`:s}[]`}case"ZodRecord":return"{}";case"ZodObject":{let r=t.shape(),o=Object.entries(r);return o.length===0?"{}":`{ ${o.map(([s,a])=>{let d=a._def.typeName;return`${d==="ZodOptional"||d==="ZodNullable"?s+"?":s}: ${R(a)}`}).join(", ")} }`}case"ZodUnion":return t.options.map(R).join(" | ");case"ZodIntersection":return`${R(t.left)} & ${R(t.right)}`;case"ZodEffects":return R(t.schema);default:return(n??"unknown").replace("Zod","").toLowerCase()}}function j(e,t){let n=e._def,r=n.typeName;if(r==="ZodOptional"||r==="ZodEffects")return j(r==="ZodOptional"?n.innerType:n.schema,t);if(r!=="ZodObject")return R(e);let o=n.shape(),i=Object.entries(o);if(i.length===0)return"{}";let s=Ee.repeat(t+1),a=Ee.repeat(t),d=[];for(let[g,f]of i){let c=f._def,y=c.typeName,u=y==="ZodOptional"||y==="ZodNullable"?`${g}?`:g,p=y==="ZodOptional"||y==="ZodNullable"?c.innerType:f,m=p?._def,w=m?.typeName,P=m?.description,b=P?` // ${P}`:"";w==="ZodObject"?d.push(`${s}${u}: ${j(p,t+1)}${b}`):d.push(`${s}${u}: ${R(f)}${b}`)}return`{
14
14
  ${d.join(`
15
15
  `)}
16
- ${a}}`}var Re=["equals","contains","startsWith","endsWith","in"],We=["equals","gt","gte","lt","lte","in"],Le=["equals"],He=["equals","before","after","between"];function ie(e){let t=e._def;switch(t.typeName){case"ZodOptional":case"ZodNullable":case"ZodDefault":return ie(t.innerType);case"ZodEffects":return ie(t.schema);case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function se(e){let t=e._def,n=t.typeName;if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")return se(t.innerType);if(n==="ZodEffects")return se(t.schema);if(n!=="ZodObject")return{};let r=t.shape(),o={};for(let[i,s]of Object.entries(r)){let a=ie(s);a==="string"?o[i]={type:"string",operators:Re}:a==="number"?o[i]={type:"number",operators:We}:a==="boolean"?o[i]={type:"boolean",operators:Le}:a==="date"&&(o[i]={type:"date",operators:He})}return o}function Ue(e,t){for(let[n,r]of Object.entries(e))if(n.toLowerCase()===t)return[n,r]}function ae(e,t,n){for(let[r,o]of Object.entries(e)){let i=[...t,r];typeof o=="function"?n.push(i.join(".")):o!==null&&typeof o=="object"&&ae(o,i,n)}}function ce(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function de(e,t,n){for(let[r,o]of Object.entries(e)){let i=[...t,r];ce(o)?n.push(i.join(".")):o!==null&&typeof o=="object"&&de(o,i,n)}}function Ie(e,t){if(t.length===0)return null;let[n,...r]=t,o=Object.entries(e).find(([a])=>a.toLowerCase()===n);if(!o)return null;let[i,s]=o;if(r.length===0)return ce(s)?[i]:null;if(s!==null&&typeof s=="object"&&!ce(s)){let a=Ie(s,r);if(a!==null)return[i,...a]}return null}function qe(e,t,n){let r=[];r.push(`${e}({`),r.push(" webhookHooks: {");for(let s=0;s<t.length;s++){let a=" ".repeat(s+2);r.push(`${a}${t[s]}: {`)}let o=" ".repeat(t.length+2),i=o+" ";r.push(`${o}before(ctx, args) {`),r.push(`${i}return { ctx, args };`),r.push(`${o}},`),r.push(`${o}after(ctx, response) {`),r.push(n!==null?`${i}// response.data: ${n}`:`${i}// response.data: unknown (register webhookSchemas to see the type)`),r.push(`${o}},`);for(let s=t.length-1;s>=0;s--){let a=" ".repeat(s+2);r.push(`${a}},`)}return r.push(" },"),r.push("})"),r.join(`
17
- `)}var ze=new Set(Ae);function W(e,t){let n=t?.type??"api",r=t?.plugin;if(r!==void 0){let i=e.find(a=>a.id===r);if(!i)return ze.has(r)?`This plugin (${r}) is not configured. Please add it to the Corsair instance to see its associated methods.`:W(e);if(n==="webhooks"){if(!i.webhooks)return[];let a=[];return de(i.webhooks,[],a),a.map(d=>`${i.id}.webhooks.${d}`)}if(n==="db"){let a=i.schema?.entities;return a?Object.keys(a).map(d=>`${i.id}.db.${d}.search`):[]}if(!i.endpoints)return[];let s=[];return ae(i.endpoints,[],s),s.map(a=>`${i.id}.api.${a}`)}let o={};if(n==="webhooks")for(let i of e){if(!i.webhooks)continue;let s=[];de(i.webhooks,[],s),o[i.id]=s.map(a=>`${i.id}.webhooks.${a}`)}else if(n==="db")for(let i of e){let s=i.schema?.entities;s&&(o[i.id]=Object.keys(s).map(a=>`${i.id}.db.${a}.search`))}else for(let i of e){if(!i.endpoints)continue;let s=[];ae(i.endpoints,[],s),o[i.id]=s.map(a=>`${i.id}.api.${a}`)}return o}function re(e,t){if(e){for(let[n,r]of Object.entries(e))if(n.toLowerCase()===t)return r}}function oe(e,t){return typeof e=="string"?e:Array.isArray(e)?`${t}:
16
+ ${a}}`}var Re=["equals","contains","startsWith","endsWith","in"],We=["equals","gt","gte","lt","lte","in"],Le=["equals"],He=["equals","before","after","between"];function ie(e){let t=e._def;switch(t.typeName){case"ZodOptional":case"ZodNullable":case"ZodDefault":return ie(t.innerType);case"ZodEffects":return ie(t.schema);case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function se(e){let t=e._def,n=t.typeName;if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")return se(t.innerType);if(n==="ZodEffects")return se(t.schema);if(n!=="ZodObject")return{};let r=t.shape(),o={};for(let[i,s]of Object.entries(r)){let a=ie(s);a==="string"?o[i]={type:"string",operators:Re}:a==="number"?o[i]={type:"number",operators:We}:a==="boolean"?o[i]={type:"boolean",operators:Le}:a==="date"&&(o[i]={type:"date",operators:He})}return o}function Ue(e,t){for(let[n,r]of Object.entries(e))if(n.toLowerCase()===t)return[n,r]}function ae(e,t,n){for(let[r,o]of Object.entries(e)){let i=[...t,r];typeof o=="function"?n.push(i.join(".")):o!==null&&typeof o=="object"&&ae(o,i,n)}}function ce(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function de(e,t,n){for(let[r,o]of Object.entries(e)){let i=[...t,r];ce(o)?n.push(i.join(".")):o!==null&&typeof o=="object"&&de(o,i,n)}}function Ie(e,t){if(t.length===0)return null;let[n,...r]=t,o=Object.entries(e).find(([a])=>a.toLowerCase()===n);if(!o)return null;let[i,s]=o;if(r.length===0)return ce(s)?[i]:null;if(s!==null&&typeof s=="object"&&!ce(s)){let a=Ie(s,r);if(a!==null)return[i,...a]}return null}function ze(e,t,n){let r=[];r.push(`${e}({`),r.push(" webhookHooks: {");for(let s=0;s<t.length;s++){let a=" ".repeat(s+2);r.push(`${a}${t[s]}: {`)}let o=" ".repeat(t.length+2),i=o+" ";r.push(`${o}before(ctx, args) {`),r.push(`${i}return { ctx, args };`),r.push(`${o}},`),r.push(`${o}after(ctx, response) {`),r.push(n!==null?`${i}// response.data: ${n}`:`${i}// response.data: unknown (register webhookSchemas to see the type)`),r.push(`${o}},`);for(let s=t.length-1;s>=0;s--){let a=" ".repeat(s+2);r.push(`${a}},`)}return r.push(" },"),r.push("})"),r.join(`
17
+ `)}var qe=new Set(Ae);function W(e,t){let n=t?.type??"api",r=t?.plugin;if(r!==void 0){let i=e.find(a=>a.id===r);if(!i)return qe.has(r)?`This plugin (${r}) is not configured. Please add it to the Corsair instance to see its associated methods.`:W(e);if(n==="webhooks"){if(!i.webhooks)return[];let a=[];return de(i.webhooks,[],a),a.map(d=>`${i.id}.webhooks.${d}`)}if(n==="db"){let a=i.schema?.entities;return a?Object.keys(a).map(d=>`${i.id}.db.${d}.search`):[]}if(!i.endpoints)return[];let s=[];return ae(i.endpoints,[],s),s.map(a=>`${i.id}.api.${a}`)}let o={};if(n==="webhooks")for(let i of e){if(!i.webhooks)continue;let s=[];de(i.webhooks,[],s),o[i.id]=s.map(a=>`${i.id}.webhooks.${a}`)}else if(n==="db")for(let i of e){let s=i.schema?.entities;s&&(o[i.id]=Object.keys(s).map(a=>`${i.id}.db.${a}.search`))}else for(let i of e){if(!i.endpoints)continue;let s=[];ae(i.endpoints,[],s),o[i.id]=s.map(a=>`${i.id}.api.${a}`)}return o}function re(e,t){if(e){for(let[n,r]of Object.entries(e))if(n.toLowerCase()===t)return r}}function oe(e,t){return typeof e=="string"?e:Array.isArray(e)?`${t}:
18
18
  ${e.join(", ")}`:`${t}:
19
19
  `+Object.entries(e).map(([n,r])=>` ${n}: ${r.join(", ")}`).join(`
20
20
  `)}function Ge(e,t){let n=t.toLowerCase(),r=n.indexOf(".");if(r!==-1){let o=n.slice(0,r),i=n.slice(r+1),s=e.find(a=>a.id===o);if(s){if(i.startsWith("db.")){let f=i.slice(3),c=f.lastIndexOf(".");if(c!==-1){let y=f.slice(0,c),h=f.slice(c+1),u=s.schema?.entities;if(h==="search"&&u){let p=Ue(u,y);if(p){let[m,w]=p,P=se(w),b=[`Search ${o} ${m} stored in the local database.`,"Pass limit and offset as numbers for pagination.","","filters {",` entity_id: string [${Re.join(", ")}]`];for(let[l,k]of Object.entries(P))b.push(` ${l}?: ${k.type} [${k.operators.join(", ")}]`);return b.push("}"),b.join(`
21
21
  `)}}}return oe(W(e,{type:"db"}),"Path not found. Available db operations")}if(i.startsWith("webhooks.")){let f=i.slice(9);if(s.webhooks){let c=Ie(s.webhooks,f.split("."));if(c!==null){let y=c.join("."),h=re(s.webhookSchemas,y.toLowerCase()),u=h?.response?R(h.response):null,p=[];return h?.description&&p.push(h.description),h?.payload&&p.push(`payload ${j(h.payload,0)}`),u&&p.push(`response: ${u}`),p.push(`usage:
22
- ${qe(o,c,u)}`),p.join(`
22
+ ${ze(o,c,u)}`),p.join(`
23
23
 
24
24
  `)}}return oe(W(e,{type:"webhooks"}),"Path not found. Available webhooks")}let a=i;a.startsWith("api.")&&(a=a.slice(4));let d=re(s.endpointMeta,a),g=re(s.endpointSchemas,a);if(d||g){let f=[],c=[d?.riskLevel?`[${d.riskLevel}]`:"",d?.irreversible?"[irreversible]":""].filter(Boolean).join(" "),y=[d?.description,c].filter(Boolean).join(" ");return y&&f.push(y),g?.input&&f.push(`input ${j(g.input,0)}`),g?.output&&f.push(`output ${j(g.output,0)}`),f.join(`
25
25
 
26
- `)}}}return oe(W(e),"Path not found. Available operations")}function J(e){return{list_operations(t){return W(e,t)},get_schema(t){return Ge(e,t)}}}function Ve(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function ue({webhooks:e,hooks:t,ctx:n,webhooksTree:r,keyBuilder:o}){for(let[i,s]of Object.entries(e)){let a=t?.[i];if(Ve(s)){let d=a,g=async f=>{let c=(h,u)=>s.handler(h,u),y=o?await o(n,"webhook"):void 0;return!d?.before&&!d?.after?c({...n,key:y},f):(async()=>{let h={...n,key:y},u=d.before?await d.before(h,f):{ctx:h,args:f,continue:!0,passToAfter:void 0};if(u.continue===!1)return;let p=await c(u.ctx,u.args);return p?.success===!0&&await d.after?.(u.ctx,p,u.passToAfter),p})()};r[i]={match:s.match,handler:g}}else if(s&&typeof s=="object"){let d={};ue({webhooks:s,hooks:a,ctx:n,webhooksTree:d,keyBuilder:o}),r[i]=d}}}function Je(e,t,n){let r=null;return async()=>{if(r)return r;if(!e)throw new Error("Database not configured");let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!o)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${n}" and integration "${t}". Make sure to create the account first.`);return r=i.id,r}}function Ye(e,t,n,r,o){return e?Q(e.db,t,n,r,o):{findByEntityId:async()=>null,findById:async()=>null,findManyByEntityIds:async()=>[],list:async()=>[],search:async()=>[],upsertByEntityId:async()=>{throw new Error("Database not configured")},deleteById:async()=>!1,deleteByEntityId:async()=>!1,count:async()=>0}}function le(e,t){let{database:n,tenantId:r,kek:o,rootErrorHandlers:i,approvalConfig:s}=t,a={},d={};for(let c of e)a[c.id]={},d[c.id]={};for(let c of e){let y=c.schema,h=r??"default",u=Je(n,c.id,h);if(y?.entities){let T={};for(let[v,E]of Object.entries(y.entities)){let N=n?Q(n.db,u,v,y.version,E):Ye(void 0,u,v,y.version,E);T[v]=N}d[c.id].db=T,a[c.id].db=T}let p=c.options,m=c.authConfig,w;if(n&&o&&p?.authType){let T=m?.[p.authType]?.account??[];w=V({authType:p.authType,integrationName:c.id,tenantId:h,kek:o,database:n,extraAccountFields:T}),a[c.id].keys=w}let P={database:n,db:d[c.id]?.db??{},$getAccountId:u,...c.options?{options:c.options}:{},...w?{keys:w,authType:p?.authType}:{},...r?{tenantId:r}:{}},b=c.endpoints??{},l=c.hooks,k={...i,...c.errorHandlers},C={},I=c.options?.permissions;te({endpoints:b,hooks:l,ctx:P,tree:C,pluginId:c.id,errorHandlers:k,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:I,endpointMeta:c.endpointMeta,database:n,approvalConfig:s,tenantId:r}),Object.keys(C).length>0&&(a[c.id].api=C),P.endpoints=C;let A=c.webhooks??{},x=c.webhookHooks;if(Object.keys(A).length>0){let T={};ue({webhooks:A,hooks:x,ctx:P,webhooksTree:T,keyBuilder:c.keyBuilder}),a[c.id].webhooks=T,c.pluginWebhookMatcher&&(a[c.id].pluginWebhookMatcher=c.pluginWebhookMatcher)}}let g=a,f=J(e);return{...g,...f}}function _e(e,t,n){let r={};for(let o of e){let i=o.options,s=o.authConfig;if(i?.authType){let a=s?.[i.authType]?.integration??[],d=G({authType:i.authType,integrationName:o.id,kek:n,database:t,extraIntegrationFields:a});r[o.id]=d}}return r}async function ve(e,t,n,r,o="pending"){if(!e)return null;try{let i=pe(),s=new Date;return await e.db.insertInto("corsair_events").values({id:i,created_at:s,updated_at:s,account_id:t,event_type:n,payload:r,status:o}).execute(),i}catch(i){return console.warn("Failed to log event:",i),null}}async function Qe(e,t,n,r="pending"){try{let o=await e.$getAccountId();return ve(e.database,o,t,n,r)}catch(o){return console.warn("Failed to log event:",o),null}}var De=Symbol.for("corsair:internal");function Zn(e){let t=e.database?ge(e.database):void 0,n=t&&e.kek?_e(e.plugins,t,e.kek):z(!!t,!!e.kek),r={plugins:e.plugins,database:t,kek:e.kek,multiTenancy:!!e.multiTenancy,approval:e.approval},o=Pe(t);if(e.multiTenancy)return Object.assign({withTenant:s=>{if(!s)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");return le(e.plugins,{database:t,tenantId:s,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval})},keys:n,permissions:o,...J(e.plugins)},{[De]:r});let i=le(e.plugins,{database:t,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval});return Object.assign({},i,{keys:n,permissions:o,[De]:r})}export{O as a,K as b,D as c,X as d,ee as e,F as f,$ as g,S as h,Z as i,G as j,V as k,be as l,we as m,Ae as n,ve as o,Qe as p,De as q,Zn as r};
26
+ `)}}}return oe(W(e),"Path not found. Available operations")}function J(e){return{list_operations(t){return W(e,t)},get_schema(t){return Ge(e,t)}}}function Ve(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function ue({webhooks:e,hooks:t,ctx:n,webhooksTree:r,keyBuilder:o}){for(let[i,s]of Object.entries(e)){let a=t?.[i];if(Ve(s)){let d=a,g=async f=>{let c=(h,u)=>s.handler(h,u),y=o?await o(n,"webhook"):void 0;return!d?.before&&!d?.after?c({...n,key:y},f):(async()=>{let h={...n,key:y},u=d.before?await d.before(h,f):{ctx:h,args:f,continue:!0,passToAfter:void 0};if(u.continue===!1)return;let p=await c(u.ctx,u.args);return p?.success===!0&&await d.after?.(u.ctx,p,u.passToAfter),p})()};r[i]={match:s.match,handler:g}}else if(s&&typeof s=="object"){let d={};ue({webhooks:s,hooks:a,ctx:n,webhooksTree:d,keyBuilder:o}),r[i]=d}}}function Je(e,t,n){let r=null;return async()=>{if(r)return r;if(!e)throw new Error("Database not configured");let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!o)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${n}" and integration "${t}". Make sure to create the account first.`);return r=i.id,r}}function Ye(e,t,n,r,o){return e?Q(e.db,t,n,r,o):{findByEntityId:async()=>null,findById:async()=>null,findManyByEntityIds:async()=>[],list:async()=>[],search:async()=>[],upsertByEntityId:async()=>{throw new Error("Database not configured")},deleteById:async()=>!1,deleteByEntityId:async()=>!1,count:async()=>0}}function le(e,t){let{database:n,tenantId:r,kek:o,rootErrorHandlers:i,approvalConfig:s}=t,a={},d={};for(let c of e)a[c.id]={},d[c.id]={};for(let c of e){let y=c.schema,h=r??"default",u=Je(n,c.id,h);if(y?.entities){let T={};for(let[v,E]of Object.entries(y.entities)){let N=n?Q(n.db,u,v,y.version,E):Ye(void 0,u,v,y.version,E);T[v]=N}d[c.id].db=T,a[c.id].db=T}let p=c.options,m=c.authConfig,w;if(n&&o&&p?.authType){let T=m?.[p.authType]?.account??[];w=V({authType:p.authType,integrationName:c.id,tenantId:h,kek:o,database:n,extraAccountFields:T}),a[c.id].keys=w}let P={database:n,db:d[c.id]?.db??{},$getAccountId:u,...c.options?{options:c.options}:{},...w?{keys:w,authType:p?.authType}:{},...r?{tenantId:r}:{}},b=c.endpoints??{},l=c.hooks,k={...i,...c.errorHandlers},C={},I=c.options?.permissions;te({endpoints:b,hooks:l,ctx:P,tree:C,pluginId:c.id,errorHandlers:k,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:I,endpointMeta:c.endpointMeta,database:n,approvalConfig:s,tenantId:r}),Object.keys(C).length>0&&(a[c.id].api=C),P.endpoints=C;let A=c.webhooks??{},x=c.webhookHooks;if(Object.keys(A).length>0){let T={};ue({webhooks:A,hooks:x,ctx:P,webhooksTree:T,keyBuilder:c.keyBuilder}),a[c.id].webhooks=T,c.pluginWebhookMatcher&&(a[c.id].pluginWebhookMatcher=c.pluginWebhookMatcher)}}let g=a,f=J(e);return{...g,...f}}function _e(e,t,n){let r={};for(let o of e){let i=o.options,s=o.authConfig;if(i?.authType){let a=s?.[i.authType]?.integration??[],d=G({authType:i.authType,integrationName:o.id,kek:n,database:t,extraIntegrationFields:a});r[o.id]=d}}return r}async function ve(e,t,n,r,o="pending"){if(!e)return null;try{let i=pe(),s=new Date;return await e.db.insertInto("corsair_events").values({id:i,created_at:s,updated_at:s,account_id:t,event_type:n,payload:r,status:o}).execute(),i}catch(i){return console.warn("Failed to log event:",i),null}}async function Qe(e,t,n,r="pending"){try{let o=await e.$getAccountId();return ve(e.database,o,t,n,r)}catch(o){return console.warn("Failed to log event:",o),null}}var De=Symbol.for("corsair:internal");function Zn(e){let t=e.database?ge(e.database):void 0,n=t&&e.kek?_e(e.plugins,t,e.kek):q(!!t,!!e.kek),r={plugins:e.plugins,database:t,kek:e.kek,multiTenancy:!!e.multiTenancy,approval:e.approval},o=Pe(t);if(e.multiTenancy)return Object.assign({withTenant:s=>{if(!s)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");return le(e.plugins,{database:t,tenantId:s,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval})},keys:n,permissions:o,...J(e.plugins)},{[De]:r});let i=le(e.plugins,{database:t,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval});return Object.assign({},i,{keys:n,permissions:o,[De]:r})}export{O as a,K as b,D as c,X as d,ee as e,F as f,$ as g,S as h,Z as i,G as j,V as k,be as l,we as m,Ae as n,ve as o,Qe as p,De as q,Zn as r};
package/dist/core.d.ts CHANGED
@@ -1,11 +1,41 @@
1
- export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair } from './index-DpPKj1ZX.js';
2
- import { A as AuthTypes, f as AccountKeyManagerFor, I as IntegrationKeyManagerFor } from './index-D_Ah5Tz6.js';
3
- export { g as AccountFieldNames, m as AllProviders, k as BASE_AUTH_FIELDS, h as BaseAuthFieldConfig, i as BaseKeyManager, e as BaseProviders, K as BeforeHookResult, o as BindEndpoints, a5 as BindWebhooks, a3 as Bivariant, p as BoundEndpointFn, q as BoundEndpointTree, a6 as BoundWebhook, B as BoundWebhookTree, l as CorsairClient, r as CorsairContext, s as CorsairEndpoint, u as CorsairErrorHandler, F as CorsairInspectMethods, a as CorsairIntegration, L as CorsairKeyBuilder, M as CorsairKeyBuilderBase, d as CorsairPermissionsNamespace, C as CorsairPlugin, Q as CorsairPluginContext, c as CorsairSingleTenantClient, b as CorsairTenantWrapper, a7 as CorsairWebhook, a8 as CorsairWebhookHandler, a9 as CorsairWebhookMatcher, S as EndpointHooks, T as EndpointMetaEntry, E as EndpointPathsOf, U as EndpointRiskLevel, G as EndpointSchemaResult, t as EndpointTree, H as EnforcePermissionOptions, J as EnforcePermissionResult, v as ErrorContext, w as ErrorHandler, x as ErrorHandlerAndMatchFunction, y as ErrorMatcher, j as IntegrationFieldNames, V as KeyBuilderContext, O as OAuth2IntegrationCredentials, N as OAuthConfig, X as PermissionMode, Y as PermissionPolicy, n as PickAuth, P as PluginAuthConfig, Z as PluginEndpointMeta, _ as PluginPermissionsConfig, R as RawWebhookRequest, $ as RequiredPluginEndpointMeta, a0 as RequiredPluginEndpointSchemas, a1 as RequiredPluginWebhookSchemas, z as RetryStrategies, D as RetryStrategy, a4 as UnionToIntersection, a2 as WebhookHooks, aa as WebhookPathsOf, ab as WebhookRequest, W as WebhookResponse, ac as WebhookTree } from './index-D_Ah5Tz6.js';
1
+ export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair } from './index-D3UKvoWx.js';
4
2
  import { CorsairDatabase } from './db.js';
5
- import 'zod';
6
- import './orm.js';
3
+ import { A as AuthTypes, f as AccountKeyManagerFor, I as IntegrationKeyManagerFor } from './index-KlQEcEwI.js';
4
+ export { g as AccountFieldNames, m as AllProviders, k as BASE_AUTH_FIELDS, h as BaseAuthFieldConfig, i as BaseKeyManager, e as BaseProviders, K as BeforeHookResult, o as BindEndpoints, a5 as BindWebhooks, a3 as Bivariant, p as BoundEndpointFn, q as BoundEndpointTree, a6 as BoundWebhook, B as BoundWebhookTree, l as CorsairClient, r as CorsairContext, s as CorsairEndpoint, u as CorsairErrorHandler, F as CorsairInspectMethods, a as CorsairIntegration, L as CorsairKeyBuilder, M as CorsairKeyBuilderBase, d as CorsairPermissionsNamespace, C as CorsairPlugin, N as CorsairPluginContext, c as CorsairSingleTenantClient, b as CorsairTenantWrapper, a7 as CorsairWebhook, a8 as CorsairWebhookHandler, a9 as CorsairWebhookMatcher, Q as EndpointHooks, S as EndpointMetaEntry, E as EndpointPathsOf, T as EndpointRiskLevel, G as EndpointSchemaResult, t as EndpointTree, H as EnforcePermissionOptions, J as EnforcePermissionResult, v as ErrorContext, w as ErrorHandler, x as ErrorHandlerAndMatchFunction, y as ErrorMatcher, j as IntegrationFieldNames, U as KeyBuilderContext, O as OAuth2IntegrationCredentials, V as OAuthConfig, X as PermissionMode, Y as PermissionPolicy, n as PickAuth, P as PluginAuthConfig, Z as PluginEndpointMeta, _ as PluginPermissionsConfig, R as RawWebhookRequest, $ as RequiredPluginEndpointMeta, a0 as RequiredPluginEndpointSchemas, a1 as RequiredPluginWebhookSchemas, z as RetryStrategies, D as RetryStrategy, a4 as UnionToIntersection, a2 as WebhookHooks, aa as WebhookPathsOf, ab as WebhookRequest, W as WebhookResponse, ac as WebhookTree } from './index-KlQEcEwI.js';
7
5
  import 'kysely';
6
+ import 'zod';
8
7
  import 'pg';
8
+ import './orm.js';
9
+
10
+ /**
11
+ * Context interface with account ID resolver for logging events.
12
+ */
13
+ interface EventLoggingContext {
14
+ database?: CorsairDatabase | undefined;
15
+ $getAccountId: () => Promise<string>;
16
+ }
17
+ /**
18
+ * Logs an event to the corsair_events table.
19
+ *
20
+ * @param database - The database adapter
21
+ * @param accountId - The account ID this event belongs to
22
+ * @param eventType - The type of event (e.g., 'slack.message.created')
23
+ * @param payload - The event payload data
24
+ * @param status - The event status (defaults to 'pending')
25
+ * @returns The event ID if successful, null if failed
26
+ */
27
+ declare function logEvent(database: CorsairDatabase | undefined, accountId: string, eventType: string, payload: Record<string, unknown>, status?: 'pending' | 'processing' | 'completed' | 'failed'): Promise<string | null>;
28
+ /**
29
+ * Logs an event from a plugin context, automatically resolving the account ID.
30
+ * This is a convenience wrapper around `logEvent` for use in plugin endpoints.
31
+ *
32
+ * @param ctx - The plugin context with database and account ID resolver
33
+ * @param eventType - The type of event (e.g., 'slack.message.created')
34
+ * @param payload - The event payload data
35
+ * @param status - The event status (defaults to 'pending')
36
+ * @returns The event ID if successful, null if failed
37
+ */
38
+ declare function logEventFromContext(ctx: EventLoggingContext, eventType: string, payload: Record<string, unknown>, status?: 'pending' | 'processing' | 'completed' | 'failed'): Promise<string | null>;
9
39
 
10
40
  /**
11
41
  * Generates a new random Data Encryption Key (DEK).
@@ -118,34 +148,4 @@ declare function initializeIntegrationDEK(database: CorsairDatabase, integration
118
148
  */
119
149
  declare function initializeAccountDEK(database: CorsairDatabase, integrationName: string, tenantId: string, kek: string): Promise<string>;
120
150
 
121
- /**
122
- * Context interface with account ID resolver for logging events.
123
- */
124
- interface EventLoggingContext {
125
- database?: CorsairDatabase | undefined;
126
- $getAccountId: () => Promise<string>;
127
- }
128
- /**
129
- * Logs an event to the corsair_events table.
130
- *
131
- * @param database - The database adapter
132
- * @param accountId - The account ID this event belongs to
133
- * @param eventType - The type of event (e.g., 'slack.message.created')
134
- * @param payload - The event payload data
135
- * @param status - The event status (defaults to 'pending')
136
- * @returns The event ID if successful, null if failed
137
- */
138
- declare function logEvent(database: CorsairDatabase | undefined, accountId: string, eventType: string, payload: Record<string, unknown>, status?: 'pending' | 'processing' | 'completed' | 'failed'): Promise<string | null>;
139
- /**
140
- * Logs an event from a plugin context, automatically resolving the account ID.
141
- * This is a convenience wrapper around `logEvent` for use in plugin endpoints.
142
- *
143
- * @param ctx - The plugin context with database and account ID resolver
144
- * @param eventType - The type of event (e.g., 'slack.message.created')
145
- * @param payload - The event payload data
146
- * @param status - The event status (defaults to 'pending')
147
- * @returns The event ID if successful, null if failed
148
- */
149
- declare function logEventFromContext(ctx: EventLoggingContext, eventType: string, payload: Record<string, unknown>, status?: 'pending' | 'processing' | 'completed' | 'failed'): Promise<string | null>;
150
-
151
151
  export { AccountKeyManagerFor, AuthTypes, type EventLoggingContext, IntegrationKeyManagerFor, createAccountKeyManager, createIntegrationKeyManager, decryptConfig, decryptDEK, decryptWithDEK, encryptConfig, encryptDEK, encryptWithDEK, generateDEK, initializeAccountDEK, initializeIntegrationDEK, logEvent, logEventFromContext, reEncryptConfig };
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,o as n,p as o,q as p,r as q}from"./chunk-ZWWGVPSP.js";import"./chunk-2PB34FTK.js";import"./chunk-73HYPGOI.js";export{i as BASE_AUTH_FIELDS,p as CORSAIR_INTERNAL,k as createAccountKeyManager,q as createCorsair,j as createIntegrationKeyManager,g as decryptConfig,c as decryptDEK,e as decryptWithDEK,f as encryptConfig,b as encryptDEK,d as encryptWithDEK,a as generateDEK,m as initializeAccountDEK,l as initializeIntegrationDEK,n as logEvent,o as logEventFromContext,h as reEncryptConfig};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,o as n,p as o,q as p,r as q}from"./chunk-YE7LLFD4.js";import"./chunk-2PB34FTK.js";import"./chunk-B6CM5Q2M.js";import"./chunk-QAIKSQAD.js";export{i as BASE_AUTH_FIELDS,p as CORSAIR_INTERNAL,k as createAccountKeyManager,q as createCorsair,j as createIntegrationKeyManager,g as decryptConfig,c as decryptDEK,e as decryptWithDEK,f as encryptConfig,b as encryptDEK,d as encryptWithDEK,a as generateDEK,m as initializeAccountDEK,l as initializeIntegrationDEK,n as logEvent,o as logEventFromContext,h as reEncryptConfig};
package/dist/db.js CHANGED
@@ -1 +1 @@
1
- import{a as g}from"./chunk-N2XRSSRL.js";import{a as b,b as c,c as d,d as e,e as f}from"./chunk-HO245J34.js";import{a}from"./chunk-73HYPGOI.js";export{c as CorsairAccountsSchema,d as CorsairEntitiesSchema,e as CorsairEventsSchema,b as CorsairIntegrationsSchema,f as CorsairPermissionsSchema,a as createCorsairDatabase,g as sql};
1
+ import{a as g}from"./chunk-N2XRSSRL.js";import{a as b,b as c,c as d,d as e,e as f}from"./chunk-HO245J34.js";import{a}from"./chunk-B6CM5Q2M.js";import"./chunk-QAIKSQAD.js";export{c as CorsairAccountsSchema,d as CorsairEntitiesSchema,e as CorsairEventsSchema,b as CorsairIntegrationsSchema,f as CorsairPermissionsSchema,a as createCorsairDatabase,g as sql};
@@ -1,5 +1,5 @@
1
1
  import { CorsairDatabase } from './db.js';
2
- import { C as CorsairPlugin, a as CorsairIntegration, b as CorsairTenantWrapper, c as CorsairSingleTenantClient } from './index-D_Ah5Tz6.js';
2
+ import { C as CorsairPlugin, a as CorsairIntegration, b as CorsairTenantWrapper, c as CorsairSingleTenantClient } from './index-KlQEcEwI.js';
3
3
 
4
4
  declare const CORSAIR_INTERNAL: unique symbol;
5
5
  type CorsairInternalConfig = {
@@ -3,8 +3,8 @@ import { CorsairPluginSchema, PluginEntityClients } from './orm.js';
3
3
  import { CorsairDatabase, CorsairDatabaseInput, CorsairPermission } from './db.js';
4
4
 
5
5
  type AllErrors = 'RATE_LIMIT_ERROR' | 'AUTH_ERROR' | 'PERMISSION_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'SERVER_ERROR' | 'VALIDATION_ERROR' | 'NOT_FOUND_ERROR' | 'BAD_REQUEST_ERROR' | 'PARSING_ERROR' | 'DEFAULT' | (string & {});
6
- declare const BaseProviders: readonly ["airtable", "amplitude", "asana", "box", "cal", "calendly", "discord", "dropbox", "exa", "figma", "fireflies", "github", "gmail", "googlecalendar", "googledrive", "googlesheets", "hackernews", "hubspot", "intercom", "jira", "linear", "monday", "notion", "oura", "pagerduty", "posthog", "resend", "sentry", "slack", "spotify", "stripe", "tavily", "teams", "telegram", "todoist", "trello", "twitter", "twitterapiio", "typeform", "zoom"];
7
- type AllProviders = 'airtable' | 'amplitude' | 'asana' | 'box' | 'cal' | 'calendly' | 'discord' | 'dropbox' | 'exa' | 'figma' | 'fireflies' | 'github' | 'gmail' | 'googlecalendar' | 'googledrive' | 'googlesheets' | 'hackernews' | 'hubspot' | 'intercom' | 'jira' | 'linear' | 'monday' | 'notion' | 'oura' | 'pagerduty' | 'posthog' | 'resend' | 'sentry' | 'slack' | 'spotify' | 'stripe' | 'tavily' | 'teams' | 'telegram' | 'todoist' | 'trello' | 'twitter' | 'twitterapiio' | 'typeform' | 'zoom' | (string & {});
6
+ declare const BaseProviders: readonly ["airtable", "amplitude", "asana", "box", "cal", "calendly", "cursor", "discord", "dropbox", "exa", "figma", "fireflies", "github", "gmail", "googlecalendar", "googledrive", "googlesheets", "hackernews", "hubspot", "intercom", "jira", "linear", "monday", "notion", "onedrive", "oura", "outlook", "pagerduty", "posthog", "razorpay", "resend", "sentry", "sharepoint", "slack", "spotify", "strava", "stripe", "tavily", "teams", "telegram", "todoist", "trello", "twitter", "twitterapiio", "youtube", "typeform", "zoom"];
7
+ type AllProviders = 'airtable' | 'amplitude' | 'asana' | 'box' | 'cal' | 'calendly' | 'cursor' | 'discord' | 'dropbox' | 'exa' | 'figma' | 'fireflies' | 'github' | 'gmail' | 'googlecalendar' | 'googledrive' | 'googlesheets' | 'hackernews' | 'hubspot' | 'intercom' | 'jira' | 'linear' | 'monday' | 'notion' | 'onedrive' | 'oura' | 'outlook' | 'pagerduty' | 'posthog' | 'razorpay' | 'resend' | 'sentry' | 'sharepoint' | 'slack' | 'spotify' | 'strava' | 'stripe' | 'tavily' | 'teams' | 'telegram' | 'todoist' | 'trello' | 'twitter' | 'twitterapiio' | 'youtube' | 'typeform' | 'zoom' | (string & {});
8
8
  type AuthTypes = 'oauth_2' | 'api_key' | 'bot_token';
9
9
  type PickAuth<T extends AuthTypes> = T;
10
10
 
@@ -1168,4 +1168,4 @@ type CorsairSingleTenantClient<Plugins extends readonly CorsairPlugin[]> = Corsa
1168
1168
  permissions: CorsairPermissionsNamespace;
1169
1169
  };
1170
1170
 
1171
- export { type RequiredPluginEndpointMeta as $, type AuthTypes as A, type BoundWebhookTree as B, type CorsairPlugin as C, type RetryStrategy as D, type EndpointPathsOf as E, type CorsairInspectMethods as F, type EndpointSchemaResult as G, type EnforcePermissionOptions as H, type IntegrationKeyManagerFor as I, type EnforcePermissionResult as J, type BeforeHookResult as K, type CorsairKeyBuilder as L, type CorsairKeyBuilderBase as M, type OAuthConfig as N, type OAuth2IntegrationCredentials as O, type PluginAuthConfig as P, type CorsairPluginContext as Q, type RawWebhookRequest as R, type EndpointHooks as S, type EndpointMetaEntry as T, type EndpointRiskLevel as U, type KeyBuilderContext as V, type WebhookResponse as W, type PermissionMode as X, type PermissionPolicy as Y, type PluginEndpointMeta as Z, type PluginPermissionsConfig as _, type CorsairIntegration as a, type RequiredPluginEndpointSchemas as a0, type RequiredPluginWebhookSchemas as a1, type WebhookHooks as a2, type Bivariant$2 as a3, type UnionToIntersection$1 as a4, type BindWebhooks as a5, type BoundWebhook as a6, type CorsairWebhook as a7, type CorsairWebhookHandler as a8, type CorsairWebhookMatcher as a9, type WebhookPathsOf as aa, type WebhookRequest as ab, type WebhookTree as ac, type CorsairTenantWrapper as b, type CorsairSingleTenantClient as c, type CorsairPermissionsNamespace as d, BaseProviders as e, type AccountKeyManagerFor as f, type AccountFieldNames as g, type BaseAuthFieldConfig as h, type BaseKeyManager as i, type IntegrationFieldNames as j, BASE_AUTH_FIELDS as k, type CorsairClient as l, type AllProviders as m, type PickAuth as n, type BindEndpoints as o, type BoundEndpointFn as p, type BoundEndpointTree as q, type CorsairContext as r, type CorsairEndpoint as s, type EndpointTree as t, type CorsairErrorHandler as u, type ErrorContext as v, type ErrorHandler as w, type ErrorHandlerAndMatchFunction as x, type ErrorMatcher as y, type RetryStrategies as z };
1171
+ export { type RequiredPluginEndpointMeta as $, type AuthTypes as A, type BoundWebhookTree as B, type CorsairPlugin as C, type RetryStrategy as D, type EndpointPathsOf as E, type CorsairInspectMethods as F, type EndpointSchemaResult as G, type EnforcePermissionOptions as H, type IntegrationKeyManagerFor as I, type EnforcePermissionResult as J, type BeforeHookResult as K, type CorsairKeyBuilder as L, type CorsairKeyBuilderBase as M, type CorsairPluginContext as N, type OAuth2IntegrationCredentials as O, type PluginAuthConfig as P, type EndpointHooks as Q, type RawWebhookRequest as R, type EndpointMetaEntry as S, type EndpointRiskLevel as T, type KeyBuilderContext as U, type OAuthConfig as V, type WebhookResponse as W, type PermissionMode as X, type PermissionPolicy as Y, type PluginEndpointMeta as Z, type PluginPermissionsConfig as _, type CorsairIntegration as a, type RequiredPluginEndpointSchemas as a0, type RequiredPluginWebhookSchemas as a1, type WebhookHooks as a2, type Bivariant$2 as a3, type UnionToIntersection$1 as a4, type BindWebhooks as a5, type BoundWebhook as a6, type CorsairWebhook as a7, type CorsairWebhookHandler as a8, type CorsairWebhookMatcher as a9, type WebhookPathsOf as aa, type WebhookRequest as ab, type WebhookTree as ac, type CorsairTenantWrapper as b, type CorsairSingleTenantClient as c, type CorsairPermissionsNamespace as d, BaseProviders as e, type AccountKeyManagerFor as f, type AccountFieldNames as g, type BaseAuthFieldConfig as h, type BaseKeyManager as i, type IntegrationFieldNames as j, BASE_AUTH_FIELDS as k, type CorsairClient as l, type AllProviders as m, type PickAuth as n, type BindEndpoints as o, type BoundEndpointFn as p, type BoundEndpointTree as q, type CorsairContext as r, type CorsairEndpoint as s, type EndpointTree as t, type CorsairErrorHandler as u, type ErrorContext as v, type ErrorHandler as w, type ErrorHandlerAndMatchFunction as x, type ErrorMatcher as y, type RetryStrategies as z };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { c as createCorsair } from './index-DpPKj1ZX.js';
2
- import { d as CorsairPermissionsNamespace, B as BoundWebhookTree, R as RawWebhookRequest, e as BaseProviders, W as WebhookResponse } from './index-D_Ah5Tz6.js';
1
+ export { c as createCorsair } from './index-D3UKvoWx.js';
2
+ import { d as CorsairPermissionsNamespace, B as BoundWebhookTree, R as RawWebhookRequest, e as BaseProviders, W as WebhookResponse } from './index-KlQEcEwI.js';
3
3
  export { SetupCorsairOptions, setupCorsair } from './setup.js';
4
4
  import './db.js';
5
5
  import 'kysely';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as W}from"./chunk-BEVGZD7X.js";import{n as k,r as x}from"./chunk-ZWWGVPSP.js";import"./chunk-7IH5DNUL.js";import"./chunk-2PB34FTK.js";import"./chunk-HO245J34.js";import"./chunk-73HYPGOI.js";var R=Symbol.for("corsair:internal");function P(n,r){let o=n;for(let e of r){if(!o||typeof o!="object")return null;o=o[e]}return typeof o=="function"?o:null}function b(n){return n[R]?.database}async function I(n,r){let o=new Date().toISOString(),e=await n.permissions.find_by_token(r);if(!e)return console.error("executePermission: no permission found for token."),{error:"executePermission: no permission found for token."};if(e.status!=="approved")return console.error(`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`};if(e.expires_at<o){let i=b(n);return i&&await i.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",e.id).execute(),console.error(`executePermission: permission '${e.id}' has expired.`),{error:`executePermission: permission '${e.id}' has expired.`,endpoint:e.endpoint,plugin:e.plugin,result:null}}let t=e.tenant_id??"default",g=(n.withTenant?n.withTenant(t):n)[e.plugin];if(!g?.api)return console.error(`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`),{error:`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`,plugin:e.plugin,endpoint:e.endpoint,result:null};let d=P(g.api,e.endpoint.split("."));if(!d)return console.error(`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`};await n.permissions.set_executing(e.id);try{let i=typeof e.args=="string"?JSON.parse(e.args):e.args,a=await d(i);return await n.permissions.set_completed(e.id),{plugin:e.plugin,endpoint:e.endpoint,result:a}}catch(i){let a=i instanceof Error?i.message:String(i),c=b(n);return c&&await c.db.updateTable("corsair_permissions").set({status:"failed",error:a,updated_at:new Date}).where("id","=",e.id).execute(),{plugin:e.plugin,endpoint:e.endpoint,result:null,error:a}}}function B(n){return n!==null&&typeof n=="object"&&"match"in n&&"handler"in n&&typeof n.match=="function"&&typeof n.handler=="function"}function m(n,r,o=[]){for(let[e,t]of Object.entries(n))if(B(t)){if(t.match(r))return{webhook:t,path:[...o,e]}}else if(t&&typeof t=="object"){let s=m(t,r,[...o,e]);if(s)return s}return null}function C(n){let r={};for(let[o,e]of Object.entries(n))r[o.toLowerCase()]=Array.isArray(e)?e[0]:e;return r}function S(n){let r=n["x-goog-resource-uri"],o=n["x-goog-channel-id"];if(!r||!o)return null;let e={resourceId:n["x-goog-resource-id"]||"",resourceState:n["x-goog-resource-state"]||"",resourceUri:r,channelId:o,channelExpiration:n["x-goog-channel-expiration"]||""};return r.includes("/drive/")&&(e.kind="drive#change"),{message:{data:Buffer.from(JSON.stringify(e)).toString("base64"),messageId:n["x-goog-message-number"]||""}}}async function T(n,r,o,e){let t=C(r),s=typeof o=="string"?JSON.parse(o):o;(!s||typeof s=="object"&&Object.keys(s).length===0)&&t["x-goog-resource-uri"]&&(s=S(t)||s);let d={headers:t,body:s},i=e?.tenantId||"default",a=n.withTenant?n.withTenant(i):n,c=k;for(let l of c){let p=a[l];if(!p||!p.webhooks||p.pluginWebhookMatcher&&!p.pluginWebhookMatcher(d))continue;let f=m(p.webhooks,d);if(!f)continue;let h=f.path.join("."),w={payload:s,headers:t,rawBody:typeof o=="string"?o:JSON.stringify(o)};try{let u=await f.webhook.handler(w),y=!!Object.keys(u.returnToSender||{})?.length;return{plugin:l,action:h,body:s,response:y?{...u?.returnToSender,success:!0}:{success:!0},...u.responseHeaders&&{responseHeaders:u.responseHeaders}}}catch(u){return console.error(`Error executing webhook handler for ${l}.${h}:`,u),{plugin:l,action:h,body:s,response:{success:!1,error:u instanceof Error?u.message:"Unknown error"}}}}return{plugin:null,action:null,body:null}}export{x as createCorsair,I as executePermission,T as processWebhook,W as setupCorsair};
1
+ import{a as W}from"./chunk-R6WAUPZG.js";import{n as k,r as x}from"./chunk-YE7LLFD4.js";import"./chunk-7IH5DNUL.js";import"./chunk-2PB34FTK.js";import"./chunk-HO245J34.js";import"./chunk-B6CM5Q2M.js";import"./chunk-QAIKSQAD.js";var R=Symbol.for("corsair:internal");function P(n,r){let o=n;for(let e of r){if(!o||typeof o!="object")return null;o=o[e]}return typeof o=="function"?o:null}function b(n){return n[R]?.database}async function I(n,r){let o=new Date().toISOString(),e=await n.permissions.find_by_token(r);if(!e)return console.error("executePermission: no permission found for token."),{error:"executePermission: no permission found for token."};if(e.status!=="approved")return console.error(`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`};if(e.expires_at<o){let i=b(n);return i&&await i.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",e.id).execute(),console.error(`executePermission: permission '${e.id}' has expired.`),{error:`executePermission: permission '${e.id}' has expired.`,endpoint:e.endpoint,plugin:e.plugin,result:null}}let t=e.tenant_id??"default",g=(n.withTenant?n.withTenant(t):n)[e.plugin];if(!g?.api)return console.error(`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`),{error:`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`,plugin:e.plugin,endpoint:e.endpoint,result:null};let d=P(g.api,e.endpoint.split("."));if(!d)return console.error(`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`};await n.permissions.set_executing(e.id);try{let i=typeof e.args=="string"?JSON.parse(e.args):e.args,a=await d(i);return await n.permissions.set_completed(e.id),{plugin:e.plugin,endpoint:e.endpoint,result:a}}catch(i){let a=i instanceof Error?i.message:String(i),c=b(n);return c&&await c.db.updateTable("corsair_permissions").set({status:"failed",error:a,updated_at:new Date}).where("id","=",e.id).execute(),{plugin:e.plugin,endpoint:e.endpoint,result:null,error:a}}}function B(n){return n!==null&&typeof n=="object"&&"match"in n&&"handler"in n&&typeof n.match=="function"&&typeof n.handler=="function"}function m(n,r,o=[]){for(let[e,t]of Object.entries(n))if(B(t)){if(t.match(r))return{webhook:t,path:[...o,e]}}else if(t&&typeof t=="object"){let s=m(t,r,[...o,e]);if(s)return s}return null}function C(n){let r={};for(let[o,e]of Object.entries(n))r[o.toLowerCase()]=Array.isArray(e)?e[0]:e;return r}function S(n){let r=n["x-goog-resource-uri"],o=n["x-goog-channel-id"];if(!r||!o)return null;let e={resourceId:n["x-goog-resource-id"]||"",resourceState:n["x-goog-resource-state"]||"",resourceUri:r,channelId:o,channelExpiration:n["x-goog-channel-expiration"]||""};return r.includes("/drive/")&&(e.kind="drive#change"),{message:{data:Buffer.from(JSON.stringify(e)).toString("base64"),messageId:n["x-goog-message-number"]||""}}}async function T(n,r,o,e){let t=C(r),s=typeof o=="string"?JSON.parse(o):o;(!s||typeof s=="object"&&Object.keys(s).length===0)&&t["x-goog-resource-uri"]&&(s=S(t)||s);let d={headers:t,body:s},i=e?.tenantId||"default",a=n.withTenant?n.withTenant(i):n,c=k;for(let l of c){let p=a[l];if(!p||!p.webhooks||p.pluginWebhookMatcher&&!p.pluginWebhookMatcher(d))continue;let f=m(p.webhooks,d);if(!f)continue;let h=f.path.join("."),w={payload:s,headers:t,rawBody:typeof o=="string"?o:JSON.stringify(o)};try{let u=await f.webhook.handler(w),y=!!Object.keys(u.returnToSender||{})?.length;return{plugin:l,action:h,body:s,response:y?{...u?.returnToSender,success:!0}:{success:!0},...u.responseHeaders&&{responseHeaders:u.responseHeaders}}}catch(u){return console.error(`Error executing webhook handler for ${l}.${h}:`,u),{plugin:l,action:h,body:s,response:{success:!1,error:u instanceof Error?u.message:"Unknown error"}}}}return{plugin:null,action:null,body:null}}export{x as createCorsair,I as executePermission,T as processWebhook,W as setupCorsair};
package/dist/orm.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-N2XRSSRL.js";import{b as o,c as e,d as n,e as s}from"./chunk-7IH5DNUL.js";import"./chunk-2PB34FTK.js";import{a as r,b as t,c as i,d as a}from"./chunk-HO245J34.js";import"./chunk-73HYPGOI.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
+ import"./chunk-N2XRSSRL.js";import{b as o,c as e,d as n,e as s}from"./chunk-7IH5DNUL.js";import"./chunk-2PB34FTK.js";import{a as r,b as t,c as i,d as a}from"./chunk-HO245J34.js";import"./chunk-B6CM5Q2M.js";import"./chunk-QAIKSQAD.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};
package/dist/setup.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as CorsairPlugin, c as CorsairSingleTenantClient } from './index-D_Ah5Tz6.js';
1
+ import { C as CorsairPlugin, c as CorsairSingleTenantClient } from './index-KlQEcEwI.js';
2
2
  import 'zod';
3
3
  import './orm.js';
4
4
  import './db.js';
package/dist/setup.js CHANGED
@@ -1 +1 @@
1
- import{a as o}from"./chunk-BEVGZD7X.js";import"./chunk-ZWWGVPSP.js";import"./chunk-7IH5DNUL.js";import"./chunk-2PB34FTK.js";import"./chunk-HO245J34.js";import"./chunk-73HYPGOI.js";export{o as setupCorsair};
1
+ import{a as o}from"./chunk-R6WAUPZG.js";import"./chunk-YE7LLFD4.js";import"./chunk-7IH5DNUL.js";import"./chunk-2PB34FTK.js";import"./chunk-HO245J34.js";import"./chunk-B6CM5Q2M.js";import"./chunk-QAIKSQAD.js";export{o as setupCorsair};
@@ -0,0 +1,15 @@
1
+ import * as kysely from 'kysely';
2
+ import { Kysely } from 'kysely';
3
+ import { CorsairKyselyDatabase, CorsairDatabase } from './db.js';
4
+ import 'zod';
5
+ import 'pg';
6
+
7
+ declare function createIntegrationAndAccount(db: Kysely<CorsairKyselyDatabase>, pluginId: string, tenantId?: string): Promise<kysely.InsertResult[]>;
8
+
9
+ declare function createTestDatabase(): {
10
+ db: Kysely<CorsairKyselyDatabase>;
11
+ database: CorsairDatabase;
12
+ cleanup: () => void;
13
+ };
14
+
15
+ export { createIntegrationAndAccount, createTestDatabase };
package/dist/tests.js ADDED
@@ -0,0 +1,42 @@
1
+ import{a as n}from"./chunk-QAIKSQAD.js";function s(a,e,r="default"){let t=new Date,T=`${e}-integration`,o=`${e}-account`;return a.insertInto("corsair_integrations").values({id:T,created_at:t,updated_at:t,name:e,config:{},dek:void 0}).execute().then(()=>a.insertInto("corsair_accounts").values({id:o,created_at:t,updated_at:t,tenant_id:r,integration_id:T,config:{},dek:void 0}).execute())}import i from"better-sqlite3";import{Kysely as E,SqliteDialect as N}from"kysely";function d(){let a=new i(":memory:");a.exec(`
2
+
3
+ CREATE TABLE IF NOT EXISTS corsair_integrations (
4
+ id TEXT PRIMARY KEY,
5
+ created_at INTEGER NOT NULL,
6
+ updated_at INTEGER NOT NULL,
7
+ name TEXT NOT NULL,
8
+ config TEXT NOT NULL,
9
+ dek TEXT NULL
10
+ );
11
+
12
+ CREATE TABLE IF NOT EXISTS corsair_accounts (
13
+ id TEXT PRIMARY KEY,
14
+ created_at INTEGER NOT NULL,
15
+ updated_at INTEGER NOT NULL,
16
+ tenant_id TEXT NOT NULL,
17
+ integration_id TEXT NOT NULL,
18
+ config TEXT NOT NULL,
19
+ dek TEXT NULL
20
+ );
21
+
22
+ CREATE TABLE IF NOT EXISTS corsair_entities (
23
+ id TEXT PRIMARY KEY,
24
+ created_at INTEGER NOT NULL,
25
+ updated_at INTEGER NOT NULL,
26
+ account_id TEXT NOT NULL,
27
+ entity_id TEXT NOT NULL,
28
+ entity_type TEXT NOT NULL,
29
+ version TEXT NOT NULL,
30
+ data TEXT NOT NULL
31
+ );
32
+
33
+ CREATE TABLE IF NOT EXISTS corsair_events (
34
+ id TEXT PRIMARY KEY,
35
+ created_at INTEGER NOT NULL,
36
+ updated_at INTEGER NOT NULL,
37
+ account_id TEXT NOT NULL,
38
+ event_type TEXT NOT NULL,
39
+ payload TEXT NOT NULL,
40
+ status TEXT
41
+ );
42
+ `);let e=new E({dialect:new N({database:a}),plugins:[new n]});return{db:e,database:{db:e},cleanup:()=>{e.destroy(),a.close()}}}export{s as createIntegrationAndAccount,d as createTestDatabase};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "corsair",
3
- "version": "0.1.52",
3
+ "version": "0.1.54",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -36,6 +36,11 @@
36
36
  "dev-source": "./http.ts",
37
37
  "types": "./dist/http.d.ts",
38
38
  "default": "./dist/http.js"
39
+ },
40
+ "./tests": {
41
+ "dev-source": "./tests.ts",
42
+ "types": "./dist/tests.d.ts",
43
+ "default": "./dist/tests.js"
39
44
  }
40
45
  },
41
46
  "dependencies": {
@@ -1 +0,0 @@
1
- import{Kysely as i,PostgresDialect as c,SqliteDialect as p}from"kysely";import{OperationNodeTransformer as u}from"kysely";function s(e){return e instanceof Date?e.toISOString():e!==null&&typeof e=="object"&&!Buffer.isBuffer(e)?JSON.stringify(e):e}var o=class extends u{transformValue(r){let t=s(r.value);return t===r.value?r:{...r,value:t}}transformPrimitiveValueList(r){let t=r.values.map(s);return t.some((n,l)=>n!==r.values[l])?{...r,values:t}:r}},y=new o,a=class{transformQuery(r){return y.transformNode(r.node)}async transformResult(r){return r.result}};function f(e){return typeof e.query=="function"&&typeof e.connect=="function"}function m(e){let r=e;return typeof r.prepare=="function"&&typeof r.exec=="function"&&typeof r.close=="function"&&!("query"in e)}function b(e){return typeof e.selectFrom=="function"}function w(e){if(b(e))return{db:e};if(m(e))return{db:new i({dialect:new p({database:e}),plugins:[new a]})};if(f(e))return{db:new i({dialect:new c({pool:e})})};throw new Error("Unsupported database input. Expected a pg Pool, better-sqlite3 Database, or a Kysely instance.")}export{w as a};