corsair 0.1.47 → 0.1.49
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-2PB34FTK.js +1 -0
- package/dist/chunk-7IH5DNUL.js +1 -0
- package/dist/{chunk-B7SHIP45.js → chunk-VPU5CT64.js} +1 -1
- package/dist/chunk-XBYB3RVJ.js +26 -0
- package/dist/core.d.ts +34 -4
- package/dist/core.js +1 -1
- package/dist/db.js +1 -1
- package/dist/http.d.ts +112 -0
- package/dist/http.js +1 -0
- package/dist/{index-D30v9sPr.d.ts → index-D_Ah5Tz6.d.ts} +11 -73
- package/dist/{index-CBFNJJDR.d.ts → index-DpPKj1ZX.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/orm.js +1 -1
- package/dist/setup.d.ts +1 -1
- package/dist/setup.js +1 -1
- package/package.json +6 -202
- package/dist/chunk-34Z5IBIX.js +0 -1
- package/dist/chunk-3KXTFATC.js +0 -1
- package/dist/chunk-476ZUILE.js +0 -1
- package/dist/chunk-A7CRE5AE.js +0 -1
- package/dist/chunk-BYXBJQAS.js +0 -0
- package/dist/chunk-BZ3WPT6I.js +0 -1
- package/dist/chunk-J7NCVPA4.js +0 -15
- package/dist/chunk-Q55TIVXA.js +0 -1
- package/dist/plugins/airtable/index.d.ts +0 -2815
- package/dist/plugins/airtable/index.js +0 -1
- package/dist/plugins/amplitude/index.d.ts +0 -3207
- package/dist/plugins/amplitude/index.js +0 -1
- package/dist/plugins/asana/index.d.ts +0 -25950
- package/dist/plugins/asana/index.js +0 -1
- package/dist/plugins/box/index.d.ts +0 -15342
- package/dist/plugins/box/index.js +0 -1
- package/dist/plugins/cal/index.d.ts +0 -10751
- package/dist/plugins/cal/index.js +0 -1
- package/dist/plugins/calendly/index.d.ts +0 -14276
- package/dist/plugins/calendly/index.js +0 -1
- package/dist/plugins/discord/index.d.ts +0 -11225
- package/dist/plugins/discord/index.js +0 -1
- package/dist/plugins/dropbox/index.d.ts +0 -8196
- package/dist/plugins/dropbox/index.js +0 -1
- package/dist/plugins/exa/index.d.ts +0 -3556
- package/dist/plugins/exa/index.js +0 -1
- package/dist/plugins/fireflies/index.d.ts +0 -4576
- package/dist/plugins/fireflies/index.js +0 -115
- package/dist/plugins/github/index.d.ts +0 -28386
- package/dist/plugins/github/index.js +0 -1
- package/dist/plugins/gmail/index.d.ts +0 -2838
- package/dist/plugins/gmail/index.js +0 -1
- package/dist/plugins/googlecalendar/index.d.ts +0 -5411
- package/dist/plugins/googlecalendar/index.js +0 -1
- package/dist/plugins/googledrive/index.d.ts +0 -4136
- package/dist/plugins/googledrive/index.js +0 -1
- package/dist/plugins/googlesheets/index.d.ts +0 -1403
- package/dist/plugins/googlesheets/index.js +0 -1
- package/dist/plugins/hackernews/index.d.ts +0 -3076
- package/dist/plugins/hackernews/index.js +0 -1
- package/dist/plugins/hubspot/index.d.ts +0 -15924
- package/dist/plugins/hubspot/index.js +0 -1
- package/dist/plugins/intercom/index.d.ts +0 -10754
- package/dist/plugins/intercom/index.js +0 -1
- package/dist/plugins/jira/index.d.ts +0 -6961
- package/dist/plugins/jira/index.js +0 -1
- package/dist/plugins/linear/index.d.ts +0 -17670
- package/dist/plugins/linear/index.js +0 -548
- package/dist/plugins/monday/index.d.ts +0 -14151
- package/dist/plugins/monday/index.js +0 -235
- package/dist/plugins/notion/index.d.ts +0 -2460
- package/dist/plugins/notion/index.js +0 -1
- package/dist/plugins/oura/index.d.ts +0 -1545
- package/dist/plugins/oura/index.js +0 -1
- package/dist/plugins/pagerduty/index.d.ts +0 -7863
- package/dist/plugins/pagerduty/index.js +0 -1
- package/dist/plugins/posthog/index.d.ts +0 -505
- package/dist/plugins/posthog/index.js +0 -1
- package/dist/plugins/resend/index.d.ts +0 -1995
- package/dist/plugins/resend/index.js +0 -1
- package/dist/plugins/sentry/index.d.ts +0 -7322
- package/dist/plugins/sentry/index.js +0 -1
- package/dist/plugins/slack/index.d.ts +0 -38957
- package/dist/plugins/slack/index.js +0 -1
- package/dist/plugins/spotify/index.d.ts +0 -13310
- package/dist/plugins/spotify/index.js +0 -1
- package/dist/plugins/stripe/index.d.ts +0 -6207
- package/dist/plugins/stripe/index.js +0 -1
- package/dist/plugins/tavily/index.d.ts +0 -352
- package/dist/plugins/tavily/index.js +0 -1
- package/dist/plugins/telegram/index.d.ts +0 -6103
- package/dist/plugins/telegram/index.js +0 -1
- package/dist/plugins/todoist/index.d.ts +0 -3562
- package/dist/plugins/todoist/index.js +0 -1
- package/dist/plugins/trello/index.d.ts +0 -9175
- package/dist/plugins/trello/index.js +0 -1
- package/dist/plugins/twitter/index.d.ts +0 -267
- package/dist/plugins/twitter/index.js +0 -1
- package/dist/plugins/twitterapiio/index.d.ts +0 -19242
- package/dist/plugins/twitterapiio/index.js +0 -1
- package/dist/plugins/zoom/index.d.ts +0 -8382
- package/dist/plugins/zoom/index.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v7 as j}from"uuid";function g(){return j()}import{z as u}from"zod";import{sql as d}from"kysely";function m(e){return e.replace(/'/g,"''")}function k(e){let t=m(e);return d`data->>'${d.raw(t)}'`}function D(e){let t=m(e);return d`(data->>'${d.raw(t)}')::numeric`}function F(e){let t=m(e);return d`(data->>'${d.raw(t)}')::boolean`}function T(e){let t=m(e);return d`(data->>'${d.raw(t)}')::timestamptz`}function A(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function _(e){let t=e;for(;t;){if(t instanceof u.ZodOptional||t instanceof u.ZodNullable){t=t._def.innerType;continue}if(t instanceof u.ZodDefault){t=t._def.innerType;continue}if(t instanceof u.ZodEffects){t=t._def.schema;continue}break}return t}function x(e){let t=_(e);if(t instanceof u.ZodString)return"string";if(t instanceof u.ZodNumber)return"number";if(t instanceof u.ZodBoolean)return"boolean";if(t instanceof u.ZodDate)return"date"}function B(e){let t=_(e);if(!(t instanceof u.ZodObject))return{};let r=t.shape,n={};for(let[y,w]of Object.entries(r)){let s=x(w);s&&(n[y]=s)}return n}function R(e,t,r){if(typeof r=="string")return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;"equals"in n&&typeof n.equals=="string"&&(e=e.where(t,"=",n.equals)),"contains"in n&&typeof n.contains=="string"&&(e=e.where(t,"like",`%${n.contains}%`)),"startsWith"in n&&typeof n.startsWith=="string"&&(e=e.where(t,"like",`${n.startsWith}%`)),"endsWith"in n&&typeof n.endsWith=="string"&&(e=e.where(t,"like",`%${n.endsWith}`)),"in"in n&&Array.isArray(n.in)&&(e=e.where(t,"in",n.in))}return e}function Z(e,t,r){if(typeof r=="number")return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;typeof n.equals=="number"&&(e=e.where(t,"=",n.equals)),typeof n.gt=="number"&&(e=e.where(t,">",n.gt)),typeof n.gte=="number"&&(e=e.where(t,">=",n.gte)),typeof n.lt=="number"&&(e=e.where(t,"<",n.lt)),typeof n.lte=="number"&&(e=e.where(t,"<=",n.lte)),Array.isArray(n.in)&&(e=e.where(t,"in",n.in))}return e}function C(e,t,r){if(typeof r=="boolean")return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;typeof n.equals=="boolean"&&(e=e.where(t,"=",n.equals))}return e}function S(e,t,r){if(r instanceof Date)return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;if(n.equals instanceof Date&&(e=e.where(t,"=",n.equals)),n.before instanceof Date&&(e=e.where(t,"<",n.before)),n.after instanceof Date&&(e=e.where(t,">",n.after)),Array.isArray(n.between)&&n.between.length===2){let[y,w]=n.between;y instanceof Date&&(e=e.where(t,">=",y)),w instanceof Date&&(e=e.where(t,"<=",w))}}return e}function I(e,t,r,n){return r==="number"?Z(e,D(t),n):r==="boolean"?C(e,F(t),n):r==="date"?S(e,T(t),n):R(e,k(t),n)}function W(e,t,r){if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;return"equals"in n&&(e=e.where(t,"=",n.equals)),"contains"in n&&typeof n.contains=="string"&&(e=e.where(t,"like",`%${n.contains}%`)),"startsWith"in n&&typeof n.startsWith=="string"&&(e=e.where(t,"like",`${n.startsWith}%`)),"endsWith"in n&&typeof n.endsWith=="string"&&(e=e.where(t,"like",`%${n.endsWith}`)),"in"in n&&Array.isArray(n.in)&&(e=e.where(t,"in",n.in)),e}return e.where(t,"=",r)}function Q(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function p(e,t,r){return e.selectFrom("corsair_entities").selectAll().where("account_id","=",t).where("entity_type","=",r)}function z(e,t,r,n,y){let w=B(y);function s(i){let o=A(i.data);return{...i,data:y.parse(o)}}return{findByEntityId:async i=>{let o=await t(),a=await p(e,o,r).where("entity_id","=",i).executeTakeFirst();return a?s(a):null},findById:async i=>{let o=await t(),a=await p(e,o,r).where("id","=",i).executeTakeFirst();return a?s(a):null},findManyByEntityIds:async i=>{if(i.length===0)return[];let o=await t();return(await p(e,o,r).where("entity_id","in",i).execute()).map(s)},list:async i=>{let o=await t(),a=p(e,o,r);return typeof i?.limit=="number"&&(a=a.limit(i.limit)),typeof i?.offset=="number"&&(a=a.offset(i.offset)),(await a.execute()).map(s)},search:async i=>{let o=await t(),a=p(e,o,r),l=new Set(["data","limit","offset"]);for(let[c,f]of Object.entries(i))l.has(c)||f===void 0||(a=W(a,c,f));if(i.data&&typeof i.data=="object")for(let[c,f]of Object.entries(i.data)){if(f===void 0)continue;let b=w[c]??"string";a=I(a,c,b,f)}return typeof i.limit=="number"&&(a=a.limit(i.limit)),typeof i.offset=="number"&&(a=a.offset(i.offset)),(await a.execute()).map(s)},upsertByEntityId:async(i,o)=>{let a=await t(),l=y.parse(o),h=new Date,c=await p(e,a,r).select("id").where("entity_id","=",i).executeTakeFirst();if(c?.id){await e.updateTable("corsair_entities").set({version:n,data:l,updated_at:h}).where("id","=",c.id).execute();let E=await e.selectFrom("corsair_entities").selectAll().where("id","=",c.id).executeTakeFirst();return s(E)}let f=g();await e.insertInto("corsair_entities").values({id:f,created_at:h,updated_at:h,account_id:a,entity_id:i,entity_type:r,version:n,data:l}).execute();let b=await e.selectFrom("corsair_entities").selectAll().where("id","=",f).executeTakeFirst();return s(b)},deleteById:async i=>{let o=await t(),a=await e.deleteFrom("corsair_entities").where("account_id","=",o).where("entity_type","=",r).where("id","=",i).executeTakeFirst();return Number(a.numDeletedRows)>0},deleteByEntityId:async i=>{let o=await t(),a=await e.deleteFrom("corsair_entities").where("account_id","=",o).where("entity_type","=",r).where("entity_id","=",i).executeTakeFirst();return Number(a.numDeletedRows)>0},count:async()=>{let i=await t(),o=await e.selectFrom("corsair_entities").select(a=>a.fn.countAll().as("count")).where("account_id","=",i).where("entity_type","=",r).executeTakeFirst();return Q(o?.count)}}}export{g as a,z as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as h,b}from"./chunk-2PB34FTK.js";import{a as E,b as I,c as x,d as D}from"./chunk-HO245J34.js";var k={corsair_integrations:E,corsair_accounts:I,corsair_entities:x,corsair_events:D};function F(t){return k[t]}function _(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}function d(t){if(!t)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function g(t){if(!t)return[];let n=[];for(let r in t){let e=r,i=t[e];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let s=i;"in"in s&&Array.isArray(s.in)?n.push({field:e,operator:"in",value:s.in}):"like"in s&&typeof s.like=="string"&&n.push({field:e,operator:"like",value:s.like})}else n.push({field:e,value:i})}return n}function p(t,n){if(!n?.length)return t;let r=t;for(let e of n){let i=e.operator??"=";r=r.where(e.field,i,e.value)}return r}function S(t){return typeof t=="number"?t:typeof t=="bigint"?Number(t):Number.parseInt(String(t??0),10)}function T(t,n){let r=F(n),e=()=>(d(t),t),i=()=>e().db.selectFrom(n),s=()=>e().db.insertInto(n),u=()=>e().db.updateTable(n),c=()=>e().db.deleteFrom(n);function m(o){let a={};for(let[l,y]of Object.entries(o))a[l]=_(y);return r.parse(a)}function C(o){let a={};for(let[l,y]of Object.entries(o))a[l]=_(y);return r.parse(a)}return{findById:async o=>{d(t);let a=i().selectAll();a=p(a,[{field:"id",value:o}]);let l=await a.executeTakeFirst();return l?m(l):null},findOne:async o=>{d(t);let a=i().selectAll();a=p(a,g(o));let l=await a.executeTakeFirst();return l?m(l):null},findMany:async o=>{d(t);let a=i().selectAll();return a=p(a,g(o?.where)),typeof o?.limit=="number"&&(a=a.limit(o.limit)),typeof o?.offset=="number"&&(a=a.offset(o.offset)),(await a.execute()).map(y=>m(y))},create:async o=>{d(t);let a=new Date,l={id:o.id??h(),created_at:a,updated_at:a,...o},y=await s().values(l).returningAll().executeTakeFirst();return y?m(y):C(l)},update:async(o,a)=>{d(t);let l={...a,updated_at:new Date},y=u().set(l).returningAll();y=p(y,[{field:"id",value:o}]);let f=await y.executeTakeFirst();return f?m(f):null},updateMany:async(o,a)=>{d(t);let l={...a,updated_at:new Date},y=i().select("id");y=p(y,g(o));let f=await y.execute();for(let P of f){let w=u().set(l);w=p(w,[{field:"id",value:P.id}]),await w.execute()}return f.length},delete:async o=>{d(t);let a=c();a=p(a,[{field:"id",value:o}]);let l=await a.executeTakeFirst();return Number(l?.numDeletedRows??0)>0},deleteMany:async o=>{d(t);let a=c();a=p(a,g(o));let l=await a.executeTakeFirst();return Number(l?.numDeletedRows??0)},count:async o=>{d(t);let a=i().select(y=>y.fn.countAll().as("count"));a=p(a,g(o));let l=await a.executeTakeFirst();return S(l?.count)}}}function R(t){let n=T(t,"corsair_integrations");return{...n,findByName:r=>n.findOne({name:r}),upsertByName:async(r,e)=>{let i=await n.findOne({name:r});return i?await n.update(i.id,e):n.create({...e,name:r})}}}function O(t){let n=T(t,"corsair_accounts");return{...n,findByTenantAndIntegration:async(r,e)=>{d(t);let i=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",e).executeTakeFirst();return i?n.findOne({tenant_id:r,integration_id:i.id}):null},listByTenant:(r,e)=>n.findMany({where:{tenant_id:r},limit:e?.limit,offset:e?.offset}),upsertByTenantAndIntegration:async(r,e,i)=>{let s=await n.findOne({tenant_id:r,integration_id:e});return s?await n.update(s.id,i):n.create({...i,tenant_id:r,integration_id:e})}}}function v(t){let n=T(t,"corsair_entities");return{...n,findByEntityId:({accountId:r,entityType:e,entityId:i})=>n.findOne({account_id:r,entity_type:e,entity_id:i}),findManyByEntityIds:async({accountId:r,entityType:e,entityIds:i})=>i.length===0?[]:(d(t),await t.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",e).where("entity_id","in",i).execute()),listByScope:({accountId:r,entityType:e,limit:i,offset:s})=>n.findMany({where:{account_id:r,entity_type:e},limit:i,offset:s}),searchByEntityId:async({accountId:r,entityType:e,query:i,limit:s,offset:u})=>{d(t);let c=t.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",e).where("entity_id","like",`%${i}%`);return typeof s=="number"&&(c=c.limit(s)),typeof u=="number"&&(c=c.offset(u)),await c.execute()},upsertByEntityId:async({accountId:r,entityType:e,entityId:i,version:s,data:u})=>{let c=await n.findOne({account_id:r,entity_type:e,entity_id:i});return c?await n.update(c.id,{version:s,data:u}):n.create({account_id:r,entity_type:e,entity_id:i,version:s,data:u})},deleteByEntityId:async({accountId:r,entityType:e,entityId:i})=>{d(t);let s=await t.db.deleteFrom("corsair_entities").where("account_id","=",r).where("entity_type","=",e).where("entity_id","=",i).executeTakeFirst();return Number(s.numDeletedRows)>0}}}function N(t){let n=T(t,"corsair_events");return{...n,listByAccount:(r,e)=>n.findMany({where:{account_id:r},limit:e?.limit,offset:e?.offset}),listByStatus:(r,e)=>{let i={status:r};return e?.accountId&&(i.account_id=e.accountId),n.findMany({where:i,limit:e?.limit,offset:e?.offset})},listPending:r=>{let e={status:"pending"};return r?.accountId&&(e.account_id=r.accountId),n.findMany({where:e,limit:r?.limit??100})},updateStatus:(r,e)=>n.update(r,{status:e})}}function A(t){return{integrations:R(t),accounts:O(t),entities:v(t),events:N(t)}}function W(t,n,r,e,i){let s=null;async function u(){if(s!==null)return s;d(t);let c=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",n.integrationName).executeTakeFirst();if(!c)throw new Error(`Integration "${n.integrationName}" not found. Make sure to create the integration first.`);let m=await t.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n.tenantId).where("integration_id","=",c.id).executeTakeFirst();if(!m)throw new Error(`Account not found for tenant "${n.tenantId}" and integration "${n.integrationName}". Make sure to create the account first.`);return s=m.id,s}return d(t),b(t.db,u,r,e,i)}function B(t){let{database:n,integrationName:r,schema:e,tenantId:i}=t,s=A(n),u={tenantId:i,integrationName:r},c=null;async function m(){if(c!==null)return c;d(n);let o=await n.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!o)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);let a=await n.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",i).where("integration_id","=",o.id).executeTakeFirst();if(!a)throw new Error(`Account not found for tenant "${i}" and integration "${r}". Make sure to create the account first.`);return c=a.id,c}let C={};for(let[o,a]of Object.entries(e.entities))C[o]=W(n,u,o,e.version,a);return{...C,$orm:s,$integrationName:r,$tenantId:i,$getAccountId:m}}function U(t,n){let r=A(t);return{$tenantId:n,$orm:r,listAccounts:e=>r.accounts.listByTenant(n,e),findAccountByIntegration:e=>r.accounts.findByTenantAndIntegration(n,e),listEntities:async e=>{d(t);let i=await t.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",n).execute();if(i.length===0)return[];let s=i.map(c=>c.id),u=t.db.selectFrom("corsair_entities").selectAll().where("account_id","in",s);return e?.entityType&&(u=u.where("entity_type","=",e.entityType)),typeof e?.limit=="number"&&(u=u.limit(e.limit)),typeof e?.offset=="number"&&(u=u.offset(e.offset)),await u.execute()},listEvents:async e=>{d(t);let i=await t.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",n).execute();if(i.length===0)return[];let s=i.map(c=>c.id),u=t.db.selectFrom("corsair_events").selectAll().where("account_id","in",s);return e?.status&&(u=u.where("status","=",e.status)),typeof e?.limit=="number"&&(u=u.limit(e.limit)),typeof e?.offset=="number"&&(u=u.offset(e.offset)),await u.execute()},forIntegration:e=>B({database:t,integrationName:e.integrationName,schema:e.schema,tenantId:n})}}function Z(t,n){return{forTenant:r=>B({database:t,integrationName:n.integrationName,schema:n.schema,tenantId:r})}}export{k as a,A as b,B as c,U as d,Z as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{q as k,r as w}from"./chunk-XBYB3RVJ.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(`
|
|
@@ -0,0 +1,26 @@
|
|
|
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 Me}from"util";var he=Me(Ke),U="aes-256-gcm",me=12,q=16,$e=16,B=32;function O(){return H(B).toString("base64")}async function K(e,t){let n=H($e),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 M(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=M(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.
|
|
2
|
+
|
|
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(m,p)};return{get_dek:f,issue_new_dek:async()=>{let u=await d.getIntegration(),p=O(),m={};if(u.dek){let x=await D(u.dek,r),b=u.config;b&&Object.keys(b).length>0&&(m=S(b,x,p))}let C=await K(p,r);return await d.updateIntegration({config:m,dek:C}),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 C={...m};for(let[b,l]of Object.entries(u))l===null?delete C[b]:C[b]=l;let x=F(C,p);await d.updateIntegration({config:x})},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(),w=l.config;return!w||Object.keys(w).length===0?{}:M(w,k)},C=async()=>{let l=await c.getIntegration(),k=await p(),w=l.config;return!w||Object.keys(w).length===0?{}:M(w,k)},b={get_dek:u,issue_new_dek:async()=>{let l=await c.getAccount(),k=O(),w={};if(l.dek){let A=await D(l.dek,o),P=l.config;P&&Object.keys(P).length>0&&(w=S(P,A,k))}let I=await K(k,o);return await c.updateAccount({config:w,dek:I}),y=k,k},...ke(m,async l=>{let k=await u(),w;try{w=await m()}catch(P){console.error(`[corsair] Failed to decrypt config for account (tenant: "${r}", integration: "${n}"), starting fresh:`,P),w={}}let I={...w};for(let[P,T]of Object.entries(l))T===null?delete I[P]:I[P]=T;let A=F(I,k);await c.updateAccount({config:A})},a)};return t==="oauth_2"&&(b.get_integration_credentials=async()=>{let l=await C();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
|
+
Action: ${r}`,`
|
|
5
|
+
To allow this, update the permission mode or add an override in your corsair config.`),{result:"blocked"};let o=JSON.stringify(e.args),i=new Date().toISOString(),s=e.tenantId??"default",a=await e.db.db.selectFrom("corsair_permissions").selectAll().where("plugin","=",e.pluginId).where("endpoint","=",e.endpointPath).where("args","=",o).where("tenant_id","=",s).where("expires_at",">",i).where("status","in",["pending","approved","executing"]).orderBy("created_at","desc").limit(1).executeTakeFirst();if(a){if(a.status==="approved"){let y=e.db,h=a.id;return{result:"allow",onComplete:async()=>{await y.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",h).execute()}}}return a.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
|
|
6
|
+
Action: ${r}`,`
|
|
7
|
+
Permission ID: ${a.id}`,`
|
|
8
|
+
Use the token to approve or deny this request.`),{result:"blocked"})}let d=Be(),g=Ne(32).toString("hex"),f=e.timeoutMs??600*1e3,c=new Date(Date.now()+f).toISOString();return await e.db.db.insertInto("corsair_permissions").values({id:d,created_at:new Date,updated_at:new Date,token:g,plugin:e.pluginId,endpoint:e.endpointPath,args:o,tenant_id:s,status:"pending",expires_at:c}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
|
|
9
|
+
Action: ${r}`,`
|
|
10
|
+
Permission ID: ${d}`,`
|
|
11
|
+
Permission token: ${g}`,`
|
|
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,C=[...s,h].join("."),x=async(b={})=>{let l;if(d){let T=g?.[C],{result:v,onComplete:E}=await xe({pluginId:o,endpointPath:C,args:b,mode:d.mode,override:d.overrides?.[C],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 $=await Ce(N,o,C,typeof E=="object"&&E!==null?E:{args:E},i);if(T<($.maxRetries||0)){let L=T+1;console.log(`Retrying (${L} / ${$.maxRetries})...`);let _;if($.headersRetryAfterMs)_=$.headersRetryAfterMs;else switch($.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}:${C}] Retry strategy:`,$)}}throw N}},w=a?await a(n,"endpoint"):void 0;if(!m?.before&&!m?.after){let T=await k(0,{...n,key:w},b);return await l?.(),T}let I={...n,key:w},A=m.before?await m.before(I,b):{ctx:I,args:b,continue:!0,passToAfter:void 0};if(A.continue===!1)return;let P=await k(0,A.ctx,A.args);return await m.after?.(A.ctx,P,A.passToAfter),await l?.(),P};r[h]=x}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":return`${R(t.type)}[]`;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;p?._def?.typeName==="ZodObject"?d.push(`${s}${u}: ${j(p,t+1)}`):d.push(`${s}${u}: ${R(f)}`)}return`{
|
|
14
|
+
${d.join(`
|
|
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.toLowerCase()}`)}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.toLowerCase()}`)}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
|
+
${e.join(", ")}`:`${t}:
|
|
19
|
+
`+Object.entries(e).map(([n,r])=>` ${n}: ${r.join(", ")}`).join(`
|
|
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,C]=p,x=se(C),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(x))b.push(` ${l}?: ${k.type} [${k.operators.join(", ")}]`);return b.push("}"),b.join(`
|
|
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(`
|
|
23
|
+
|
|
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
|
+
|
|
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,C;if(n&&o&&p?.authType){let T=m?.[p.authType]?.account??[];C=V({authType:p.authType,integrationName:c.id,tenantId:h,kek:o,database:n,extraAccountFields:T}),a[c.id].keys=C}let x={database:n,db:d[c.id]?.db??{},$getAccountId:u,...c.options?{options:c.options}:{},...C?{keys:C,authType:p?.authType}:{},...r?{tenantId:r}:{}},b=c.endpoints??{},l=c.hooks,k={...i,...c.errorHandlers},w={},I=c.options?.permissions;te({endpoints:b,hooks:l,ctx:x,tree:w,pluginId:c.id,errorHandlers:k,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:I,endpointMeta:c.endpointMeta,database:n,approvalConfig:s,tenantId:r}),Object.keys(w).length>0&&(a[c.id].api=w),x.endpoints=w;let A=c.webhooks??{},P=c.webhookHooks;if(Object.keys(A).length>0){let T={};ue({webhooks:A,hooks:P,ctx:x,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,M 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,6 +1,6 @@
|
|
|
1
|
-
export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair } from './index-
|
|
2
|
-
import { A as AuthTypes,
|
|
3
|
-
export {
|
|
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';
|
|
4
4
|
import { CorsairDatabase } from './db.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import './orm.js';
|
|
@@ -118,4 +118,34 @@ declare function initializeIntegrationDEK(database: CorsairDatabase, integration
|
|
|
118
118
|
*/
|
|
119
119
|
declare function initializeAccountDEK(database: CorsairDatabase, integrationName: string, tenantId: string, kek: string): Promise<string>;
|
|
120
120
|
|
|
121
|
-
|
|
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
|
+
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}from"./chunk-
|
|
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-XBYB3RVJ.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};
|
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";
|
|
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};
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
type ApiRequestOptions = {
|
|
2
|
+
readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
|
|
3
|
+
readonly url: string;
|
|
4
|
+
readonly path?: Record<string, any>;
|
|
5
|
+
readonly cookies?: Record<string, any>;
|
|
6
|
+
readonly headers?: Record<string, any>;
|
|
7
|
+
readonly query?: Record<string, any>;
|
|
8
|
+
readonly formData?: Record<string, any>;
|
|
9
|
+
readonly body?: any;
|
|
10
|
+
readonly mediaType?: string;
|
|
11
|
+
readonly responseHeader?: string;
|
|
12
|
+
readonly errors?: Record<number, string>;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
type ApiResult = {
|
|
16
|
+
readonly url: string;
|
|
17
|
+
readonly ok: boolean;
|
|
18
|
+
readonly status: number;
|
|
19
|
+
readonly statusText: string;
|
|
20
|
+
readonly body: any;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
declare class ApiError extends Error {
|
|
24
|
+
readonly url: string;
|
|
25
|
+
readonly status: number;
|
|
26
|
+
readonly statusText: string;
|
|
27
|
+
readonly body: any;
|
|
28
|
+
readonly request: ApiRequestOptions;
|
|
29
|
+
readonly retryAfter?: number;
|
|
30
|
+
readonly rateLimitReset?: number;
|
|
31
|
+
readonly rateLimitRemaining?: number;
|
|
32
|
+
readonly rateLimitLimit?: number;
|
|
33
|
+
constructor(request: ApiRequestOptions, response: ApiResult, message: string, rateLimitInfo?: {
|
|
34
|
+
retryAfter?: number;
|
|
35
|
+
rateLimitReset?: number;
|
|
36
|
+
rateLimitRemaining?: number;
|
|
37
|
+
rateLimitLimit?: number;
|
|
38
|
+
});
|
|
39
|
+
isRateLimitError(): boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
|
|
43
|
+
type Headers = Record<string, string>;
|
|
44
|
+
type OpenAPIConfig = {
|
|
45
|
+
BASE: string;
|
|
46
|
+
VERSION: string;
|
|
47
|
+
WITH_CREDENTIALS: boolean;
|
|
48
|
+
CREDENTIALS: 'include' | 'omit' | 'same-origin';
|
|
49
|
+
TOKEN?: string | Resolver<string> | undefined;
|
|
50
|
+
USERNAME?: string | Resolver<string> | undefined;
|
|
51
|
+
PASSWORD?: string | Resolver<string> | undefined;
|
|
52
|
+
HEADERS?: Headers | Resolver<Headers> | undefined;
|
|
53
|
+
ENCODE_PATH?: ((path: string) => string) | undefined;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
interface RateLimitConfig {
|
|
57
|
+
enabled: boolean;
|
|
58
|
+
maxRetries: number;
|
|
59
|
+
initialRetryDelay: number;
|
|
60
|
+
backoffMultiplier: number;
|
|
61
|
+
headerNames: {
|
|
62
|
+
retryAfter?: string;
|
|
63
|
+
resetTime?: string;
|
|
64
|
+
remaining?: string;
|
|
65
|
+
limit?: string;
|
|
66
|
+
};
|
|
67
|
+
isRateLimitError?: (status: number, body: any) => boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface OnCancel {
|
|
71
|
+
readonly isResolved: boolean;
|
|
72
|
+
readonly isRejected: boolean;
|
|
73
|
+
readonly isCancelled: boolean;
|
|
74
|
+
(cancelHandler: () => void): void;
|
|
75
|
+
}
|
|
76
|
+
declare class CancelablePromise<T> implements Promise<T> {
|
|
77
|
+
#private;
|
|
78
|
+
constructor(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void, onCancel: OnCancel) => void);
|
|
79
|
+
get [Symbol.toStringTag](): string;
|
|
80
|
+
then<TResult1 = T, TResult2 = never>(onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null, onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
81
|
+
catch<TResult = never>(onRejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null): Promise<T | TResult>;
|
|
82
|
+
finally(onFinally?: (() => void) | null): Promise<T>;
|
|
83
|
+
cancel(): void;
|
|
84
|
+
get isCancelled(): boolean;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface RequestOptions {
|
|
88
|
+
rateLimitConfig?: RateLimitConfig;
|
|
89
|
+
}
|
|
90
|
+
declare const request: <T>(config: OpenAPIConfig, options: ApiRequestOptions, requestOptions?: RequestOptions) => CancelablePromise<T>;
|
|
91
|
+
|
|
92
|
+
type WebhookEventHandler<TEvent = any> = (event: TEvent) => void | Promise<void>;
|
|
93
|
+
interface BaseHandleWebhookResult {
|
|
94
|
+
success: boolean;
|
|
95
|
+
error?: string;
|
|
96
|
+
}
|
|
97
|
+
declare abstract class BaseWebhookHandler<TEventName extends string = string, TEvent = any> {
|
|
98
|
+
protected handlers: Map<TEventName, WebhookEventHandler<TEvent>[]>;
|
|
99
|
+
on(eventName: TEventName, handler: WebhookEventHandler<TEvent>): this;
|
|
100
|
+
off(eventName: TEventName, handler: WebhookEventHandler<TEvent>): this;
|
|
101
|
+
getRegisteredEvents(): TEventName[];
|
|
102
|
+
hasHandlers(eventName: TEventName): boolean;
|
|
103
|
+
clearHandlers(eventName?: TEventName): this;
|
|
104
|
+
protected executeHandlers(eventName: TEventName, event: TEvent): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
declare function verifyHmacSignature(payload: string | Buffer, secret: string, signature: string, algorithm?: 'sha256' | 'sha1'): boolean;
|
|
108
|
+
declare function verifyHmacSignatureWithPrefix(payload: string | Buffer, secret: string, signature: string, prefix: string, algorithm?: 'sha256' | 'sha1'): boolean;
|
|
109
|
+
declare function verifyHmacSha256Signature(payload: string, secret: string, timestamp: string, signature: string, maxAgeSeconds?: number): boolean;
|
|
110
|
+
declare function verifySlackSignature(payload: string, secret: string, timestamp: string, signature: string, maxAgeSeconds?: number): boolean;
|
|
111
|
+
|
|
112
|
+
export { ApiError, type ApiRequestOptions, type ApiResult, type BaseHandleWebhookResult, BaseWebhookHandler, type OpenAPIConfig, type RateLimitConfig, type WebhookEventHandler, request, verifyHmacSha256Signature, verifyHmacSignature, verifyHmacSignatureWithPrefix, verifySlackSignature };
|
package/dist/http.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=class extends Error{url;status;statusText;body;request;retryAfter;rateLimitReset;rateLimitRemaining;rateLimitLimit;constructor(e,i,n,r){super(n),this.name="ApiError",this.url=i.url,this.status=i.status,this.statusText=i.statusText,this.body=i.body,this.request=e,this.retryAfter=r?.retryAfter,this.rateLimitReset=r?.rateLimitReset,this.rateLimitRemaining=r?.rateLimitRemaining,this.rateLimitLimit=r?.rateLimitLimit}isRateLimitError(){return this.status===429}};var g=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},p=class{#t;#r;#e;#i;#s;#a;#n;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#i=[],this.#s=new Promise((i,n)=>{this.#a=i,this.#n=n;let r=o=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#a&&this.#a(o))},a=o=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#n&&this.#n(o))},s=o=>{this.#t||this.#r||this.#e||this.#i.push(o)};return Object.defineProperty(s,"isResolved",{get:()=>this.#t}),Object.defineProperty(s,"isRejected",{get:()=>this.#r}),Object.defineProperty(s,"isCancelled",{get:()=>this.#e}),e(r,a,s)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,i){return this.#s.then(e,i)}catch(e){return this.#s.catch(e)}finally(e){return this.#s.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#i.length)try{for(let e of this.#i)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#i.length=0,this.#n&&this.#n(new g("Request aborted"))}}get isCancelled(){return this.#e}};var O={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 S(t,e){let i={};if(e.headerNames.retryAfter){let n=t.headers.get(e.headerNames.retryAfter);if(n){let r=parseInt(n,10);isNaN(r)||(i.retryAfter=r*1e3)}}if(e.headerNames.resetTime){let n=t.headers.get(e.headerNames.resetTime);if(n){let r=parseInt(n,10);if(!isNaN(r)){let a=Date.now(),s=r>1e12?r:r*1e3;i.rateLimitReset=s,s>a&&(i.retryAfter=s-a)}}}if(e.headerNames.remaining){let n=t.headers.get(e.headerNames.remaining);if(n){let r=parseInt(n,10);isNaN(r)||(i.rateLimitRemaining=r)}}if(e.headerNames.limit){let n=t.headers.get(e.headerNames.limit);if(n){let r=parseInt(n,10);isNaN(r)||(i.rateLimitLimit=r)}}return i}function C(t,e,i){return i.enabled?t===429?!0:i.isRateLimitError?i.isRateLimitError(t,e):!1:!1}function R(t,e,i){if(e.retryAfter)return e.retryAfter;let n=i.initialRetryDelay*Math.pow(i.backoffMultiplier,t-1);return Math.min(n,6e4)}async function T(t){return new Promise(e=>setTimeout(e,t))}var x=t=>t!=null,d=t=>typeof t=="string",A=t=>d(t)&&t!=="",L=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]),N=t=>t instanceof FormData,j=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},k=t=>{let e=[],i=(r,a)=>{e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(a))}`)},n=(r,a)=>{x(a)&&(Array.isArray(a)?a.forEach(s=>{n(r,s)}):typeof a=="object"?Object.entries(a).forEach(([s,o])=>{n(`${r}[${s}]`,o)}):i(r,a))};return Object.entries(t).forEach(([r,a])=>{n(r,a)}),e.length>0?`?${e.join("&")}`:""},$=(t,e)=>{let i=t.ENCODE_PATH||encodeURI,n=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(o,u)=>e.path?.hasOwnProperty(u)?i(String(e.path[u])):o),r=t.BASE.endsWith("/")?t.BASE.slice(0,-1):t.BASE,a=n.startsWith("/")?n.slice(1):n,s=`${r}/${a}`;return e.query?`${s}${k(e.query)}`:s},W=t=>{if(t.formData){let e=new FormData,i=(n,r)=>{d(r)||L(r)?e.append(n,r):e.append(n,JSON.stringify(r))};return Object.entries(t.formData).filter(([n,r])=>x(r)).forEach(([n,r])=>{Array.isArray(r)?r.forEach(a=>i(n,a)):i(n,r)}),e}},h=async(t,e)=>typeof e=="function"?e(t):e,F=async(t,e)=>{let[i,n,r,a]=await Promise.all([h(e,t.TOKEN),h(e,t.USERNAME),h(e,t.PASSWORD),h(e,t.HEADERS)]),s=Object.entries({Accept:"application/json",...a,...e.headers}).filter(([o,u])=>x(u)).reduce((o,[u,l])=>({...o,[u]:String(l)}),{});if(A(i)&&(s.Authorization=`Bearer ${i}`),A(n)&&A(r)){let o=j(`${n}:${r}`);s.Authorization=`Basic ${o}`}return e.body!==void 0&&(e.mediaType?s["Content-Type"]=e.mediaType:L(e.body)?s["Content-Type"]=e.body.type||"application/octet-stream":d(e.body)?s["Content-Type"]="text/plain":N(e.body)||(s["Content-Type"]="application/json")),new Headers(s)},M=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):d(t.body)||L(t.body)||N(t.body)?t.body:JSON.stringify(t.body)},U=async(t,e,i,n,r,a,s)=>{let o=new AbortController,u={headers:a,body:n??r,method:e.method,signal:o.signal};return t.WITH_CREDENTIALS&&(u.credentials=t.CREDENTIALS),s(()=>o.abort()),await fetch(i,u)},_=(t,e)=>{if(e){let i=t.headers.get(e);if(d(i))return i}},J=async t=>{if(t.status!==204)try{let e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(r=>e.toLowerCase().startsWith(r))?await t.json():await t.text()}catch(e){console.error(e)}},P=(t,e,i)=>{let r={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(r)throw new c(t,e,r,i);if(!e.ok){let a=e.status??"unknown",s=e.statusText??"unknown",o=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})(),u=e.body?.message||e.body?.error||e.body?.detail||`Generic Error: status: ${a}; status text: ${s}; body: ${o}`;throw new c(t,e,u,i)}},G=(t,e,i)=>{let n=i?.rateLimitConfig||O;return new p(async(r,a,s)=>{let o=0,u=n.maxRetries+1;for(;o<u;){o++;try{let l=$(t,e),b=W(e),w=M(e),H=await F(t,e);if(s.isCancelled)return;let m=await U(t,e,l,w,b,H,s),I=await J(m),B=_(m,e.responseHeader),y={url:l,ok:m.ok,status:m.status,statusText:m.statusText,body:B??I};if(n.enabled&&C(m.status,y.body,n)){let v=S(m,n);if(o<u){let D=R(o,v,n);await T(D);continue}P(e,y,v)}P(e,y),r(y.body);return}catch(l){if(l instanceof c&&l.isRateLimitError()&&o<u){let b=l.retryAfter?l.retryAfter:R(o,{retryAfter:l.retryAfter,rateLimitReset:l.rateLimitReset},n);await T(b);continue}if(o>=u){a(l);return}if(l instanceof c&&l.isRateLimitError())continue;a(l);return}}})};var E=class{handlers=new Map;on(e,i){let n=this.handlers.get(e)||[];return n.push(i),this.handlers.set(e,n),this}off(e,i){let n=this.handlers.get(e)||[],r=n.indexOf(i);return r!==-1&&(n.splice(r,1),this.handlers.set(e,n)),this}getRegisteredEvents(){return Array.from(this.handlers.keys())}hasHandlers(e){let i=this.handlers.get(e);return!!i&&i.length>0}clearHandlers(e){return e?this.handlers.delete(e):this.handlers.clear(),this}async executeHandlers(e,i){let n=this.handlers.get(e)||[];for(let r of n)await r(i)}};import*as f from"crypto";function z(t,e,i,n="sha256"){if(!i||!e)return!1;let r=f.createHmac(n,e).update(t).digest("hex");try{return f.timingSafeEqual(Buffer.from(i),Buffer.from(r))}catch{return!1}}function V(t,e,i,n,r="sha256"){if(!i||!e||!i.startsWith(n))return!1;let a=i.slice(n.length),s=f.createHmac(r,e).update(t).digest("hex");try{return f.timingSafeEqual(Buffer.from(a),Buffer.from(s))}catch{return!1}}function q(t,e,i,n,r=300){if(!e)return!0;if(!n||!i)return!1;let a=Math.floor(Date.now()/1e3),s=parseInt(i,10);if(Math.abs(a-s)>r)return!1;let o=`v0:${i}:${t}`,u="v0="+f.createHmac("sha256",e).update(o).digest("hex");try{return f.timingSafeEqual(Buffer.from(n),Buffer.from(u))}catch{return!1}}function K(t,e,i,n,r=300){return q(t,e,i,n,r)}export{c as ApiError,E as BaseWebhookHandler,G as request,q as verifyHmacSha256Signature,z as verifyHmacSignature,V as verifyHmacSignatureWithPrefix,K as verifySlackSignature};
|
|
@@ -917,71 +917,15 @@ type CorsairIntegration<Plugins extends readonly CorsairPlugin[]> = {
|
|
|
917
917
|
};
|
|
918
918
|
};
|
|
919
919
|
|
|
920
|
-
|
|
920
|
+
/** @deprecated get_schema now returns a plain string. This type is kept for backwards compatibility. */
|
|
921
921
|
type EndpointSchemaResult = {
|
|
922
|
-
/** Human-readable description of what this endpoint does. */
|
|
923
922
|
description?: string;
|
|
924
|
-
/** Risk classification: 'read' | 'write' | 'destructive' */
|
|
925
923
|
riskLevel?: 'read' | 'write' | 'destructive';
|
|
926
|
-
/** Whether this action cannot be undone. */
|
|
927
924
|
irreversible?: boolean;
|
|
928
|
-
/** JSON Schema representation of the input arguments object. */
|
|
929
925
|
input?: unknown;
|
|
930
|
-
/** JSON Schema representation of the response object. */
|
|
931
926
|
output?: unknown;
|
|
932
|
-
/**
|
|
933
|
-
* Present when the requested method was not found.
|
|
934
|
-
* Lists all available full-form paths so the caller can pick a valid one.
|
|
935
|
-
*/
|
|
936
927
|
availableMethods?: Record<string, string[]>;
|
|
937
928
|
};
|
|
938
|
-
type WebhookSchemaResult = {
|
|
939
|
-
/** Human-readable description of what triggers this webhook. */
|
|
940
|
-
description?: string;
|
|
941
|
-
/** JSON Schema for the webhook payload — the type of `request.payload` in the before hook. */
|
|
942
|
-
payload?: unknown;
|
|
943
|
-
/** JSON Schema for the webhook response data — the type of `response.data` in the after hook. */
|
|
944
|
-
response?: unknown;
|
|
945
|
-
/**
|
|
946
|
-
* Ready-to-copy code example showing exactly how to configure this webhook,
|
|
947
|
-
* including response.data type as an inline comment.
|
|
948
|
-
*/
|
|
949
|
-
usage?: string;
|
|
950
|
-
/**
|
|
951
|
-
* Present when the requested webhook path was not found.
|
|
952
|
-
* Lists all available webhook dot-paths per plugin so the caller can self-correct.
|
|
953
|
-
*/
|
|
954
|
-
availableWebhooks?: Record<string, string[]>;
|
|
955
|
-
};
|
|
956
|
-
type DbSearchSchemaResult = {
|
|
957
|
-
/**
|
|
958
|
-
* What this entity type represents and how to search it.
|
|
959
|
-
* Pass `limit` and `offset` as numbers for pagination.
|
|
960
|
-
*/
|
|
961
|
-
description: string;
|
|
962
|
-
/**
|
|
963
|
-
* Filterable fields for the search() call.
|
|
964
|
-
* All active filters are AND-combined. Omit a field to skip filtering on it.
|
|
965
|
-
*
|
|
966
|
-
* Each operator shorthand: passing a raw value (string/number/boolean/Date) is
|
|
967
|
-
* equivalent to `{ equals: value }`.
|
|
968
|
-
*/
|
|
969
|
-
filters: {
|
|
970
|
-
/** Filter by the entity's external platform ID (e.g. a Slack channel ID). */
|
|
971
|
-
entity_id: {
|
|
972
|
-
type: 'string';
|
|
973
|
-
operators: string[];
|
|
974
|
-
};
|
|
975
|
-
/**
|
|
976
|
-
* Filter by fields inside the entity's data payload.
|
|
977
|
-
* Only flat primitive fields are listed — nested objects are not filterable.
|
|
978
|
-
*/
|
|
979
|
-
data: Record<string, {
|
|
980
|
-
type: DbFieldType;
|
|
981
|
-
operators: string[];
|
|
982
|
-
}>;
|
|
983
|
-
};
|
|
984
|
-
};
|
|
985
929
|
type ListOperationsOptions = {
|
|
986
930
|
/**
|
|
987
931
|
* Filter to a specific plugin by its ID (e.g. 'slack', 'github').
|
|
@@ -1033,29 +977,23 @@ type CorsairInspectMethods = {
|
|
|
1033
977
|
*/
|
|
1034
978
|
list_operations(options?: ListOperationsOptions): Record<string, string[]> | string[] | string;
|
|
1035
979
|
/**
|
|
1036
|
-
* Returns
|
|
980
|
+
* Returns a plain-text TypeScript-style type declaration for a specific operation path.
|
|
1037
981
|
* The path format determines which kind of schema is returned:
|
|
1038
|
-
* - API path (`plugin.api.group.method`) →
|
|
1039
|
-
* - Webhook path (`plugin.webhooks.group.event`) →
|
|
1040
|
-
* - DB path (`plugin.db.entityType.search`) →
|
|
982
|
+
* - API path (`plugin.api.group.method`) → description, risk level, input/output types
|
|
983
|
+
* - Webhook path (`plugin.webhooks.group.event`) → description, payload/response types, usage snippet
|
|
984
|
+
* - DB path (`plugin.db.entityType.search`) → description, filterable fields with operators
|
|
1041
985
|
*
|
|
1042
986
|
* Casing is ignored — the path is lowercased before lookup.
|
|
1043
|
-
* If the path is not found, returns
|
|
987
|
+
* If the path is not found, returns a list of available paths for self-correction.
|
|
1044
988
|
*
|
|
1045
989
|
* @example
|
|
1046
|
-
* corsair.get_schema('slack.api.
|
|
1047
|
-
* //
|
|
1048
|
-
*
|
|
1049
|
-
* corsair.get_schema('slack.webhooks.messages.message')
|
|
1050
|
-
* // { description: '...', usage: '...', payload: { ... }, response: { ... } }
|
|
1051
|
-
*
|
|
1052
|
-
* corsair.get_schema('slack.db.messages.search')
|
|
1053
|
-
* // { description: '...', filters: { entity_id: { ... }, data: { text: { type: 'string', operators: [...] }, ... } } }
|
|
990
|
+
* corsair.get_schema('slack.api.messages.post')
|
|
991
|
+
* // "Post a message to a channel [write]\n\ninput {\n channel: string\n text?: string\n ..."
|
|
1054
992
|
*
|
|
1055
993
|
* corsair.get_schema('slack.api.invalid')
|
|
1056
|
-
* //
|
|
994
|
+
* // "Path not found. Available operations:\n slack: slack.api.channels.list, ..."
|
|
1057
995
|
*/
|
|
1058
|
-
get_schema(path: string):
|
|
996
|
+
get_schema(path: string): string;
|
|
1059
997
|
};
|
|
1060
998
|
|
|
1061
999
|
/**
|
|
@@ -1230,4 +1168,4 @@ type CorsairSingleTenantClient<Plugins extends readonly CorsairPlugin[]> = Corsa
|
|
|
1230
1168
|
permissions: CorsairPermissionsNamespace;
|
|
1231
1169
|
};
|
|
1232
1170
|
|
|
1233
|
-
export { type
|
|
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 };
|
|
@@ -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-
|
|
2
|
+
import { C as CorsairPlugin, a as CorsairIntegration, b as CorsairTenantWrapper, c as CorsairSingleTenantClient } from './index-D_Ah5Tz6.js';
|
|
3
3
|
|
|
4
4
|
declare const CORSAIR_INTERNAL: unique symbol;
|
|
5
5
|
type CorsairInternalConfig = {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { c as createCorsair } from './index-
|
|
2
|
-
import {
|
|
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';
|
|
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-
|
|
1
|
+
import{a as W}from"./chunk-VPU5CT64.js";import{n as k,r as x}from"./chunk-XBYB3RVJ.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};
|
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-
|
|
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};
|
package/dist/setup.d.ts
CHANGED
package/dist/setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-VPU5CT64.js";import"./chunk-XBYB3RVJ.js";import"./chunk-7IH5DNUL.js";import"./chunk-2PB34FTK.js";import"./chunk-HO245J34.js";import"./chunk-73HYPGOI.js";export{o as setupCorsair};
|