corsair 0.1.46 → 0.1.48

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.
Files changed (99) hide show
  1. package/dist/chunk-2PB34FTK.js +1 -0
  2. package/dist/{chunk-B7SHIP45.js → chunk-34QKYT53.js} +1 -1
  3. package/dist/chunk-5XRKMGCV.js +15 -0
  4. package/dist/chunk-7IH5DNUL.js +1 -0
  5. package/dist/core.d.ts +34 -4
  6. package/dist/core.js +1 -1
  7. package/dist/db.js +1 -1
  8. package/dist/http.d.ts +112 -0
  9. package/dist/http.js +1 -0
  10. package/dist/{index-D30v9sPr.d.ts → index-CNwyqNCs.d.ts} +1 -1
  11. package/dist/{index-CBFNJJDR.d.ts → index-mtAgyrsC.d.ts} +1 -1
  12. package/dist/index.d.ts +2 -2
  13. package/dist/index.js +1 -1
  14. package/dist/orm.js +1 -1
  15. package/dist/setup.d.ts +1 -1
  16. package/dist/setup.js +1 -1
  17. package/package.json +5 -200
  18. package/dist/chunk-34Z5IBIX.js +0 -1
  19. package/dist/chunk-3KXTFATC.js +0 -1
  20. package/dist/chunk-476ZUILE.js +0 -1
  21. package/dist/chunk-A7CRE5AE.js +0 -1
  22. package/dist/chunk-BYXBJQAS.js +0 -0
  23. package/dist/chunk-BZ3WPT6I.js +0 -1
  24. package/dist/chunk-J7NCVPA4.js +0 -15
  25. package/dist/chunk-Q55TIVXA.js +0 -1
  26. package/dist/plugins/airtable/index.d.ts +0 -2815
  27. package/dist/plugins/airtable/index.js +0 -1
  28. package/dist/plugins/amplitude/index.d.ts +0 -3207
  29. package/dist/plugins/amplitude/index.js +0 -1
  30. package/dist/plugins/asana/index.d.ts +0 -25950
  31. package/dist/plugins/asana/index.js +0 -1
  32. package/dist/plugins/box/index.d.ts +0 -15342
  33. package/dist/plugins/box/index.js +0 -1
  34. package/dist/plugins/cal/index.d.ts +0 -10751
  35. package/dist/plugins/cal/index.js +0 -1
  36. package/dist/plugins/calendly/index.d.ts +0 -14276
  37. package/dist/plugins/calendly/index.js +0 -1
  38. package/dist/plugins/discord/index.d.ts +0 -11225
  39. package/dist/plugins/discord/index.js +0 -1
  40. package/dist/plugins/dropbox/index.d.ts +0 -8196
  41. package/dist/plugins/dropbox/index.js +0 -1
  42. package/dist/plugins/exa/index.d.ts +0 -3556
  43. package/dist/plugins/exa/index.js +0 -1
  44. package/dist/plugins/fireflies/index.d.ts +0 -4576
  45. package/dist/plugins/fireflies/index.js +0 -115
  46. package/dist/plugins/github/index.d.ts +0 -28386
  47. package/dist/plugins/github/index.js +0 -1
  48. package/dist/plugins/gmail/index.d.ts +0 -2838
  49. package/dist/plugins/gmail/index.js +0 -1
  50. package/dist/plugins/googlecalendar/index.d.ts +0 -5411
  51. package/dist/plugins/googlecalendar/index.js +0 -1
  52. package/dist/plugins/googledrive/index.d.ts +0 -4136
  53. package/dist/plugins/googledrive/index.js +0 -1
  54. package/dist/plugins/googlesheets/index.d.ts +0 -1403
  55. package/dist/plugins/googlesheets/index.js +0 -1
  56. package/dist/plugins/hackernews/index.d.ts +0 -3076
  57. package/dist/plugins/hackernews/index.js +0 -1
  58. package/dist/plugins/hubspot/index.d.ts +0 -15924
  59. package/dist/plugins/hubspot/index.js +0 -1
  60. package/dist/plugins/intercom/index.d.ts +0 -10754
  61. package/dist/plugins/intercom/index.js +0 -1
  62. package/dist/plugins/jira/index.d.ts +0 -6961
  63. package/dist/plugins/jira/index.js +0 -1
  64. package/dist/plugins/linear/index.d.ts +0 -17670
  65. package/dist/plugins/linear/index.js +0 -548
  66. package/dist/plugins/monday/index.d.ts +0 -14151
  67. package/dist/plugins/monday/index.js +0 -235
  68. package/dist/plugins/notion/index.d.ts +0 -2460
  69. package/dist/plugins/notion/index.js +0 -1
  70. package/dist/plugins/oura/index.d.ts +0 -1545
  71. package/dist/plugins/oura/index.js +0 -1
  72. package/dist/plugins/pagerduty/index.d.ts +0 -7863
  73. package/dist/plugins/pagerduty/index.js +0 -1
  74. package/dist/plugins/posthog/index.d.ts +0 -505
  75. package/dist/plugins/posthog/index.js +0 -1
  76. package/dist/plugins/resend/index.d.ts +0 -1995
  77. package/dist/plugins/resend/index.js +0 -1
  78. package/dist/plugins/sentry/index.d.ts +0 -7322
  79. package/dist/plugins/sentry/index.js +0 -1
  80. package/dist/plugins/slack/index.d.ts +0 -38957
  81. package/dist/plugins/slack/index.js +0 -1
  82. package/dist/plugins/spotify/index.d.ts +0 -13310
  83. package/dist/plugins/spotify/index.js +0 -1
  84. package/dist/plugins/stripe/index.d.ts +0 -6207
  85. package/dist/plugins/stripe/index.js +0 -1
  86. package/dist/plugins/tavily/index.d.ts +0 -352
  87. package/dist/plugins/tavily/index.js +0 -1
  88. package/dist/plugins/telegram/index.d.ts +0 -6103
  89. package/dist/plugins/telegram/index.js +0 -1
  90. package/dist/plugins/todoist/index.d.ts +0 -3562
  91. package/dist/plugins/todoist/index.js +0 -1
  92. package/dist/plugins/trello/index.d.ts +0 -9175
  93. package/dist/plugins/trello/index.js +0 -1
  94. package/dist/plugins/twitter/index.d.ts +0 -267
  95. package/dist/plugins/twitter/index.js +0 -1
  96. package/dist/plugins/twitterapiio/index.d.ts +0 -19242
  97. package/dist/plugins/twitterapiio/index.js +0 -1
  98. package/dist/plugins/zoom/index.d.ts +0 -8382
  99. 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};
@@ -1,4 +1,4 @@
1
- import{o as k,p as w}from"./chunk-J7NCVPA4.js";import{a as m}from"./chunk-34Z5IBIX.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-5XRKMGCV.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,15 @@
1
+ import{a as le,b as Y}from"./chunk-2PB34FTK.js";import{a as ue}from"./chunk-73HYPGOI.js";import{createCipheriv as ge,createDecipheriv as pe,randomBytes as j,scrypt as ve}from"crypto";import{promisify as De}from"util";var fe=De(ve),H="aes-256-gcm",ye=12,U=16,Ke=16,N=32;function K(){return j(N).toString("base64")}async function O(e,t){let n=j(Ke),o=await fe(t,n,N),r=j(ye),i=ge(H,o,r,{authTagLength:U}),s=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[n.toString("base64"),r.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function D(e,t){let[n,o,r,i]=e.split(":");if(!n||!o||!r||!i)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(n,"base64"),a=Buffer.from(o,"base64"),d=Buffer.from(r,"base64"),g=Buffer.from(i,"base64"),y=await fe(t,s,N),c=pe(H,y,a,{authTagLength:U});return c.setAuthTag(d),Buffer.concat([c.update(g),c.final()]).toString("utf8")}function Q(e,t){let n=Buffer.from(t,"base64"),o=j(ye),r=ge(H,n,o,{authTagLength:U}),i=Buffer.concat([r.update(e,"utf8"),r.final()]),s=r.getAuthTag();return[o.toString("base64"),s.toString("base64"),i.toString("base64")].join(":")}function X(e,t){let[n,o,r]=e.split(":");if(!n||!o||!r)throw new Error("Invalid encrypted data format");let i=Buffer.from(t,"base64"),s=Buffer.from(n,"base64"),a=Buffer.from(o,"base64"),d=Buffer.from(r,"base64"),g=pe(H,i,s,{authTagLength:U});return g.setAuthTag(a),Buffer.concat([g.update(d),g.final()]).toString("utf8")}function S(e,t){let n={};for(let[o,r]of Object.entries(e))n[o]=Q(r,t);return n}function M(e,t){let n={};for(let[o,r]of Object.entries(e))n[o]=X(r,t);return n}function $(e,t,n){let o=M(e,t);return S(o,n)}function q(e,t){let n=[];e||n.push("database"),t||n.push("kek");let o={};return new Proxy(o,{get(r,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 ${N}`)}})}var W={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 he(e,t,n){let o={};for(let r of n)o[`get_${r}`]=async()=>(await e())[r]??null,o[`set_${r}`]=async i=>{let s=[null,void 0,""].includes(i)?null:i;await t({[r]:s})};return o}var ee=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};function z(e){let{authType:t,integrationName:n,kek:o,database:r,extraIntegrationFields:i=[]}=e,s=[...W[t].integration,...i],a=null,d={kek:o,integrationName:n,getIntegration:async()=>{if(a)return a;let u=await r.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:ee(u.config),dek:u.dek??null},a},updateIntegration:async u=>{let f=await d.getIntegration();await r.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","=",f.id).execute(),a=null}},g=null,y=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,o),g},c=async()=>{let u=await d.getIntegration(),f=await y(),h=u.config;return!h||Object.keys(h).length===0?{}:M(h,f)};return{get_dek:y,issue_new_dek:async()=>{let u=await d.getIntegration(),f=K(),h={};if(u.dek){let E=await D(u.dek,o),T=u.config;T&&Object.keys(T).length>0&&(h=$(T,E,f))}let w=await O(f,o);return await d.updateIntegration({config:h,dek:w}),g=f,f},...he(c,async u=>{let f=await y(),h;try{h=await c()}catch(T){console.error(`[corsair] Failed to decrypt config for integration "${n}", starting fresh:`,T),h={}}let w={...h};for(let[T,l]of Object.entries(u))l===null?delete w[T]:w[T]=l;let E=S(w,f);await d.updateIntegration({config:E})},s)}}function G(e){let{authType:t,integrationName:n,tenantId:o,kek:r,database:i,extraAccountFields:s=[]}=e,a=[...W[t].account,...s],d=null,g=null,y=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:ee(l.config),dek:l.dek??null},g},c={kek:r,integrationName:n,tenantId:o,getIntegration:y,getAccount:async()=>{if(d)return d;let l=await y(),k=await i.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",o).where("integration_id","=",l.id).executeTakeFirst();if(!k)throw new Error(`Account not found for tenant "${o}" and integration "${n}". Make sure to create the account first.`);return d={id:k.id,config:ee(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}},m=null,p=null,u=async()=>{if(m)return m;let l=await c.getAccount();if(!l.dek)throw new Error(`No DEK found for account (tenant: "${o}", integration: "${n}"). Initialize the account first.`);return m=await D(l.dek,r),m},f=async()=>{if(p)return p;let l=await c.getIntegration();if(!l.dek)throw new Error(`No DEK found for integration "${n}". Initialize the integration first.`);return p=await D(l.dek,r),p},h=async()=>{let l=await c.getAccount(),k=await u(),b=l.config;return!b||Object.keys(b).length===0?{}:M(b,k)},w=async()=>{let l=await c.getIntegration(),k=await f(),b=l.config;return!b||Object.keys(b).length===0?{}:M(b,k)},T={get_dek:u,issue_new_dek:async()=>{let l=await c.getAccount(),k=K(),b={};if(l.dek){let A=await D(l.dek,r),P=l.config;P&&Object.keys(P).length>0&&(b=$(P,A,k))}let I=await O(k,r);return await c.updateAccount({config:b,dek:I}),m=k,k},...he(h,async l=>{let k=await u(),b;try{b=await h()}catch(P){console.error(`[corsair] Failed to decrypt config for account (tenant: "${o}", integration: "${n}"), starting fresh:`,P),b={}}let I={...b};for(let[P,C]of Object.entries(l))C===null?delete I[P]:I[P]=C;let A=S(I,k);await c.updateAccount({config:A})},a)};return t==="oauth_2"&&(T.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}}),T}async function me(e,t,n){let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!o)throw new Error(`Integration "${t}" not found.`);let r=K(),i=await O(r,n);return await e.db.updateTable("corsair_integrations").set({dek:i,updated_at:new Date}).where("id","=",o.id).execute(),r}async function ke(e,t,n,o){let r=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!r)throw new Error(`Integration "${t}" not found.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n).where("integration_id","=",r.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${n}" and integration "${t}".`);let s=K(),a=await O(s,o);return await e.db.updateTable("corsair_accounts").set({dek:a,updated_at:new Date}).where("id","=",i.id).execute(),s}var Oe=async(e,t)=>(console.error(`[corsair:${t.pluginId}:${t.operation}]`,{error:e.message,input:t.input}),{maxRetries:0});async function be(e,t,n,o,r){let i={pluginId:t,operation:n,input:o,originalError:e},s=Object.keys(r).find(g=>r[g]?.match(e,i));return await(r[s||"DEFAULT"]?.handler||Oe)(e,i)}import{randomBytes as Me}from"crypto";import{v4 as Fe}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 Be(e,t,n){return n!==void 0?n:Se[t][e]}function we(e){let t=/(\d+)(d|h|m|s)/g,n=0,o;for(;(o=t.exec(e))!==null;){let r=parseInt(o[1],10);switch(o[2]){case"d":n+=r*864e5;break;case"h":n+=r*36e5;break;case"m":n+=r*6e4;break;case"s":n+=r*1e3;break}}return n>0?n:600*1e3}function Ce(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 Te(e){let t=Be(e.riskLevel,e.mode,e.override);if(t==="allow")return{result:"allow"};let n=e.meta?.irreversible?" (irreversible)":"",o=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: ${o}`,`
5
+ To allow this, update the permission mode or add an override in your corsair config.`),{result:"blocked"};let r=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","=",r).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 m=e.db,p=a.id;return{result:"allow",onComplete:async()=>{await m.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",p).execute()}}}return a.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
6
+ Action: ${o}`,`
7
+ Permission ID: ${a.id}`,`
8
+ Use the token to approve or deny this request.`),{result:"blocked"})}let d=Fe(),g=Me(32).toString("hex"),y=e.timeoutMs??600*1e3,c=new Date(Date.now()+y).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:r,tenant_id:s,status:"pending",expires_at:c}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
9
+ Action: ${o}`,`
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 Ne(e){return typeof e=="function"}function ne({endpoints:e,hooks:t,ctx:n,tree:o,pluginId:r,errorHandlers:i,currentPath:s=[],keyBuilder:a,permissionsConfig:d,endpointMeta:g,database:y,approvalConfig:c,tenantId:m}){for(let[p,u]of Object.entries(e)){let f=t?.[p];if(Ne(u)){let h=f,w=[...s,p].join("."),E=async(T={})=>{let l;if(d){let C=g?.[w],{result:v,onComplete:R}=await Te({pluginId:r,endpointPath:w,args:T,mode:d.mode,override:d.overrides?.[w],riskLevel:C?.riskLevel??"write",meta:C,db:y,timeoutMs:c?we(c.timeout):void 0,tenantId:m});if(v==="blocked")return null;l=R}let k=async(C,v,R)=>{try{return await u(v,R)}catch(B){if(B instanceof Error){let F=await be(B,r,w,typeof R=="object"&&R!==null?R:{args:R},i);if(C<(F.maxRetries||0)){let L=C+1;console.log(`Retrying (${L} / ${F.maxRetries})...`);let _;if(F.headersRetryAfterMs)_=F.headersRetryAfterMs;else switch(F.retryStrategy){case"exponential_backoff":_=Math.pow(2,L-1)*1e3;break;case"exponential_backoff_jitter":let V=Math.pow(2,L-1)*1e3,_e=(Math.random()-.5)*1e3;_=Math.max(0,V+_e);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(V=>setTimeout(V,_)),await k(L,v,R),console.log(`[corsair:${r}:${w}] Retry strategy:`,F)}}throw B}},b=a?await a(n,"endpoint"):void 0;if(!h?.before&&!h?.after){let C=await k(0,{...n,key:b},T);return await l?.(),C}let I={...n,key:b},A=h.before?await h.before(I,T):{ctx:I,args:T,continue:!0,passToAfter:void 0};if(A.continue===!1)return;let P=await k(0,A.ctx,A.args);return await h.after?.(A.ctx,P,A.passToAfter),await l?.(),P};o[p]=E}else if(u&&typeof u=="object"){let h={};ne({endpoints:u,hooks:f,ctx:n,tree:h,pluginId:r,errorHandlers:i,currentPath:[...s,p],keyBuilder:a,permissionsConfig:d,endpointMeta:g,database:y,approvalConfig:c,tenantId:m}),o[p]=h}}}var Pe=["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"];function x(e){let t=e._def,n=t.typeName;switch(n){case"ZodString":return{type:"string"};case"ZodNumber":return{type:"number"};case"ZodBoolean":return{type:"boolean"};case"ZodNull":return{type:"null"};case"ZodUnknown":case"ZodAny":return{};case"ZodLiteral":return{const:t.value};case"ZodEnum":return{enum:t.values};case"ZodOptional":return x(t.innerType);case"ZodNullable":return{anyOf:[x(t.innerType),{type:"null"}]};case"ZodArray":return{type:"array",items:x(t.type)};case"ZodRecord":return{type:"object",additionalProperties:x(t.valueType)};case"ZodObject":{let o=t.shape(),r={},i=[];for(let[a,d]of Object.entries(o)){r[a]=x(d);let g=d._def.typeName;g!=="ZodOptional"&&g!=="ZodNullable"&&i.push(a)}let s={type:"object",properties:r};return i.length>0&&(s.required=i),s}case"ZodUnion":return{anyOf:t.options.map(x)};case"ZodIntersection":return{allOf:[x(t.left),x(t.right)]};case"ZodEffects":return x(t.schema);default:return{type:(n??"unknown").replace("Zod","").toLowerCase()}}}var xe=["equals","contains","startsWith","endsWith","in"],$e=["equals","gt","gte","lt","lte","in"],We=["equals"],Ze=["equals","before","after","between"];function re(e){let t=e._def;switch(t.typeName){case"ZodOptional":case"ZodNullable":case"ZodDefault":return re(t.innerType);case"ZodEffects":return re(t.schema);case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function oe(e){let t=e._def,n=t.typeName;if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")return oe(t.innerType);if(n==="ZodEffects")return oe(t.schema);if(n!=="ZodObject")return{};let o=t.shape(),r={};for(let[i,s]of Object.entries(o)){let a=re(s);a==="string"?r[i]={type:"string",operators:xe}:a==="number"?r[i]={type:"number",operators:$e}:a==="boolean"?r[i]={type:"boolean",operators:We}:a==="date"&&(r[i]={type:"date",operators:Ze})}return r}function Le(e,t){for(let[n,o]of Object.entries(e))if(n.toLowerCase()===t)return[n,o]}function ie(e,t,n){for(let[o,r]of Object.entries(e)){let i=[...t,o];typeof r=="function"?n.push(i.join(".")):r!==null&&typeof r=="object"&&ie(r,i,n)}}function se(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function ae(e,t,n){for(let[o,r]of Object.entries(e)){let i=[...t,o];se(r)?n.push(i.join(".")):r!==null&&typeof r=="object"&&ae(r,i,n)}}function Ae(e,t){if(t.length===0)return null;let[n,...o]=t,r=Object.entries(e).find(([a])=>a.toLowerCase()===n);if(!r)return null;let[i,s]=r;if(o.length===0)return se(s)?[i]:null;if(s!==null&&typeof s=="object"&&!se(s)){let a=Ae(s,o);if(a!==null)return[i,...a]}return null}function je(e,t,n){let o=[];o.push(`${e}({`),o.push(" webhookHooks: {");for(let s=0;s<t.length;s++){let a=" ".repeat(s+2);o.push(`${a}${t[s]}: {`)}let r=" ".repeat(t.length+2),i=r+" ";if(o.push(`${r}before(ctx, args) {`),o.push(`${i}return { ctx, args };`),o.push(`${r}},`),o.push(`${r}after(ctx, response) {`),n!==null){let a=JSON.stringify(n,null,2).split(`
14
+ `).map((d,g)=>g===0?`${i}// response.data: ${d}`:`${i}// ${d}`);o.push(...a)}else o.push(`${i}// response.data: unknown (register webhookSchemas to see the type)`);o.push(`${r}},`);for(let s=t.length-1;s>=0;s--){let a=" ".repeat(s+2);o.push(`${a}},`)}return o.push(" },"),o.push("})"),o.join(`
15
+ `)}var He=new Set(Pe);function Z(e,t){let n=t?.type??"api",o=t?.plugin;if(o!==void 0){let i=e.find(a=>a.id===o);if(!i)return He.has(o)?`This plugin (${o}) is not configured. Please add it to the Corsair instance to see its associated methods.`:Z(e);if(n==="webhooks"){if(!i.webhooks)return[];let a=[];return ae(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 ie(i.endpoints,[],s),s.map(a=>`${i.id}.api.${a.toLowerCase()}`)}let r={};if(n==="webhooks")for(let i of e){if(!i.webhooks)continue;let s=[];ae(i.webhooks,[],s),r[i.id]=s.map(a=>`${i.id}.webhooks.${a}`)}else if(n==="db")for(let i of e){let s=i.schema?.entities;s&&(r[i.id]=Object.keys(s).map(a=>`${i.id}.db.${a}.search`))}else for(let i of e){if(!i.endpoints)continue;let s=[];ie(i.endpoints,[],s),r[i.id]=s.map(a=>`${i.id}.api.${a.toLowerCase()}`)}return r}function te(e,t){if(e){for(let[n,o]of Object.entries(e))if(n.toLowerCase()===t)return o}}function Ue(e,t){let n=t.toLowerCase(),o=n.indexOf(".");if(o!==-1){let r=n.slice(0,o),i=n.slice(o+1),s=e.find(a=>a.id===r);if(s){if(i.startsWith("db.")){let y=i.slice(3),c=y.lastIndexOf(".");if(c!==-1){let m=y.slice(0,c),p=y.slice(c+1),u=s.schema?.entities;if(p==="search"&&u){let f=Le(u,m);if(f){let[h,w]=f;return{description:`Search ${r} ${h} stored in the local database. Returns an array of matching records. Pass limit and offset (numbers) for pagination.`,filters:{entity_id:{type:"string",operators:xe},data:oe(w)}}}}}return{availableMethods:Z(e,{type:"db"})}}if(i.startsWith("webhooks.")){let y=i.slice(9);if(s.webhooks){let c=Ae(s.webhooks,y.split("."));if(c!==null){let m=c.join("."),p=te(s.webhookSchemas,m.toLowerCase()),u=p?.response?x(p.response):null;return{description:p?.description,payload:p?.payload?x(p.payload):void 0,response:u??void 0,usage:je(r,c,u)}}}return{availableWebhooks:Z(e,{type:"webhooks"})}}let a=i;a.startsWith("api.")&&(a=a.slice(4));let d=te(s.endpointMeta,a),g=te(s.endpointSchemas,a);if(d||g)return{description:d?.description,riskLevel:d?.riskLevel,irreversible:d?.irreversible,input:g?.input?x(g.input):void 0,output:g?.output?x(g.output):void 0}}}return{availableMethods:Z(e)}}function J(e){return{list_operations(t){return Z(e,t)},get_schema(t){return Ue(e,t)}}}function qe(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function ce({webhooks:e,hooks:t,ctx:n,webhooksTree:o,keyBuilder:r}){for(let[i,s]of Object.entries(e)){let a=t?.[i];if(qe(s)){let d=a,g=async y=>{let c=(p,u)=>s.handler(p,u),m=r?await r(n,"webhook"):void 0;return!d?.before&&!d?.after?c({...n,key:m},y):(async()=>{let p={...n,key:m},u=d.before?await d.before(p,y):{ctx:p,args:y,continue:!0,passToAfter:void 0};if(u.continue===!1)return;let f=await c(u.ctx,u.args);return f?.success===!0&&await d.after?.(u.ctx,f,u.passToAfter),f})()};o[i]={match:s.match,handler:g}}else if(s&&typeof s=="object"){let d={};ce({webhooks:s,hooks:a,ctx:n,webhooksTree:d,keyBuilder:r}),o[i]=d}}}function ze(e,t,n){let o=null;return async()=>{if(o)return o;if(!e)throw new Error("Database not configured");let r=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!r)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","=",r.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${n}" and integration "${t}". Make sure to create the account first.`);return o=i.id,o}}function Ge(e,t,n,o,r){return e?Y(e.db,t,n,o,r):{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 de(e,t){let{database:n,tenantId:o,kek:r,rootErrorHandlers:i,approvalConfig:s}=t,a={},d={};for(let c of e)a[c.id]={},d[c.id]={};for(let c of e){let m=c.schema,p=o??"default",u=ze(n,c.id,p);if(m?.entities){let C={};for(let[v,R]of Object.entries(m.entities)){let B=n?Y(n.db,u,v,m.version,R):Ge(void 0,u,v,m.version,R);C[v]=B}d[c.id].db=C,a[c.id].db=C}let f=c.options,h=c.authConfig,w;if(n&&r&&f?.authType){let C=h?.[f.authType]?.account??[];w=G({authType:f.authType,integrationName:c.id,tenantId:p,kek:r,database:n,extraAccountFields:C}),a[c.id].keys=w}let E={database:n,db:d[c.id]?.db??{},$getAccountId:u,...c.options?{options:c.options}:{},...w?{keys:w,authType:f?.authType}:{},...o?{tenantId:o}:{}},T=c.endpoints??{},l=c.hooks,k={...i,...c.errorHandlers},b={},I=c.options?.permissions;ne({endpoints:T,hooks:l,ctx:E,tree:b,pluginId:c.id,errorHandlers:k,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:I,endpointMeta:c.endpointMeta,database:n,approvalConfig:s,tenantId:o}),Object.keys(b).length>0&&(a[c.id].api=b),E.endpoints=b;let A=c.webhooks??{},P=c.webhookHooks;if(Object.keys(A).length>0){let C={};ce({webhooks:A,hooks:P,ctx:E,webhooksTree:C,keyBuilder:c.keyBuilder}),a[c.id].webhooks=C,c.pluginWebhookMatcher&&(a[c.id].pluginWebhookMatcher=c.pluginWebhookMatcher)}}let g=a,y=J(e);return{...g,...y}}function Re(e,t,n){let o={};for(let r of e){let i=r.options,s=r.authConfig;if(i?.authType){let a=s?.[i.authType]?.integration??[],d=z({authType:i.authType,integrationName:r.id,kek:n,database:t,extraIntegrationFields:a});o[r.id]=d}}return o}async function Ee(e,t,n,o,r="pending"){if(!e)return null;try{let i=le(),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:o,status:r}).execute(),i}catch(i){return console.warn("Failed to log event:",i),null}}async function Je(e,t,n,o="pending"){try{let r=await e.$getAccountId();return Ee(e.database,r,t,n,o)}catch(r){return console.warn("Failed to log event:",r),null}}var Ie=Symbol.for("corsair:internal");function Bn(e){let t=e.database?ue(e.database):void 0,n=t&&e.kek?Re(e.plugins,t,e.kek):q(!!t,!!e.kek),o={plugins:e.plugins,database:t,kek:e.kek,multiTenancy:!!e.multiTenancy,approval:e.approval},r=Ce(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 de(e.plugins,{database:t,tenantId:s,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval})},keys:n,permissions:r,...J(e.plugins)},{[Ie]:o});let i=de(e.plugins,{database:t,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval});return Object.assign({},i,{keys:n,permissions:r,[Ie]:o})}export{K as a,O as b,D as c,Q as d,X as e,S as f,M as g,$ as h,W as i,z as j,G as k,me as l,ke as m,Pe as n,Ee as o,Je as p,Ie as q,Bn as r};
@@ -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};
package/dist/core.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair } from './index-CBFNJJDR.js';
2
- import { A as AuthTypes, d as AccountKeyManagerFor, I as IntegrationKeyManagerFor } from './index-D30v9sPr.js';
3
- export { e as AccountFieldNames, j as AllProviders, h as BASE_AUTH_FIELDS, B as BaseAuthFieldConfig, f as BaseKeyManager, k as BaseProviders, G as BeforeHookResult, l as BindEndpoints, a1 as BindWebhooks, $ as Bivariant, m as BoundEndpointFn, n as BoundEndpointTree, a2 as BoundWebhook, a3 as BoundWebhookTree, i as CorsairClient, o as CorsairContext, p as CorsairEndpoint, r as CorsairErrorHandler, x as CorsairInspectMethods, a as CorsairIntegration, H as CorsairKeyBuilder, J as CorsairKeyBuilderBase, z as CorsairPermissionsNamespace, C as CorsairPlugin, L as CorsairPluginContext, c as CorsairSingleTenantClient, b as CorsairTenantWrapper, a4 as CorsairWebhook, a5 as CorsairWebhookHandler, a6 as CorsairWebhookMatcher, M as EndpointHooks, N as EndpointMetaEntry, E as EndpointPathsOf, Q as EndpointRiskLevel, y as EndpointSchemaResult, q as EndpointTree, D as EnforcePermissionOptions, F as EnforcePermissionResult, s as ErrorContext, t as ErrorHandler, u as ErrorHandlerAndMatchFunction, v as ErrorMatcher, g as IntegrationFieldNames, S as KeyBuilderContext, O as OAuth2IntegrationCredentials, K as OAuthConfig, T as PermissionMode, U as PermissionPolicy, P as PluginAuthConfig, V as PluginEndpointMeta, W as PluginPermissionsConfig, a7 as RawWebhookRequest, X as RequiredPluginEndpointMeta, Y as RequiredPluginEndpointSchemas, Z as RequiredPluginWebhookSchemas, R as RetryStrategies, w as RetryStrategy, a0 as UnionToIntersection, _ as WebhookHooks, a8 as WebhookPathsOf, a9 as WebhookRequest, aa as WebhookResponse, ab as WebhookTree } from './index-D30v9sPr.js';
1
+ export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair } from './index-mtAgyrsC.js';
2
+ import { A as AuthTypes, f as AccountKeyManagerFor, I as IntegrationKeyManagerFor } from './index-CNwyqNCs.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-CNwyqNCs.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
- export { AccountKeyManagerFor, AuthTypes, IntegrationKeyManagerFor, createAccountKeyManager, createIntegrationKeyManager, decryptConfig, decryptDEK, decryptWithDEK, encryptConfig, encryptDEK, encryptWithDEK, generateDEK, initializeAccountDEK, initializeIntegrationDEK, reEncryptConfig };
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-J7NCVPA4.js";import"./chunk-Q55TIVXA.js";import"./chunk-73HYPGOI.js";import"./chunk-A7CRE5AE.js";import"./chunk-476ZUILE.js";export{i as BASE_AUTH_FIELDS,n as CORSAIR_INTERNAL,k as createAccountKeyManager,o 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,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-5XRKMGCV.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";import"./chunk-476ZUILE.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-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};
@@ -1230,4 +1230,4 @@ type CorsairSingleTenantClient<Plugins extends readonly CorsairPlugin[]> = Corsa
1230
1230
  permissions: CorsairPermissionsNamespace;
1231
1231
  };
1232
1232
 
1233
- export { type Bivariant$2 as $, type AuthTypes as A, type BaseAuthFieldConfig as B, type CorsairPlugin as C, type EnforcePermissionOptions as D, type EndpointPathsOf as E, type EnforcePermissionResult as F, type BeforeHookResult as G, type CorsairKeyBuilder as H, type IntegrationKeyManagerFor as I, type CorsairKeyBuilderBase as J, type OAuthConfig as K, type CorsairPluginContext as L, type EndpointHooks as M, type EndpointMetaEntry as N, type OAuth2IntegrationCredentials as O, type PluginAuthConfig as P, type EndpointRiskLevel as Q, type RetryStrategies as R, type KeyBuilderContext as S, type PermissionMode as T, type PermissionPolicy as U, type PluginEndpointMeta as V, type PluginPermissionsConfig as W, type RequiredPluginEndpointMeta as X, type RequiredPluginEndpointSchemas as Y, type RequiredPluginWebhookSchemas as Z, type WebhookHooks as _, type CorsairIntegration as a, type UnionToIntersection$1 as a0, type BindWebhooks as a1, type BoundWebhook as a2, type BoundWebhookTree as a3, type CorsairWebhook as a4, type CorsairWebhookHandler as a5, type CorsairWebhookMatcher as a6, type RawWebhookRequest as a7, type WebhookPathsOf as a8, type WebhookRequest as a9, type WebhookResponse as aa, type WebhookTree as ab, type PickAuth as ac, type CorsairTenantWrapper as b, type CorsairSingleTenantClient as c, type AccountKeyManagerFor as d, type AccountFieldNames as e, type BaseKeyManager as f, type IntegrationFieldNames as g, BASE_AUTH_FIELDS as h, type CorsairClient as i, type AllProviders as j, BaseProviders as k, type BindEndpoints as l, type BoundEndpointFn as m, type BoundEndpointTree as n, type CorsairContext as o, type CorsairEndpoint as p, type EndpointTree as q, type CorsairErrorHandler as r, type ErrorContext as s, type ErrorHandler as t, type ErrorHandlerAndMatchFunction as u, type ErrorMatcher as v, type RetryStrategy as w, type CorsairInspectMethods as x, type EndpointSchemaResult as y, type CorsairPermissionsNamespace as z };
1233
+ 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-D30v9sPr.js';
2
+ import { C as CorsairPlugin, a as CorsairIntegration, b as CorsairTenantWrapper, c as CorsairSingleTenantClient } from './index-CNwyqNCs.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-CBFNJJDR.js';
2
- import { z as CorsairPermissionsNamespace, a3 as BoundWebhookTree, a7 as RawWebhookRequest, k as BaseProviders, aa as WebhookResponse } from './index-D30v9sPr.js';
1
+ export { c as createCorsair } from './index-mtAgyrsC.js';
2
+ import { d as CorsairPermissionsNamespace, B as BoundWebhookTree, R as RawWebhookRequest, e as BaseProviders, W as WebhookResponse } from './index-CNwyqNCs.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-B7SHIP45.js";import{n as k,p as x}from"./chunk-J7NCVPA4.js";import"./chunk-34Z5IBIX.js";import"./chunk-Q55TIVXA.js";import"./chunk-HO245J34.js";import"./chunk-73HYPGOI.js";import"./chunk-A7CRE5AE.js";import"./chunk-476ZUILE.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-34QKYT53.js";import{n as k,r as x}from"./chunk-5XRKMGCV.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-34Z5IBIX.js";import"./chunk-Q55TIVXA.js";import{a as r,b as t,c as i,d as a}from"./chunk-HO245J34.js";import"./chunk-73HYPGOI.js";import"./chunk-A7CRE5AE.js";import"./chunk-476ZUILE.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-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
@@ -1,4 +1,4 @@
1
- import { C as CorsairPlugin, c as CorsairSingleTenantClient } from './index-D30v9sPr.js';
1
+ import { C as CorsairPlugin, c as CorsairSingleTenantClient } from './index-CNwyqNCs.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-B7SHIP45.js";import"./chunk-J7NCVPA4.js";import"./chunk-34Z5IBIX.js";import"./chunk-Q55TIVXA.js";import"./chunk-HO245J34.js";import"./chunk-73HYPGOI.js";import"./chunk-A7CRE5AE.js";import"./chunk-476ZUILE.js";export{o as setupCorsair};
1
+ import{a as o}from"./chunk-34QKYT53.js";import"./chunk-5XRKMGCV.js";import"./chunk-7IH5DNUL.js";import"./chunk-2PB34FTK.js";import"./chunk-HO245J34.js";import"./chunk-73HYPGOI.js";export{o as setupCorsair};