drizzle-cube 0.4.33 → 0.4.35

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 (69) hide show
  1. package/README.md +1 -1
  2. package/dist/adapters/express/index.cjs +1 -1
  3. package/dist/adapters/express/index.d.ts +7 -1
  4. package/dist/adapters/express/index.js +5 -4
  5. package/dist/adapters/fastify/index.cjs +1 -1
  6. package/dist/adapters/fastify/index.d.ts +7 -1
  7. package/dist/adapters/fastify/index.js +5 -4
  8. package/dist/adapters/{handler-ClgB__a-.cjs → handler-DzUX7CBs.cjs} +1 -1
  9. package/dist/adapters/{handler-rPpxuopb.js → handler-J55KQKe5.js} +1 -1
  10. package/dist/adapters/hono/index.cjs +1 -1
  11. package/dist/adapters/hono/index.d.ts +7 -1
  12. package/dist/adapters/hono/index.js +5 -4
  13. package/dist/adapters/{mcp-transport-DWSNkwUY.js → mcp-transport-Cdisv8il.js} +34 -19
  14. package/dist/adapters/{mcp-transport-DPpei63d.cjs → mcp-transport-Dmf2vbIb.cjs} +2 -2
  15. package/dist/adapters/nextjs/index.cjs +1 -1
  16. package/dist/adapters/nextjs/index.d.ts +7 -1
  17. package/dist/adapters/nextjs/index.js +9 -8
  18. package/dist/adapters/{utils-BLFzzCI9.cjs → utils-CDExg9uP.cjs} +1 -1
  19. package/dist/adapters/{utils-B7VkyzMv.js → utils-DkKcpkx5.js} +1 -5
  20. package/dist/adapters/utils.cjs +1 -1
  21. package/dist/adapters/utils.js +1 -1
  22. package/dist/client/charts.js +3 -3
  23. package/dist/client/chunks/{DashboardEditModal-DenRJiYr.js → DashboardEditModal-DsxYiMct.js} +8 -8
  24. package/dist/client/chunks/{DashboardEditModal-DenRJiYr.js.map → DashboardEditModal-DsxYiMct.js.map} +1 -1
  25. package/dist/client/chunks/{FieldSearchModal-BQS1v1up.js → FieldSearchModal-CSzgVPdG.js} +3 -3
  26. package/dist/client/chunks/{FieldSearchModal-BQS1v1up.js.map → FieldSearchModal-CSzgVPdG.js.map} +1 -1
  27. package/dist/client/chunks/{analysis-builder-DG38V1gO.js → analysis-builder-CxXZDfFR.js} +8 -8
  28. package/dist/client/chunks/{analysis-builder-DG38V1gO.js.map → analysis-builder-CxXZDfFR.js.map} +1 -1
  29. package/dist/client/chunks/{analysis-builder-shared-DaFu78dk.js → analysis-builder-shared-fwyLiZ48.js} +15 -19
  30. package/dist/client/chunks/{analysis-builder-shared-DaFu78dk.js.map → analysis-builder-shared-fwyLiZ48.js.map} +1 -1
  31. package/dist/client/chunks/{chart-data-table-B2m_6EZe.js → chart-data-table-CGG-_R93.js} +601 -580
  32. package/dist/client/chunks/chart-data-table-CGG-_R93.js.map +1 -0
  33. package/dist/client/chunks/{chart-kpi-delta-S6qDEoJO.js → chart-kpi-delta-D9eNhKR6.js} +2 -2
  34. package/dist/client/chunks/{chart-kpi-delta-S6qDEoJO.js.map → chart-kpi-delta-D9eNhKR6.js.map} +1 -1
  35. package/dist/client/chunks/{chart-kpi-number-CEUBsVW2.js → chart-kpi-number-IJWReEix.js} +3 -3
  36. package/dist/client/chunks/{chart-kpi-number-CEUBsVW2.js.map → chart-kpi-number-IJWReEix.js.map} +1 -1
  37. package/dist/client/chunks/{chart-kpi-text-DgRig_jQ.js → chart-kpi-text-Dsr7nPmz.js} +2 -2
  38. package/dist/client/chunks/{chart-kpi-text-DgRig_jQ.js.map → chart-kpi-text-Dsr7nPmz.js.map} +1 -1
  39. package/dist/client/chunks/{chart-markdown-DXxc43w1.js → chart-markdown-B2X4IwLO.js} +1132 -1119
  40. package/dist/client/chunks/chart-markdown-B2X4IwLO.js.map +1 -0
  41. package/dist/client/chunks/{charts-loader-BI07yxaQ.js → charts-loader-DSdXpr7e.js} +6 -6
  42. package/dist/client/chunks/{charts-loader-BI07yxaQ.js.map → charts-loader-DSdXpr7e.js.map} +1 -1
  43. package/dist/client/chunks/{core-D1TOj17W.js → core-DJrniqct.js} +2 -6
  44. package/dist/client/chunks/{core-D1TOj17W.js.map → core-DJrniqct.js.map} +1 -1
  45. package/dist/client/chunks/{schema-visualization-DPL5_Tkh.js → schema-visualization-CBQrcxb8.js} +13 -14
  46. package/dist/client/chunks/{schema-visualization-DPL5_Tkh.js.map → schema-visualization-CBQrcxb8.js.map} +1 -1
  47. package/dist/client/chunks/{syntaxHighlighting-87bOwTxj.js → syntaxHighlighting-BLl0ch4A.js} +2 -2
  48. package/dist/client/chunks/{syntaxHighlighting-87bOwTxj.js.map → syntaxHighlighting-BLl0ch4A.js.map} +1 -1
  49. package/dist/client/chunks/{useDebounce-DkuM7nQk.js → useDebounce-BbYqb134.js} +2 -2
  50. package/dist/client/chunks/{useDebounce-DkuM7nQk.js.map → useDebounce-BbYqb134.js.map} +1 -1
  51. package/dist/client/chunks/{useExplainAI-RflLTDVL.js → useExplainAI-CbAR-1p5.js} +4 -4
  52. package/dist/client/chunks/{useExplainAI-RflLTDVL.js.map → useExplainAI-CbAR-1p5.js.map} +1 -1
  53. package/dist/client/chunks/{utils--32ZtfbZ.js → utils-BxLeWUeg.js} +2 -2
  54. package/dist/client/chunks/{utils--32ZtfbZ.js.map → utils-BxLeWUeg.js.map} +1 -1
  55. package/dist/client/chunks/{vendor-CZX7UVzM.js → vendor-QBbbDL5y.js} +3 -3
  56. package/dist/client/chunks/{vendor-CZX7UVzM.js.map → vendor-QBbbDL5y.js.map} +1 -1
  57. package/dist/client/components.js +3 -3
  58. package/dist/client/hooks.js +3 -3
  59. package/dist/client/icons.js +1 -1
  60. package/dist/client/index.js +12 -12
  61. package/dist/client/providers.js +1 -1
  62. package/dist/client/utils.js +4 -4
  63. package/dist/client-bundle-stats.html +1 -1
  64. package/dist/server/index.cjs +2 -2
  65. package/dist/server/index.d.ts +47 -5
  66. package/dist/server/index.js +33 -18
  67. package/package.json +4 -4
  68. package/dist/client/chunks/chart-data-table-B2m_6EZe.js.map +0 -1
  69. package/dist/client/chunks/chart-markdown-DXxc43w1.js.map +0 -1
package/README.md CHANGED
@@ -132,7 +132,7 @@ Build ad-hoc queries with measures, dimensions, filters, and time ranges. Search
132
132
 
133
133
  ![Analysis Builder](https://try.drizzle-cube.dev/dashboard_light.png)
134
134
 
135
- **[Try the Analysis Builder →](https://try.drizzle-cube.dev/analysis)**
135
+ **[Try the Analysis Builder →](https://try.drizzle-cube.dev/analysis-builder)**
136
136
 
137
137
  ### Funnel Analysis
138
138
  Track conversion through multi-step processes. Define funnel steps, measure drop-off rates, and analyze time-to-convert metrics (average, median, p90).
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../utils-BLFzzCI9.cjs`),t=require(`../mcp-transport-DPpei63d.cjs`);let n=require(`express`);n=e.g(n);let r=require(`cors`);r=e.g(r);function i(i){let{cubes:a,drizzle:o,schema:s,extractSecurityContext:c,engineType:l,cors:u,basePath:d=`/cubejs-api/v1`,jsonLimit:f=`10mb`,cache:p,mcp:m={enabled:!0},agent:h}=i;if(!a||a.length===0)throw Error(`At least one cube must be provided in the cubes array`);let g=(0,n.Router)();u&&g.use((0,r.default)(u)),g.use(n.default.json({limit:f})),g.use(n.default.urlencoded({extended:!0,limit:f}));let _=new t.h({drizzle:o,schema:s,engineType:l,cache:p});if(a.forEach(e=>{_.registerCube(e)}),g.post(`${d}/load`,async(t,n)=>{try{let r=t.body.query||t.body,i=await c(t,n),a=_.validateQuery(r);if(!a.isValid)return n.status(400).json(e.i(`Query validation failed: ${a.errors.join(`, `)}`,400));let o=t.headers[`x-cache-control`]===`no-cache`,s=await _.executeMultiCubeQuery(r,i,{skipCache:o});n.json(e.r(r,s,_))}catch(t){console.error(`Query execution error:`,t),n.status(500).json(e.i(t instanceof Error?t.message:`Query execution failed`,500))}}),g.get(`${d}/load`,async(t,n)=>{try{let r=t.query.query;if(!r)return n.status(400).json(e.i(`Query parameter is required`,400));let i;try{i=JSON.parse(r)}catch{return n.status(400).json(e.i(`Invalid JSON in query parameter`,400))}let a=await c(t,n),o=_.validateQuery(i);if(!o.isValid)return n.status(400).json(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=t.headers[`x-cache-control`]===`no-cache`,l=await _.executeMultiCubeQuery(i,a,{skipCache:s});n.json(e.r(i,l,_))}catch(t){console.error(`Query execution error:`,t),n.status(500).json(e.i(t instanceof Error?t.message:`Query execution failed`,500))}}),g.post(`${d}/batch`,async(t,n)=>{try{let{queries:r}=t.body;if(!r||!Array.isArray(r))return n.status(400).json(e.i(`Request body must contain a "queries" array`,400));if(r.length===0)return n.status(400).json(e.i(`Queries array cannot be empty`,400));let i=await e.u(r,await c(t,n),_,{skipCache:t.headers[`x-cache-control`]===`no-cache`});n.json(i)}catch(t){console.error(`Batch execution error:`,t),n.status(500).json(e.i(t instanceof Error?t.message:`Batch execution failed`,500))}}),g.get(`${d}/meta`,(t,n)=>{try{let t=_.getMetadata();n.json(e.a(t))}catch(t){console.error(`Metadata error:`,t),n.status(500).json(e.i(t instanceof Error?t.message:`Failed to fetch metadata`,500))}}),g.post(`${d}/sql`,async(t,n)=>{try{let r=t.body,i=await c(t,n),a=_.validateQuery(r);if(!a.isValid)return n.status(400).json(e.i(`Query validation failed: ${a.errors.join(`, `)}`,400));let o=r.measures?.[0]||r.dimensions?.[0];if(!o)return n.status(400).json(e.i(`No measures or dimensions specified`,400));let s=o.split(`.`)[0],l=await _.generateSQL(s,r,i);n.json(e.o(r,l))}catch(t){console.error(`SQL generation error:`,String(t).replace(/\n|\r/g,``)),n.status(500).json(e.i(t instanceof Error?t.message:`SQL generation failed`,500))}}),g.get(`${d}/sql`,async(t,n)=>{try{let r=t.query.query;if(!r)return n.status(400).json(e.i(`Query parameter is required`,400));let i=JSON.parse(r),a=await c(t,n),o=_.validateQuery(i);if(!o.isValid)return n.status(400).json(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=i.measures?.[0]||i.dimensions?.[0];if(!s)return n.status(400).json(e.i(`No measures or dimensions specified`,400));let l=s.split(`.`)[0],u=await _.generateSQL(l,i,a);n.json(e.o(i,u))}catch(t){console.error(`SQL generation error:`,String(t).replace(/\n|\r/g,``)),n.status(500).json(e.i(t instanceof Error?t.message:`SQL generation failed`,500))}}),g.post(`${d}/dry-run`,async(t,n)=>{try{let r=await e.f(t.body.query||t.body,await c(t,n),_);n.json(r)}catch(e){console.error(`Dry-run error:`,e),n.status(400).json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1})}}),g.get(`${d}/dry-run`,async(t,n)=>{try{let r=t.query.query;if(!r)return n.status(400).json({error:`Query parameter is required`,valid:!1});let i=await e.f(JSON.parse(r),await c(t,n),_);n.json(i)}catch(e){console.error(`Dry-run error:`,e),n.status(400).json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1})}}),g.post(`${d}/explain`,async(e,t)=>{try{let n=e.body.query||e.body,r=e.body.options||{},i=await c(e,t),a=_.validateQuery(n);if(!a.isValid)return t.status(400).json({error:`Query validation failed: ${a.errors.join(`, `)}`});let o=await _.explainQuery(n,i,r);t.json(o)}catch(e){console.error(`Explain error:`,e),t.status(500).json({error:e instanceof Error?e.message:`Explain query failed`})}}),h&&g.post(`${d}/agent/chat`,async(e,t)=>{try{let{handleAgentChat:n}=await Promise.resolve().then(()=>require(`../handler-ClgB__a-.cjs`)),{message:r,sessionId:i,history:a}=e.body;if(!r||typeof r!=`string`)return t.status(400).json({error:`message is required and must be a string`});let o=(h.apiKey||``).trim();if(h.allowClientApiKey){let t=e.headers[`x-agent-api-key`];t&&(o=t.trim())}if(!o)return t.status(401).json({error:`No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header.`});let s=h.allowClientApiKey?e.headers[`x-agent-provider`]:void 0,l=h.allowClientApiKey?e.headers[`x-agent-model`]:void 0,u=h.allowClientApiKey?e.headers[`x-agent-provider-endpoint`]:void 0,d=await c(e,t),f=h.buildSystemContext?.(d);t.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`});try{let e=n({message:r,sessionId:i,history:a,semanticLayer:_,securityContext:d,agentConfig:h,apiKey:o,systemContext:f,providerOverride:s,modelOverride:l,baseURLOverride:u});for await(let n of e)t.write(`data: ${JSON.stringify(n)}\n\n`)}catch(e){let n={type:`error`,data:{message:e instanceof Error?e.message:`Stream failed`}};t.write(`data: ${JSON.stringify(n)}\n\n`)}finally{t.end()}}catch(e){console.error(`Agent chat error:`,e),t.headersSent||t.status(500).json({error:e instanceof Error?e.message:`Agent chat failed`})}}),m.enabled!==!1){let e=m.basePath??`/mcp`;g.post(`${e}`,async(e,n)=>{let r=t.p(e.headers.origin,m.allowedOrigins?{allowedOrigins:m.allowedOrigins}:{});if(!r.valid)return n.status(403).json(t.n(null,-32600,r.reason));let i=e.headers.accept;if(!t.f(i))return n.status(400).json(t.n(null,-32600,`Accept header must include both application/json and text/event-stream`));let a=t.c(e.headers);if(!a.ok)return n.status(426).json({error:`Unsupported MCP protocol version`,supported:a.supported});let o=t.l(e.body);if(!o)return n.status(400).json(t.n(null,-32600,`Invalid JSON-RPC 2.0 request`));let s=t.m(i),l=o.method===`initialize`;try{let r=await t.i(o.method,o.params,{semanticLayer:_,extractSecurityContext:c,rawRequest:e,rawResponse:n,negotiatedProtocol:a.negotiated});if(t.s(o))return n.status(202).end();let i=l&&r&&typeof r==`object`&&`sessionId`in r?r.sessionId:void 0;i&&n.setHeader(t.t,i);let u=t.r(o.id??null,r);if(s){let e=t.u();return n.status(200),n.setHeader(`Content-Type`,`text/event-stream`),n.setHeader(`Cache-Control`,`no-cache`),n.setHeader(`Connection`,`keep-alive`),n.write(`id: ${e}\n\n`),n.write(t.d(u,e)),n.end()}return n.json(u)}catch(e){if(t.s(o))return console.error(`MCP notification processing error:`,String(e).replace(/\n|\r/g,``)),n.status(202).end();console.error(`MCP RPC error:`,String(e).replace(/\n|\r/g,``));let r=e?.code??-32603,i=e?.data,a=e.message||`MCP request failed`,c=t.n(o.id??null,r,a,i);if(s){let e=t.u();return n.status(200),n.setHeader(`Content-Type`,`text/event-stream`),n.setHeader(`Cache-Control`,`no-cache`),n.setHeader(`Connection`,`keep-alive`),n.write(`id: ${e}\n\n`),n.write(t.d(c,e)),n.end()}return n.status(200).json(c)}}),g.get(`${e}`,async(e,n)=>{let r=t.u();n.status(200),n.setHeader(`Content-Type`,`text/event-stream`),n.setHeader(`Cache-Control`,`no-cache`),n.setHeader(`Connection`,`keep-alive`),n.write(t.d({jsonrpc:`2.0`,method:`mcp/ready`,params:{protocol:`streamable-http`}},r,15e3));let i=setInterval(()=>{n.write(`: keep-alive
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../utils-CDExg9uP.cjs`),t=require(`../mcp-transport-Dmf2vbIb.cjs`);let n=require(`express`);n=e.g(n);let r=require(`cors`);r=e.g(r);function i(i){let{cubes:a,drizzle:o,schema:s,extractSecurityContext:c,engineType:l,cors:u,basePath:d=`/cubejs-api/v1`,jsonLimit:f=`10mb`,cache:p,mcp:m={enabled:!0},agent:h}=i;if(!a||a.length===0)throw Error(`At least one cube must be provided in the cubes array`);let g=(0,n.Router)();u&&g.use((0,r.default)(u)),g.use(n.default.json({limit:f})),g.use(n.default.urlencoded({extended:!0,limit:f}));let _=new t.h({drizzle:o,schema:s,engineType:l,cache:p,rlsSetup:i.rlsSetup});if(a.forEach(e=>{_.registerCube(e)}),g.post(`${d}/load`,async(t,n)=>{try{let r=t.body.query||t.body,i=await c(t,n),a=_.validateQuery(r);if(!a.isValid)return n.status(400).json(e.i(`Query validation failed: ${a.errors.join(`, `)}`,400));let o=t.headers[`x-cache-control`]===`no-cache`,s=await _.executeMultiCubeQuery(r,i,{skipCache:o});n.json(e.r(r,s,_))}catch(t){console.error(`Query execution error:`,t),n.status(500).json(e.i(t instanceof Error?t.message:`Query execution failed`,500))}}),g.get(`${d}/load`,async(t,n)=>{try{let r=t.query.query;if(!r)return n.status(400).json(e.i(`Query parameter is required`,400));let i;try{i=JSON.parse(r)}catch{return n.status(400).json(e.i(`Invalid JSON in query parameter`,400))}let a=await c(t,n),o=_.validateQuery(i);if(!o.isValid)return n.status(400).json(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=t.headers[`x-cache-control`]===`no-cache`,l=await _.executeMultiCubeQuery(i,a,{skipCache:s});n.json(e.r(i,l,_))}catch(t){console.error(`Query execution error:`,t),n.status(500).json(e.i(t instanceof Error?t.message:`Query execution failed`,500))}}),g.post(`${d}/batch`,async(t,n)=>{try{let{queries:r}=t.body;if(!r||!Array.isArray(r))return n.status(400).json(e.i(`Request body must contain a "queries" array`,400));if(r.length===0)return n.status(400).json(e.i(`Queries array cannot be empty`,400));let i=await e.u(r,await c(t,n),_,{skipCache:t.headers[`x-cache-control`]===`no-cache`});n.json(i)}catch(t){console.error(`Batch execution error:`,t),n.status(500).json(e.i(t instanceof Error?t.message:`Batch execution failed`,500))}}),g.get(`${d}/meta`,(t,n)=>{try{let t=_.getMetadata();n.json(e.a(t))}catch(t){console.error(`Metadata error:`,t),n.status(500).json(e.i(t instanceof Error?t.message:`Failed to fetch metadata`,500))}}),g.post(`${d}/sql`,async(t,n)=>{try{let r=t.body,i=await c(t,n),a=_.validateQuery(r);if(!a.isValid)return n.status(400).json(e.i(`Query validation failed: ${a.errors.join(`, `)}`,400));let o=r.measures?.[0]||r.dimensions?.[0];if(!o)return n.status(400).json(e.i(`No measures or dimensions specified`,400));let s=o.split(`.`)[0],l=await _.generateSQL(s,r,i);n.json(e.o(r,l))}catch(t){console.error(`SQL generation error:`,String(t).replace(/\n|\r/g,``)),n.status(500).json(e.i(t instanceof Error?t.message:`SQL generation failed`,500))}}),g.get(`${d}/sql`,async(t,n)=>{try{let r=t.query.query;if(!r)return n.status(400).json(e.i(`Query parameter is required`,400));let i=JSON.parse(r),a=await c(t,n),o=_.validateQuery(i);if(!o.isValid)return n.status(400).json(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=i.measures?.[0]||i.dimensions?.[0];if(!s)return n.status(400).json(e.i(`No measures or dimensions specified`,400));let l=s.split(`.`)[0],u=await _.generateSQL(l,i,a);n.json(e.o(i,u))}catch(t){console.error(`SQL generation error:`,String(t).replace(/\n|\r/g,``)),n.status(500).json(e.i(t instanceof Error?t.message:`SQL generation failed`,500))}}),g.post(`${d}/dry-run`,async(t,n)=>{try{let r=await e.f(t.body.query||t.body,await c(t,n),_);n.json(r)}catch(e){console.error(`Dry-run error:`,e),n.status(400).json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1})}}),g.get(`${d}/dry-run`,async(t,n)=>{try{let r=t.query.query;if(!r)return n.status(400).json({error:`Query parameter is required`,valid:!1});let i=await e.f(JSON.parse(r),await c(t,n),_);n.json(i)}catch(e){console.error(`Dry-run error:`,e),n.status(400).json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1})}}),g.post(`${d}/explain`,async(e,t)=>{try{let n=e.body.query||e.body,r=e.body.options||{},i=await c(e,t),a=_.validateQuery(n);if(!a.isValid)return t.status(400).json({error:`Query validation failed: ${a.errors.join(`, `)}`});let o=await _.explainQuery(n,i,r);t.json(o)}catch(e){console.error(`Explain error:`,e),t.status(500).json({error:e instanceof Error?e.message:`Explain query failed`})}}),h&&g.post(`${d}/agent/chat`,async(e,t)=>{try{let{handleAgentChat:n}=await Promise.resolve().then(()=>require(`../handler-DzUX7CBs.cjs`)),{message:r,sessionId:i,history:a}=e.body;if(!r||typeof r!=`string`)return t.status(400).json({error:`message is required and must be a string`});let o=(h.apiKey||``).trim();if(h.allowClientApiKey){let t=e.headers[`x-agent-api-key`];t&&(o=t.trim())}if(!o)return t.status(401).json({error:`No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header.`});let s=h.allowClientApiKey?e.headers[`x-agent-provider`]:void 0,l=h.allowClientApiKey?e.headers[`x-agent-model`]:void 0,u=h.allowClientApiKey?e.headers[`x-agent-provider-endpoint`]:void 0,d=await c(e,t),f=h.buildSystemContext?.(d);t.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`});try{let e=n({message:r,sessionId:i,history:a,semanticLayer:_,securityContext:d,agentConfig:h,apiKey:o,systemContext:f,providerOverride:s,modelOverride:l,baseURLOverride:u});for await(let n of e)t.write(`data: ${JSON.stringify(n)}\n\n`)}catch(e){let n={type:`error`,data:{message:e instanceof Error?e.message:`Stream failed`}};t.write(`data: ${JSON.stringify(n)}\n\n`)}finally{t.end()}}catch(e){console.error(`Agent chat error:`,e),t.headersSent||t.status(500).json({error:e instanceof Error?e.message:`Agent chat failed`})}}),m.enabled!==!1){let e=m.basePath??`/mcp`;g.post(`${e}`,async(e,n)=>{let r=t.p(e.headers.origin,m.allowedOrigins?{allowedOrigins:m.allowedOrigins}:{});if(!r.valid)return n.status(403).json(t.n(null,-32600,r.reason));let i=e.headers.accept;if(!t.f(i))return n.status(400).json(t.n(null,-32600,`Accept header must include both application/json and text/event-stream`));let a=t.c(e.headers);if(!a.ok)return n.status(426).json({error:`Unsupported MCP protocol version`,supported:a.supported});let o=t.l(e.body);if(!o)return n.status(400).json(t.n(null,-32600,`Invalid JSON-RPC 2.0 request`));let s=t.m(i),l=o.method===`initialize`;try{let r=await t.i(o.method,o.params,{semanticLayer:_,extractSecurityContext:c,rawRequest:e,rawResponse:n,negotiatedProtocol:a.negotiated});if(t.s(o))return n.status(202).end();let i=l&&r&&typeof r==`object`&&`sessionId`in r?r.sessionId:void 0;i&&n.setHeader(t.t,i);let u=t.r(o.id??null,r);if(s){let e=t.u();return n.status(200),n.setHeader(`Content-Type`,`text/event-stream`),n.setHeader(`Cache-Control`,`no-cache`),n.setHeader(`Connection`,`keep-alive`),n.write(`id: ${e}\n\n`),n.write(t.d(u,e)),n.end()}return n.json(u)}catch(e){if(t.s(o))return console.error(`MCP notification processing error:`,String(e).replace(/\n|\r/g,``)),n.status(202).end();console.error(`MCP RPC error:`,String(e).replace(/\n|\r/g,``));let r=e?.code??-32603,i=e?.data,a=e.message||`MCP request failed`,c=t.n(o.id??null,r,a,i);if(s){let e=t.u();return n.status(200),n.setHeader(`Content-Type`,`text/event-stream`),n.setHeader(`Cache-Control`,`no-cache`),n.setHeader(`Connection`,`keep-alive`),n.write(`id: ${e}\n\n`),n.write(t.d(c,e)),n.end()}return n.status(200).json(c)}}),g.get(`${e}`,async(e,n)=>{let r=t.u();n.status(200),n.setHeader(`Content-Type`,`text/event-stream`),n.setHeader(`Cache-Control`,`no-cache`),n.setHeader(`Connection`,`keep-alive`),n.write(t.d({jsonrpc:`2.0`,method:`mcp/ready`,params:{protocol:`streamable-http`}},r,15e3));let i=setInterval(()=>{n.write(`: keep-alive
2
2
 
3
3
  `)},15e3);e.on(`close`,()=>{clearInterval(i)})}),g.delete(`${e}`,(e,t)=>t.status(405).json({error:`Session termination not supported`}))}return g.use((t,n,r,i)=>{console.error(`Express adapter error:`,t),r.headersSent||r.status(500).json(e.i(t,500))}),g}function a(e,t){let n=i(t);return e.use(`/`,n),e}function o(e){return a((0,n.default)(),e)}exports.createCubeApp=o,exports.createCubeRouter=i,exports.mountCubeRoutes=a;
@@ -1,6 +1,6 @@
1
1
  import { Router, Request, Response, Express } from 'express';
2
2
  import { CorsOptions } from 'cors';
3
- import { SemanticQuery, SecurityContext, DatabaseExecutor, DrizzleDatabase, Cube, CacheConfig } from '../../server';
3
+ import { SemanticQuery, SecurityContext, DatabaseExecutor, DrizzleDatabase, Cube, CacheConfig, RLSSetupFn } from '../../server';
4
4
  import { AgentConfig } from '../../server/agent/types';
5
5
  import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
6
6
  import { MySql2Database } from 'drizzle-orm/mysql2';
@@ -80,6 +80,12 @@ export interface ExpressAdapterOptions {
80
80
  * Requires `@anthropic-ai/sdk` as a peer dependency.
81
81
  */
82
82
  agent?: AgentConfig;
83
+ /**
84
+ * Row-Level Security setup function.
85
+ * When provided, every query execution opens a transaction, calls this function
86
+ * to configure RLS (e.g., set JWT claims and switch Postgres roles), then runs the query.
87
+ */
88
+ rlsSetup?: RLSSetupFn;
83
89
  }
84
90
  /**
85
91
  * Create Express router for Cube.js-compatible API
@@ -1,5 +1,5 @@
1
- import { a as e, f as t, i as n, o as r, r as i, u as a } from "../utils-B7VkyzMv.js";
2
- import { c as o, d as s, f as c, h as l, i as u, l as d, m as f, n as p, p as m, r as h, s as g, t as _, u as v } from "../mcp-transport-DWSNkwUY.js";
1
+ import { a as e, f as t, i as n, o as r, r as i, u as a } from "../utils-DkKcpkx5.js";
2
+ import { c as o, d as s, f as c, h as l, i as u, l as d, m as f, n as p, p as m, r as h, s as g, t as _, u as v } from "../mcp-transport-Cdisv8il.js";
3
3
  import y, { Router as b } from "express";
4
4
  import x from "cors";
5
5
  //#region src/adapters/express/index.ts
@@ -15,7 +15,8 @@ function S(S) {
15
15
  drizzle: w,
16
16
  schema: T,
17
17
  engineType: D,
18
- cache: j
18
+ cache: j,
19
+ rlsSetup: S.rlsSetup
19
20
  });
20
21
  if (C.forEach((e) => {
21
22
  F.registerCube(e);
@@ -122,7 +123,7 @@ function S(S) {
122
123
  }
123
124
  }), N && P.post(`${k}/agent/chat`, async (e, t) => {
124
125
  try {
125
- let { handleAgentChat: n } = await import("../handler-rPpxuopb.js"), { message: r, sessionId: i, history: a } = e.body;
126
+ let { handleAgentChat: n } = await import("../handler-J55KQKe5.js"), { message: r, sessionId: i, history: a } = e.body;
126
127
  if (!r || typeof r != "string") return t.status(400).json({ error: "message is required and must be a string" });
127
128
  let o = (N.apiKey || "").trim();
128
129
  if (N.allowClientApiKey) {
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../utils-BLFzzCI9.cjs`),t=require(`../mcp-transport-DPpei63d.cjs`);var n=function(n,r,i){let{cubes:a,drizzle:o,schema:s,extractSecurityContext:c,engineType:l,cors:u,basePath:d=`/cubejs-api/v1`,bodyLimit:f=10485760,cache:p,mcp:m={enabled:!0},agent:h}=r;if(!a||a.length===0)return i(Error(`At least one cube must be provided in the cubes array`));u&&n.register(import(`@fastify/cors`),u),n.addHook(`onRequest`,async(e,t)=>{e.method===`POST`&&(e.body=void 0)});let g=new t.h({drizzle:o,schema:s,engineType:l,cache:p});if(a.forEach(e=>{g.registerCube(e)}),n.post(`${d}/load`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(t,n)=>{try{let r=t.body,i=r.query||r,a=await c(t),o=g.validateQuery(i);if(!o.isValid)return n.status(400).send(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=t.headers[`x-cache-control`]===`no-cache`;return e.r(i,await g.executeMultiCubeQuery(i,a,{skipCache:s}),g)}catch(r){return t.log.error(r,`Query execution error`),n.status(500).send(e.i(r instanceof Error?r.message:`Query execution failed`,500))}}),n.get(`${d}/load`,{schema:{querystring:{type:`object`,properties:{query:{type:`string`}},required:[`query`]}}},async(t,n)=>{try{let{query:r}=t.query,i;try{i=JSON.parse(r)}catch{return n.status(400).send(e.i(`Invalid JSON in query parameter`,400))}let a=await c(t),o=g.validateQuery(i);if(!o.isValid)return n.status(400).send(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=t.headers[`x-cache-control`]===`no-cache`,l=await g.executeMultiCubeQuery(i,a,{skipCache:s});return e.r(i,l,g)}catch(r){return t.log.error(r,`Query execution error`),n.status(500).send(e.i(r instanceof Error?r.message:`Query execution failed`,500))}}),n.post(`${d}/batch`,{bodyLimit:f,schema:{body:{type:`object`,required:[`queries`],properties:{queries:{type:`array`,items:{type:`object`}}}}}},async(t,n)=>{try{let{queries:r}=t.body;return!r||!Array.isArray(r)?n.status(400).send(e.i(`Request body must contain a "queries" array`,400)):r.length===0?n.status(400).send(e.i(`Queries array cannot be empty`,400)):await e.u(r,await c(t),g,{skipCache:t.headers[`x-cache-control`]===`no-cache`})}catch(r){return t.log.error(r,`Batch execution error`),n.status(500).send(e.i(r instanceof Error?r.message:`Batch execution failed`,500))}}),n.get(`${d}/meta`,async(t,n)=>{try{return e.a(g.getMetadata())}catch(r){return t.log.error(r,`Metadata error`),n.status(500).send(e.i(r instanceof Error?r.message:`Failed to fetch metadata`,500))}}),n.post(`${d}/sql`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(t,n)=>{try{let r=t.body,i=await c(t),a=g.validateQuery(r);if(!a.isValid)return n.status(400).send(e.i(`Query validation failed: ${a.errors.join(`, `)}`,400));let o=r.measures?.[0]||r.dimensions?.[0];if(!o)return n.status(400).send(e.i(`No measures or dimensions specified`,400));let s=o.split(`.`)[0];return e.o(r,await g.generateSQL(s,r,i))}catch(r){return t.log.error({err:String(r).replace(/\n|\r/g,``)},`SQL generation error`),n.status(500).send(e.i(r instanceof Error?r.message:`SQL generation failed`,500))}}),n.get(`${d}/sql`,{schema:{querystring:{type:`object`,properties:{query:{type:`string`}},required:[`query`]}}},async(t,n)=>{try{let{query:r}=t.query,i=JSON.parse(r),a=await c(t),o=g.validateQuery(i);if(!o.isValid)return n.status(400).send(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=i.measures?.[0]||i.dimensions?.[0];if(!s)return n.status(400).send(e.i(`No measures or dimensions specified`,400));let l=s.split(`.`)[0];return e.o(i,await g.generateSQL(l,i,a))}catch(r){return t.log.error({err:String(r).replace(/\n|\r/g,``)},`SQL generation error`),n.status(500).send(e.i(r instanceof Error?r.message:`SQL generation failed`,500))}}),n.post(`${d}/dry-run`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(t,n)=>{try{let n=t.body;return await e.f(n.query||n,await c(t),g)}catch(e){return t.log.error(e,`Dry-run error`),n.status(400).send({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1})}}),n.get(`${d}/dry-run`,{schema:{querystring:{type:`object`,properties:{query:{type:`string`}},required:[`query`]}}},async(t,n)=>{try{let{query:n}=t.query;return await e.f(JSON.parse(n),await c(t),g)}catch(e){return t.log.error(e,`Dry-run error`),n.status(400).send({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1})}}),n.post(`${d}/explain`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(e,t)=>{try{let n=e.body,r=n.query||n,i=n.options||{},a=await c(e),o=g.validateQuery(r);return o.isValid?await g.explainQuery(r,a,i):t.status(400).send({error:`Query validation failed: ${o.errors.join(`, `)}`})}catch(n){return e.log.error(n,`Explain error`),t.status(500).send({error:n instanceof Error?n.message:`Explain query failed`})}}),h&&n.post(`${d}/agent/chat`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(e,t)=>{try{let{handleAgentChat:n}=await Promise.resolve().then(()=>require(`../handler-ClgB__a-.cjs`)),{message:r,sessionId:i,history:a}=e.body;if(!r||typeof r!=`string`)return t.status(400).send({error:`message is required and must be a string`});let o=(h.apiKey||``).trim();if(h.allowClientApiKey){let t=e.headers[`x-agent-api-key`];t&&(o=t.trim())}if(!o)return t.status(401).send({error:`No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header.`});let s=h.allowClientApiKey?e.headers[`x-agent-provider`]:void 0,l=h.allowClientApiKey?e.headers[`x-agent-model`]:void 0,u=h.allowClientApiKey?e.headers[`x-agent-provider-endpoint`]:void 0,d=await c(e),f=h.buildSystemContext?.(d);t.raw.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`});try{let e=n({message:r,sessionId:i,history:a,semanticLayer:g,securityContext:d,agentConfig:h,apiKey:o,systemContext:f,providerOverride:s,modelOverride:l,baseURLOverride:u});for await(let n of e)t.raw.write(`data: ${JSON.stringify(n)}\n\n`)}catch(e){let n={type:`error`,data:{message:e instanceof Error?e.message:`Stream failed`}};t.raw.write(`data: ${JSON.stringify(n)}\n\n`)}finally{t.raw.end()}}catch(n){if(e.log.error(n,`Agent chat error`),!t.raw.headersSent)return t.status(500).send({error:n instanceof Error?n.message:`Agent chat failed`})}}),m.enabled!==!1){let e=m.basePath??`/mcp`;n.post(`${e}`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(e,n)=>{let r=t.p(e.headers.origin,m.allowedOrigins?{allowedOrigins:m.allowedOrigins}:{});if(!r.valid)return n.status(403).send(t.n(null,-32600,r.reason));let i=e.headers.accept;if(!t.f(i))return n.status(400).send(t.n(null,-32600,`Accept header must include both application/json and text/event-stream`));let a=t.c(e.headers);if(!a.ok)return n.status(426).send({error:`Unsupported MCP protocol version`,supported:a.supported});let o=t.l(e.body);if(!o)return n.status(400).send(t.n(null,-32600,`Invalid JSON-RPC 2.0 request`));let s=t.m(i),l=o.method===`initialize`;try{let r=await t.i(o.method,o.params,{semanticLayer:g,extractSecurityContext:c,rawRequest:e,rawResponse:n,negotiatedProtocol:a.negotiated});if(t.s(o))return n.status(202).send();let i=l&&r&&typeof r==`object`&&`sessionId`in r?r.sessionId:void 0;i&&n.header(t.t,i);let u=t.r(o.id??null,r);if(s){let e=t.u();n.header(`Content-Type`,`text/event-stream`).header(`Cache-Control`,`no-cache`).header(`Connection`,`keep-alive`).send(`id: ${e}\n\n${t.d(u,e)}`);return}return n.send(u)}catch(r){if(t.s(o))return e.log.error({err:String(r).replace(/\n|\r/g,``)},`MCP notification processing error`),n.status(202).send();e.log.error({err:String(r).replace(/\n|\r/g,``)},`MCP RPC error`);let i=r?.code??-32603,a=r?.data,c=r.message||`MCP request failed`,l=t.n(o.id??null,i,c,a);if(s){let e=t.u();n.header(`Content-Type`,`text/event-stream`).header(`Cache-Control`,`no-cache`).header(`Connection`,`keep-alive`).send(`id: ${e}\n\n${t.d(l,e)}`);return}return n.send(l)}}),n.get(`${e}`,async(e,n)=>{let r=t.u();n.raw.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}),n.raw.write(t.d({jsonrpc:`2.0`,method:`mcp/ready`,params:{protocol:`streamable-http`}},r,15e3));let i=setInterval(()=>{n.raw.write(`: keep-alive
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../utils-CDExg9uP.cjs`),t=require(`../mcp-transport-Dmf2vbIb.cjs`);var n=function(n,r,i){let{cubes:a,drizzle:o,schema:s,extractSecurityContext:c,engineType:l,cors:u,basePath:d=`/cubejs-api/v1`,bodyLimit:f=10485760,cache:p,mcp:m={enabled:!0},agent:h}=r;if(!a||a.length===0)return i(Error(`At least one cube must be provided in the cubes array`));u&&n.register(import(`@fastify/cors`),u),n.addHook(`onRequest`,async(e,t)=>{e.method===`POST`&&(e.body=void 0)});let g=new t.h({drizzle:o,schema:s,engineType:l,cache:p,rlsSetup:r.rlsSetup});if(a.forEach(e=>{g.registerCube(e)}),n.post(`${d}/load`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(t,n)=>{try{let r=t.body,i=r.query||r,a=await c(t),o=g.validateQuery(i);if(!o.isValid)return n.status(400).send(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=t.headers[`x-cache-control`]===`no-cache`;return e.r(i,await g.executeMultiCubeQuery(i,a,{skipCache:s}),g)}catch(r){return t.log.error(r,`Query execution error`),n.status(500).send(e.i(r instanceof Error?r.message:`Query execution failed`,500))}}),n.get(`${d}/load`,{schema:{querystring:{type:`object`,properties:{query:{type:`string`}},required:[`query`]}}},async(t,n)=>{try{let{query:r}=t.query,i;try{i=JSON.parse(r)}catch{return n.status(400).send(e.i(`Invalid JSON in query parameter`,400))}let a=await c(t),o=g.validateQuery(i);if(!o.isValid)return n.status(400).send(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=t.headers[`x-cache-control`]===`no-cache`,l=await g.executeMultiCubeQuery(i,a,{skipCache:s});return e.r(i,l,g)}catch(r){return t.log.error(r,`Query execution error`),n.status(500).send(e.i(r instanceof Error?r.message:`Query execution failed`,500))}}),n.post(`${d}/batch`,{bodyLimit:f,schema:{body:{type:`object`,required:[`queries`],properties:{queries:{type:`array`,items:{type:`object`}}}}}},async(t,n)=>{try{let{queries:r}=t.body;return!r||!Array.isArray(r)?n.status(400).send(e.i(`Request body must contain a "queries" array`,400)):r.length===0?n.status(400).send(e.i(`Queries array cannot be empty`,400)):await e.u(r,await c(t),g,{skipCache:t.headers[`x-cache-control`]===`no-cache`})}catch(r){return t.log.error(r,`Batch execution error`),n.status(500).send(e.i(r instanceof Error?r.message:`Batch execution failed`,500))}}),n.get(`${d}/meta`,async(t,n)=>{try{return e.a(g.getMetadata())}catch(r){return t.log.error(r,`Metadata error`),n.status(500).send(e.i(r instanceof Error?r.message:`Failed to fetch metadata`,500))}}),n.post(`${d}/sql`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(t,n)=>{try{let r=t.body,i=await c(t),a=g.validateQuery(r);if(!a.isValid)return n.status(400).send(e.i(`Query validation failed: ${a.errors.join(`, `)}`,400));let o=r.measures?.[0]||r.dimensions?.[0];if(!o)return n.status(400).send(e.i(`No measures or dimensions specified`,400));let s=o.split(`.`)[0];return e.o(r,await g.generateSQL(s,r,i))}catch(r){return t.log.error({err:String(r).replace(/\n|\r/g,``)},`SQL generation error`),n.status(500).send(e.i(r instanceof Error?r.message:`SQL generation failed`,500))}}),n.get(`${d}/sql`,{schema:{querystring:{type:`object`,properties:{query:{type:`string`}},required:[`query`]}}},async(t,n)=>{try{let{query:r}=t.query,i=JSON.parse(r),a=await c(t),o=g.validateQuery(i);if(!o.isValid)return n.status(400).send(e.i(`Query validation failed: ${o.errors.join(`, `)}`,400));let s=i.measures?.[0]||i.dimensions?.[0];if(!s)return n.status(400).send(e.i(`No measures or dimensions specified`,400));let l=s.split(`.`)[0];return e.o(i,await g.generateSQL(l,i,a))}catch(r){return t.log.error({err:String(r).replace(/\n|\r/g,``)},`SQL generation error`),n.status(500).send(e.i(r instanceof Error?r.message:`SQL generation failed`,500))}}),n.post(`${d}/dry-run`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(t,n)=>{try{let n=t.body;return await e.f(n.query||n,await c(t),g)}catch(e){return t.log.error(e,`Dry-run error`),n.status(400).send({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1})}}),n.get(`${d}/dry-run`,{schema:{querystring:{type:`object`,properties:{query:{type:`string`}},required:[`query`]}}},async(t,n)=>{try{let{query:n}=t.query;return await e.f(JSON.parse(n),await c(t),g)}catch(e){return t.log.error(e,`Dry-run error`),n.status(400).send({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1})}}),n.post(`${d}/explain`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(e,t)=>{try{let n=e.body,r=n.query||n,i=n.options||{},a=await c(e),o=g.validateQuery(r);return o.isValid?await g.explainQuery(r,a,i):t.status(400).send({error:`Query validation failed: ${o.errors.join(`, `)}`})}catch(n){return e.log.error(n,`Explain error`),t.status(500).send({error:n instanceof Error?n.message:`Explain query failed`})}}),h&&n.post(`${d}/agent/chat`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(e,t)=>{try{let{handleAgentChat:n}=await Promise.resolve().then(()=>require(`../handler-DzUX7CBs.cjs`)),{message:r,sessionId:i,history:a}=e.body;if(!r||typeof r!=`string`)return t.status(400).send({error:`message is required and must be a string`});let o=(h.apiKey||``).trim();if(h.allowClientApiKey){let t=e.headers[`x-agent-api-key`];t&&(o=t.trim())}if(!o)return t.status(401).send({error:`No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header.`});let s=h.allowClientApiKey?e.headers[`x-agent-provider`]:void 0,l=h.allowClientApiKey?e.headers[`x-agent-model`]:void 0,u=h.allowClientApiKey?e.headers[`x-agent-provider-endpoint`]:void 0,d=await c(e),f=h.buildSystemContext?.(d);t.raw.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`});try{let e=n({message:r,sessionId:i,history:a,semanticLayer:g,securityContext:d,agentConfig:h,apiKey:o,systemContext:f,providerOverride:s,modelOverride:l,baseURLOverride:u});for await(let n of e)t.raw.write(`data: ${JSON.stringify(n)}\n\n`)}catch(e){let n={type:`error`,data:{message:e instanceof Error?e.message:`Stream failed`}};t.raw.write(`data: ${JSON.stringify(n)}\n\n`)}finally{t.raw.end()}}catch(n){if(e.log.error(n,`Agent chat error`),!t.raw.headersSent)return t.status(500).send({error:n instanceof Error?n.message:`Agent chat failed`})}}),m.enabled!==!1){let e=m.basePath??`/mcp`;n.post(`${e}`,{bodyLimit:f,schema:{body:{type:`object`,additionalProperties:!0}}},async(e,n)=>{let r=t.p(e.headers.origin,m.allowedOrigins?{allowedOrigins:m.allowedOrigins}:{});if(!r.valid)return n.status(403).send(t.n(null,-32600,r.reason));let i=e.headers.accept;if(!t.f(i))return n.status(400).send(t.n(null,-32600,`Accept header must include both application/json and text/event-stream`));let a=t.c(e.headers);if(!a.ok)return n.status(426).send({error:`Unsupported MCP protocol version`,supported:a.supported});let o=t.l(e.body);if(!o)return n.status(400).send(t.n(null,-32600,`Invalid JSON-RPC 2.0 request`));let s=t.m(i),l=o.method===`initialize`;try{let r=await t.i(o.method,o.params,{semanticLayer:g,extractSecurityContext:c,rawRequest:e,rawResponse:n,negotiatedProtocol:a.negotiated});if(t.s(o))return n.status(202).send();let i=l&&r&&typeof r==`object`&&`sessionId`in r?r.sessionId:void 0;i&&n.header(t.t,i);let u=t.r(o.id??null,r);if(s){let e=t.u();n.header(`Content-Type`,`text/event-stream`).header(`Cache-Control`,`no-cache`).header(`Connection`,`keep-alive`).send(`id: ${e}\n\n${t.d(u,e)}`);return}return n.send(u)}catch(r){if(t.s(o))return e.log.error({err:String(r).replace(/\n|\r/g,``)},`MCP notification processing error`),n.status(202).send();e.log.error({err:String(r).replace(/\n|\r/g,``)},`MCP RPC error`);let i=r?.code??-32603,a=r?.data,c=r.message||`MCP request failed`,l=t.n(o.id??null,i,c,a);if(s){let e=t.u();n.header(`Content-Type`,`text/event-stream`).header(`Cache-Control`,`no-cache`).header(`Connection`,`keep-alive`).send(`id: ${e}\n\n${t.d(l,e)}`);return}return n.send(l)}}),n.get(`${e}`,async(e,n)=>{let r=t.u();n.raw.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}),n.raw.write(t.d({jsonrpc:`2.0`,method:`mcp/ready`,params:{protocol:`streamable-http`}},r,15e3));let i=setInterval(()=>{n.raw.write(`: keep-alive
2
2
 
3
3
  `)},15e3);e.raw.on(`close`,()=>{clearInterval(i)})}),n.delete(`${e}`,async(e,t)=>t.status(405).send({error:`Session termination not supported`}))}n.setErrorHandler(async(t,n,r)=>(n.log.error(t,`Fastify cube adapter error`),r.statusCode<400&&r.status(500),e.i(t instanceof Error?t:String(t),r.statusCode))),i()};async function r(e,t){await e.register(n,t)}function i(e){let t=require(`fastify`)({logger:!0});return t.register(n,e),t}exports.createCubeApp=i,exports.cubePlugin=n,exports.registerCubeRoutes=r;
@@ -1,6 +1,6 @@
1
1
  import { FastifyPluginCallback, FastifyRequest, FastifyInstance } from 'fastify';
2
2
  import { FastifyCorsOptions } from '@fastify/cors';
3
- import { SemanticQuery, SecurityContext, DatabaseExecutor, DrizzleDatabase, Cube, CacheConfig } from '../../server';
3
+ import { SemanticQuery, SecurityContext, DatabaseExecutor, DrizzleDatabase, Cube, CacheConfig, RLSSetupFn } from '../../server';
4
4
  import { AgentConfig } from '../../server/agent/types';
5
5
  import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
6
6
  import { MySql2Database } from 'drizzle-orm/mysql2';
@@ -79,6 +79,12 @@ export interface FastifyAdapterOptions {
79
79
  * Requires `@anthropic-ai/sdk` as a peer dependency.
80
80
  */
81
81
  agent?: AgentConfig;
82
+ /**
83
+ * Row-Level Security setup function.
84
+ * When provided, every query execution opens a transaction, calls this function
85
+ * to configure RLS (e.g., set JWT claims and switch Postgres roles), then runs the query.
86
+ */
87
+ rlsSetup?: RLSSetupFn;
82
88
  }
83
89
  /**
84
90
  * Fastify plugin for Cube.js-compatible API
@@ -1,5 +1,5 @@
1
- import { a as e, f as t, g as n, i as r, o as i, r as a, u as o } from "../utils-B7VkyzMv.js";
2
- import { c as s, d as c, f as l, h as u, i as d, l as f, m as p, n as m, p as h, r as g, s as _, t as v, u as y } from "../mcp-transport-DWSNkwUY.js";
1
+ import { a as e, f as t, g as n, i as r, o as i, r as a, u as o } from "../utils-DkKcpkx5.js";
2
+ import { c as s, d as c, f as l, h as u, i as d, l as f, m as p, n as m, p as h, r as g, s as _, t as v, u as y } from "../mcp-transport-Cdisv8il.js";
3
3
  //#region src/adapters/fastify/index.ts
4
4
  var b = function(n, b, x) {
5
5
  let { cubes: S, drizzle: C, schema: w, extractSecurityContext: T, engineType: E, cors: D, basePath: O = "/cubejs-api/v1", bodyLimit: k = 10485760, cache: A, mcp: j = { enabled: !0 }, agent: M } = b;
@@ -11,7 +11,8 @@ var b = function(n, b, x) {
11
11
  drizzle: C,
12
12
  schema: w,
13
13
  engineType: E,
14
- cache: A
14
+ cache: A,
15
+ rlsSetup: b.rlsSetup
15
16
  });
16
17
  if (S.forEach((e) => {
17
18
  N.registerCube(e);
@@ -155,7 +156,7 @@ var b = function(n, b, x) {
155
156
  } }
156
157
  }, async (e, t) => {
157
158
  try {
158
- let { handleAgentChat: n } = await import("../handler-rPpxuopb.js"), { message: r, sessionId: i, history: a } = e.body;
159
+ let { handleAgentChat: n } = await import("../handler-J55KQKe5.js"), { message: r, sessionId: i, history: a } = e.body;
159
160
  if (!r || typeof r != "string") return t.status(400).send({ error: "message is required and must be a string" });
160
161
  let o = (M.apiKey || "").trim();
161
162
  if (M.allowClientApiKey) {
@@ -1,4 +1,4 @@
1
- const e=require(`./utils-BLFzzCI9.cjs`),t=require(`./mcp-prompts-DsAkafVn.cjs`);function n(e){if(e.length===0)return`No cubes are currently available.`;let t=[`## Available Cubes`,``];for(let n of e){if(t.push(`### ${n.name}`),n.description&&t.push(n.description),n.measures&&n.measures.length>0){t.push(``),t.push(`**Measures:**`);for(let e of n.measures){let r=e.description?` - ${e.description}`:``;t.push(`- \`${n.name}.${e.name}\` (${e.type})${r}`)}}if(n.dimensions&&n.dimensions.length>0){t.push(``),t.push(`**Dimensions:**`);for(let e of n.dimensions){let r=e.description?` - ${e.description}`:``;t.push(`- \`${n.name}.${e.name}\` (${e.type})${r}`)}}if(n.relationships&&n.relationships.length>0){t.push(``),t.push(`**Joins:**`);for(let e of n.relationships)t.push(`- → \`${e.targetCube}\` (${e.relationship})`)}n.meta?.eventStream&&(t.push(``),t.push(`**Event Stream:** Yes (supports funnel, flow, retention queries)`),n.meta.eventStream.bindingKey&&t.push(`- Binding key: \`${n.name}.${n.meta.eventStream.bindingKey}\``),n.meta.eventStream.timeDimension&&t.push(`- Time dimension: \`${n.name}.${n.meta.eventStream.timeDimension}\``)),t.push(``)}return t.join(`
1
+ const e=require(`./utils-CDExg9uP.cjs`),t=require(`./mcp-prompts-DsAkafVn.cjs`);function n(e){if(e.length===0)return`No cubes are currently available.`;let t=[`## Available Cubes`,``];for(let n of e){if(t.push(`### ${n.name}`),n.description&&t.push(n.description),n.measures&&n.measures.length>0){t.push(``),t.push(`**Measures:**`);for(let e of n.measures){let r=e.description?` - ${e.description}`:``;t.push(`- \`${n.name}.${e.name}\` (${e.type})${r}`)}}if(n.dimensions&&n.dimensions.length>0){t.push(``),t.push(`**Dimensions:**`);for(let e of n.dimensions){let r=e.description?` - ${e.description}`:``;t.push(`- \`${n.name}.${e.name}\` (${e.type})${r}`)}}if(n.relationships&&n.relationships.length>0){t.push(``),t.push(`**Joins:**`);for(let e of n.relationships)t.push(`- → \`${e.targetCube}\` (${e.relationship})`)}n.meta?.eventStream&&(t.push(``),t.push(`**Event Stream:** Yes (supports funnel, flow, retention queries)`),n.meta.eventStream.bindingKey&&t.push(`- Binding key: \`${n.name}.${n.meta.eventStream.bindingKey}\``),n.meta.eventStream.timeDimension&&t.push(`- Time dimension: \`${n.name}.${n.meta.eventStream.timeDimension}\``)),t.push(``)}return t.join(`
2
2
  `)}function r(e){return e.messages.map(e=>e.content.text).join(`
3
3
 
4
4
  `)}function i(e){return[`# Drizzle Cube Analytics Agent`,``,`You are an analytics agent that helps users explore and visualize data.`,`You have access to a semantic layer with cubes (data models) that you can query.`,``,`## Your Workflow`,``,`For EACH insight, follow this cycle — do NOT batch all queries first:`,``,"1. **Discover** available cubes using `discover_cubes` (once at the start)",`2. **For each analysis point**, repeat this cycle:`," a. `execute_query` — get the data"," b. `add_markdown` — explain the results and insight"," c. `add_portlet` — visualize the results",``,`Call all three (query → markdown → portlet) in a single turn before moving on to the next analysis.`,`Do NOT run multiple queries first and add charts later — the user sees results in real-time.`,``,`## Important Guidelines`,``,`- ALWAYS discover cubes first before attempting queries`,"- Field names MUST be `CubeName.fieldName` with a DOT separator (e.g. `PullRequests.count`, `Teams.name`). NEVER use underscores, NEVER use just the cube name as a field — `PullRequests.PullRequests` and `Teams_count` are WRONG.",`- Order keys MUST be one of the measures or dimensions already listed in that query. You CANNOT order by a field that is not in measures or dimensions — add it to measures first, or remove it from order.`,"- After EVERY `execute_query`, IMMEDIATELY call `add_markdown` and `add_portlet` in the SAME turn — never defer visualizations to a later turn",`- Choose appropriate chart types: bar for categories, line for trends, table for detailed data`,`- If a query fails, explain the error and try an alternative approach`,``,`## Output Format Rules`,``,`### CRITICAL: Always think before acting`,`- EVERY single turn MUST begin with a text message (1-2 sentences) BEFORE any tool calls. This is your #1 rule — never violate it.`,`- This applies to EVERY turn, including turns where you are adding visualizations or explanations to the notebook.`,`- Even when adding multiple charts in sequence, each turn must start with a brief status like "Now I'll chart the productivity breakdown." or "Next, let me show the department comparison."`,`- Example good turn: "Let me see what data is available." → discover_cubes`,`- Example good turn: "I'll add a chart showing the top employees." → add_markdown → add_portlet`,`- Example bad turn: (no text) → add_portlet ← NEVER do this`,``,`### Text vs Notebook`,"- ALL analysis, findings, methodology, and insights MUST go through `add_markdown` tool calls — never in your text responses",`- Your text responses must be 1-2 short sentences (under 50 words) summarizing what you are about to do next — status updates only`,`- Never use markdown formatting (headers, bullets, bold, code blocks) in text responses — plain sentences only`,`- Write text responses as a friendly analyst would — use plain business language the user understands`,`- NEVER mention internal terms like "cube", "query syntax", "field names", "measures", "dimensions", "portlet", "prefix format", or tool names in text responses`,`- Instead of "Let me correct the query syntax and retry" → "Let me fix that and try again"`,`- Instead of "I'll query the PullRequests cube" → "I'll look at the pull request data"`,`- Instead of "Adding a portlet with the results" → "Here's a chart of the results"`,``,`### Notebook content rules`,"- Before each `add_portlet`, ALWAYS call `add_markdown` first to explain WHY you are adding this visualization and what it shows","- Before calling `add_portlet`, verify the query is valid: all fields in `order` must also appear in `measures` or `dimensions`",'- Never put data tables in markdown blocks — use `add_portlet` with chartType "table" instead',"- Think out loud in the notebook: use `add_markdown` to share your reasoning at each step so users can follow along",`- NEVER use emojis in text responses or markdown content — no 📊, 📈, ✅, 🔍, etc. Write in plain, professional language.`,``,`## Chart Selection Guide`,``,`Choose the chart type that best communicates the answer to the user's question. Think about what the data represents and what insight the user needs — do NOT default to the first option in this table. Consider the number of data points, whether values are categorical or temporal, and whether the user is comparing, trending, or summarizing.`,``,`| Intent / Data Shape | Chart Type |`,`|---|---|`,"| Compare discrete categories or rankings | `bar` |","| Trend over time (one or few series) | `line` |","| Trend over time showing volume/magnitude | `area` |","| Part-of-whole breakdown | `pie` (≤7 slices) |","| Correlation between two measures | `scatter` |","| Correlation with size/color third dimension | `bubble` |","| Intensity across two categorical dimensions | `heatmap` |","| Multi-variable comparison across categories | `radar` |","| Distribution/spread of values | `boxPlot` |","| Detailed row-level data or many columns | `table` |","| Single headline number — ONLY when user explicitly asks for a KPI card or single number | `kpiNumber` |","| Headline metric with period-over-period change — ONLY when user asks about change in a single metric | `kpiDelta` |",``,`Analysis-mode-specific chart types (require the corresponding analysis mode):`,``,`| Analysis Mode | Chart Type | Description |`,`|---|---|---|`,"| Funnel | `funnel` | Sequential step conversion bars with conversion rates |","| Flow | `sankey` | Flow diagram showing paths between states/steps |","| Flow | `sunburst` | Radial rings showing forward paths from a starting event |","| Retention | `retentionHeatmap` | Cohort × period retention matrix |","| Retention | `retentionCombined` | Retention with line chart, heatmap, or combined modes |",``,'**Chart selection priorities:** Default to `bar` for categories, `line` for time series, `table` for exploratory data. Use `kpiNumber`/`kpiDelta` only as a last resort — they are appropriate only when the user explicitly asks for a single headline number or KPI card. If the query returns multiple rows or the user asks a general question like "show me revenue", prefer `bar` or `table` over `kpiNumber`.',``,`## Chart Axis Configuration Rules`,``,"**Bar charts MUST have an xAxis.** Put a dimension in `chartConfig.xAxis` so bars have category labels. If your query has no dimensions, add one or use `table` instead.",``,"**Never duplicate xAxis in series.** Putting the same dimension in both `xAxis` and `series` creates a sparse, broken-looking chart. The `series` field is ONLY for splitting bars into grouped/stacked sub-series by a SECOND dimension.",``,`Correct bar chart examples:`,'- Categories only: `xAxis: ["Cube.category"], yAxis: ["Cube.count"]` — no series needed','- Grouped bars: `xAxis: ["Cube.category"], yAxis: ["Cube.count"], series: ["Cube.status"]` — series is a DIFFERENT dimension','- Multiple measures: `xAxis: ["Cube.category"], yAxis: ["Cube.count", "Cube.total"]` — each measure becomes a bar group',``,`Wrong:`,'- `xAxis: [], yAxis: ["Cube.avg1", "Cube.avg2"]` — missing xAxis, bars have no labels','- `xAxis: ["Cube.size"], series: ["Cube.size"]` — same field in both, creates sparse chart',``,`## Analysis Mode Decision Tree`,``,`The default mode is **query** (standard measures/dimensions). Switch to a special mode only when the user's question matches:`,``,`- **Funnel mode** — "What is the conversion rate from step A → B → C?"`," - Requires: an event-stream cube with `capabilities.funnel = true` from `discover_cubes`"," - Execute: `execute_query` with `funnel` param:",' `{ bindingKey: "Events.userId", timeDimension: "Events.timestamp", steps: [{ name: "Signup", filter: { member: "Events.eventName", operator: "equals", values: ["signup"] }}, { name: "Purchase", filter: { member: "Events.eventName", operator: "equals", values: ["purchase"] }}] }`',' - Visualize: `add_portlet` with `chartType: "funnel"` and `query` as JSON string containing `{ "funnel": { ... } }`',``,`- **Flow mode** — "What paths do users take after signup?"`," - Requires: `capabilities.flow = true` from `discover_cubes`"," - Execute: `execute_query` with `flow` param:",' `{ bindingKey: "Events.userId", timeDimension: "Events.timestamp", eventDimension: "Events.eventName", startingStep: { name: "Signup", filter: { member: "Events.eventName", operator: "equals", values: ["signup"] }}, stepsBefore: 0, stepsAfter: 3 }`',' - Visualize: `add_portlet` with `chartType: "sankey"` (or `"sunburst"`) and `query` as JSON string containing `{ "flow": { ... } }`',``,`- **Retention mode** — "What % of users come back after 7 days?"`," - Requires: `capabilities.retention = true` from `discover_cubes`"," - Execute: `execute_query` with `retention` param:",' `{ timeDimension: "Events.timestamp", bindingKey: "Events.userId", dateRange: { start: "2024-01-01", end: "2024-03-31" }, granularity: "week", periods: 8, retentionType: "classic" }`',' - Visualize: `add_portlet` with `chartType: "retentionCombined"` (or `"retentionHeatmap"`) and `query` as JSON string containing `{ "retention": { ... } }`',``,"Before using funnel/flow/retention, check the `capabilities` object returned by `discover_cubes`. If the required capability is `false`, explain to the user that the data model does not support that analysis mode.",``,`Event-stream cubes are marked in the Available Cubes section below with **Event Stream: Yes** and list their binding key and time dimension.`,``,`---`,``,r(t.n),``,`---`,``,r(t.i),``,`---`,``,r(t.r),``,`---`,``,r(t.t),``,`---`,``,`## Save as Dashboard`,``,"When the user asks to save, export, or convert the notebook into a dashboard, use the `save_as_dashboard` tool.",``,`### Layout Rules`,`- Dashboard grid is 12 columns wide`,`- KPI cards: w=3, h=3 — place at the top in a row of 4`,`- Overview charts (bar, line, area): w=6, h=4`,`- Wide charts (heatmap, table): w=12, h=5`,`- Section headers (markdown): w=12, h=1`,``,`### Section Headers`,'Use `chartType: "markdown"` portlets as section headers to organize the dashboard:',"```json",`{`,` "id": "header-overview",`,` "title": "Overview",`,` "chartType": "markdown",`,` "displayConfig": {`,` "content": "## Overview",`,` "hideHeader": true,`,` "transparentBackground": true,`,` "autoHeight": true`,` },`,` "w": 12, "h": 1, "x": 0, "y": 0`,`}`,"```",``,`### Dashboard Filters`,"- ALWAYS include a universal date filter with `isUniversalTime: true`",`- Add dimension filters for key fields used across portlets (e.g., department, status, region)`,`- Use human-readable labels (e.g., "Department" not "Employees.departmentName")`,"- Map filters to portlets using `dashboardFilterMapping` — list the filter IDs that apply",`- When promoting a hardcoded filter to a dashboard filter, REMOVE that filter from the portlet query`,``,`### Analysis Types`,'- Standard query portlets: `analysisType: "query"` (default)','- Funnel portlets: `analysisType: "funnel"`, query contains `{ "funnel": {...} }`, chartType `"funnel"`','- Flow portlets: `analysisType: "flow"`, query contains `{ "flow": {...} }`, chartType `"sankey"` or `"sunburst"`','- Retention portlets: `analysisType: "retention"`, query contains `{ "retention": {...} }`, chartType `"retentionHeatmap"` or `"retentionCombined"`',``,`### CRITICAL: Only use portlets from the notebook`,"- ONLY include portlets that you already added to the notebook via `add_portlet` during this conversation",`- Do NOT invent new queries or charts that were not part of the analysis — the dashboard is a direct conversion of the notebook`,`- Reuse the exact same queries, chart types, and chart configs from the notebook portlets`,`- Arrange the existing portlets in a sensible layout (KPIs at top, charts in middle, tables at bottom)`,`- You may add section header markdown portlets to organize the layout, but do not add new data portlets`,``,`---`,``,n(e)].join(`
@@ -1,4 +1,4 @@
1
- import { d as e, p as t } from "./utils-B7VkyzMv.js";
1
+ import { d as e, p as t } from "./utils-DkKcpkx5.js";
2
2
  import { i as n, n as r, r as i, t as a } from "./mcp-prompts-BAutSQYA.js";
3
3
  //#region src/server/agent/system-prompt.ts
4
4
  function o(e) {
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../utils-BLFzzCI9.cjs`),t=require(`../mcp-transport-DPpei63d.cjs`);let n=require(`hono`);var r=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`],allowHeaders:[],exposeHeaders:[],...e},n=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),r=(e=>typeof e==`function`?e:Array.isArray(e)?()=>e:()=>[])(t.allowMethods);return async function(e,i){function a(t,n){e.res.headers.set(t,n)}let o=await n(e.req.header(`origin`)||``,e);if(o&&a(`Access-Control-Allow-Origin`,o),t.credentials&&a(`Access-Control-Allow-Credentials`,`true`),t.exposeHeaders?.length&&a(`Access-Control-Expose-Headers`,t.exposeHeaders.join(`,`)),e.req.method===`OPTIONS`){t.origin!==`*`&&a(`Vary`,`Origin`),t.maxAge!=null&&a(`Access-Control-Max-Age`,t.maxAge.toString());let n=await r(e.req.header(`origin`)||``,e);n.length&&a(`Access-Control-Allow-Methods`,n.join(`,`));let i=t.allowHeaders;if(!i?.length){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(/\s*,\s*/))}return i?.length&&(a(`Access-Control-Allow-Headers`,i.join(`,`)),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await i(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};function i(i){let{cubes:a,drizzle:o,schema:s,extractSecurityContext:c,engineType:l,cors:u,basePath:d=`/cubejs-api/v1`,cache:f,mcp:p={enabled:!0},agent:m}=i;if(!i.semanticLayer&&(!a||a.length===0))throw Error(`Either semanticLayer or a non-empty cubes array must be provided`);let h=new n.Hono;u&&h.use(`/*`,r(u));let g=i.semanticLayer??new t.h({drizzle:o,schema:s,engineType:l,cache:f});if(!i.semanticLayer&&a&&a.forEach(e=>{g.registerCube(e)}),h.post(`${d}/load`,async t=>{try{let n=await t.req.json(),r=n.query||n,i=await c(t),a=g.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=t.req.header(`x-cache-control`)===`no-cache`,s=await g.executeMultiCubeQuery(r,i,{skipCache:o});return t.json(e.r(r,s,g))}catch(e){return console.error(`Query execution error:`,e),t.json({error:e instanceof Error?e.message:`Query execution failed`},500)}}),h.get(`${d}/load`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`},400);let r;try{r=JSON.parse(n)}catch{return t.json({error:`Invalid JSON in query parameter`},400)}let i=await c(t),a=g.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=t.req.header(`x-cache-control`)===`no-cache`,s=await g.executeMultiCubeQuery(r,i,{skipCache:o});return t.json(e.r(r,s,g))}catch(e){return console.error(`Query execution error:`,e),t.json({error:e instanceof Error?e.message:`Query execution failed`},500)}}),h.post(`${d}/batch`,async t=>{try{let{queries:n}=await t.req.json();if(!n||!Array.isArray(n))return t.json({error:`Request body must contain a "queries" array`},400);if(n.length===0)return t.json({error:`Queries array cannot be empty`},400);let r=await e.u(n,await c(t),g,{skipCache:t.req.header(`x-cache-control`)===`no-cache`});return t.json(r)}catch(e){return console.error(`Batch execution error:`,e),t.json({error:e instanceof Error?e.message:`Batch execution failed`},500)}}),h.get(`${d}/meta`,t=>{try{let n=g.getMetadata();return t.json(e.a(n))}catch(e){return console.error(`Metadata error:`,e),t.json({error:e instanceof Error?e.message:`Failed to fetch metadata`},500)}}),h.post(`${d}/sql`,async t=>{try{let n=await t.req.json(),r=await c(t),i=g.validateQuery(n);if(!i.isValid)return t.json({error:`Query validation failed: ${i.errors.join(`, `)}`},400);let a=n.measures?.[0]||n.dimensions?.[0];if(!a)return t.json({error:`No measures or dimensions specified`},400);let o=a.split(`.`)[0],s=await g.generateSQL(o,n,r);return t.json(e.o(n,s))}catch(e){return console.error(`SQL generation error:`,e),t.json({error:e instanceof Error?e.message:`SQL generation failed`},500)}}),h.get(`${d}/sql`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`},400);let r=JSON.parse(n),i=await c(t),a=g.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=r.measures?.[0]||r.dimensions?.[0];if(!o)return t.json({error:`No measures or dimensions specified`},400);let s=o.split(`.`)[0],l=await g.generateSQL(s,r,i);return t.json(e.o(r,l))}catch(e){return console.error(`SQL generation error:`,e),t.json({error:e instanceof Error?e.message:`SQL generation failed`},500)}}),h.post(`${d}/dry-run`,async t=>{try{let n=await t.req.json(),r=await e.f(n.query||n,await c(t),g);return t.json(r)}catch(e){return console.error(`Dry-run error:`,e),t.json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1},400)}}),h.get(`${d}/dry-run`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`,valid:!1},400);let r=await e.f(JSON.parse(n),await c(t),g);return t.json(r)}catch(e){return console.error(`Dry-run error:`,e),t.json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1},400)}}),h.post(`${d}/explain`,async e=>{try{let t=await e.req.json(),n=t.query||t,r=t.options||{},i=await c(e),a=g.validateQuery(n);if(!a.isValid)return e.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=await g.explainQuery(n,i,r);return e.json(o)}catch(t){return console.error(`Explain error:`,t),e.json({error:t instanceof Error?t.message:`Explain query failed`},500)}}),m&&h.post(`${d}/agent/chat`,async e=>{try{let{handleAgentChat:t}=await Promise.resolve().then(()=>require(`../handler-ClgB__a-.cjs`)),{message:n,sessionId:r,history:i}=await e.req.json();if(!n||typeof n!=`string`)return e.json({error:`message is required and must be a string`},400);let a=(m.apiKey||``).trim();if(m.allowClientApiKey){let t=e.req.header(`x-agent-api-key`);t&&(a=t.trim())}if(!a)return e.json({error:`No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header.`},401);let o=m.allowClientApiKey?e.req.header(`x-agent-provider`):void 0,s=m.allowClientApiKey?e.req.header(`x-agent-model`):void 0,l=m.allowClientApiKey?e.req.header(`x-agent-provider-endpoint`):void 0,u=await c(e),d=m.buildSystemContext?.(u),f=new TextEncoder,p=new ReadableStream({async start(e){try{let c=t({message:n,sessionId:r,history:i,semanticLayer:g,securityContext:u,agentConfig:m,apiKey:a,systemContext:d,providerOverride:o,modelOverride:s,baseURLOverride:l});for await(let t of c){let n=`data: ${JSON.stringify(t)}\n\n`;e.enqueue(f.encode(n))}}catch(t){let n={type:`error`,data:{message:t instanceof Error?t.message:`Stream failed`}};e.enqueue(f.encode(`data: ${JSON.stringify(n)}\n\n`))}finally{e.close()}}});return new Response(p,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})}catch(t){return console.error(`Agent chat error:`,t),e.json({error:t instanceof Error?t.message:`Agent chat failed`},500)}}),p.enabled!==!1){let e={uri:`drizzle-cube://schema`,name:`Cube Schema`,description:`Current cube metadata as JSON`,mimeType:`application/json`,text:JSON.stringify(g.getMetadata(),null,2)},n=[...t.o(),e],r=t.a(),i=p.basePath??`/mcp`;h.post(`${i}`,async e=>{let i=t.p(e.req.header(`origin`),p.allowedOrigins?{allowedOrigins:p.allowedOrigins}:{});if(!i.valid)return e.json(t.n(null,-32600,i.reason),403);let a=e.req.header(`accept`);if(!t.f(a))return e.json(t.n(null,-32600,`Accept header must include both application/json and text/event-stream`),400);let o=t.c(e.req.header());if(!o.ok)return e.json({error:`Unsupported MCP protocol version`,supported:o.supported},426);let s=t.l(await e.req.json().catch(()=>null));if(!s)return e.json(t.n(null,-32600,`Invalid JSON-RPC 2.0 request`),400);let l=t.m(a),u=s.method===`initialize`;try{let i=await t.i(s.method,s.params,{semanticLayer:g,extractSecurityContext:c,rawRequest:e,rawResponse:null,negotiatedProtocol:o.negotiated,resources:n,prompts:r});if(t.s(s))return e.body(null,202);let a=t.r(s.id??null,i),d=u&&i&&typeof i==`object`&&`sessionId`in i?i.sessionId:void 0,f={};if(d&&(f[t.t]=d),l){let e=new TextEncoder,n=t.u(),r=new ReadableStream({start(r){r.enqueue(e.encode(`id: ${n}\n\n`)),r.enqueue(e.encode(t.d(a,n))),r.close()}});return new Response(r,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`,...f}})}return e.json(a,200,f)}catch(n){if(t.s(s))return console.error(`MCP notification processing error:`,n),e.body(null,202);console.error(`MCP RPC error:`,n);let r=n?.code??-32603,i=n?.data,a=n.message||`MCP request failed`,o=t.n(s.id??null,r,a,i);if(l){let e=new TextEncoder,n=t.u(),r=new ReadableStream({start(r){r.enqueue(e.encode(`id: ${n}\n\n`)),r.enqueue(e.encode(t.d(o,n))),r.close()}});return new Response(r,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})}return e.json(o,200)}}),h.delete(`${i}`,e=>e.json({error:`Session termination not supported`},405)),h.get(`${i}`,e=>{let n=new TextEncoder,r=t.u(),i,a=new ReadableStream({start(e){e.enqueue(n.encode(t.d({jsonrpc:`2.0`,method:`mcp/ready`,params:{protocol:`streamable-http`}},r,15e3))),i=setInterval(()=>{e.enqueue(n.encode(`: keep-alive
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../utils-CDExg9uP.cjs`),t=require(`../mcp-transport-Dmf2vbIb.cjs`);let n=require(`hono`);var r=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`],allowHeaders:[],exposeHeaders:[],...e},n=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),r=(e=>typeof e==`function`?e:Array.isArray(e)?()=>e:()=>[])(t.allowMethods);return async function(e,i){function a(t,n){e.res.headers.set(t,n)}let o=await n(e.req.header(`origin`)||``,e);if(o&&a(`Access-Control-Allow-Origin`,o),t.credentials&&a(`Access-Control-Allow-Credentials`,`true`),t.exposeHeaders?.length&&a(`Access-Control-Expose-Headers`,t.exposeHeaders.join(`,`)),e.req.method===`OPTIONS`){t.origin!==`*`&&a(`Vary`,`Origin`),t.maxAge!=null&&a(`Access-Control-Max-Age`,t.maxAge.toString());let n=await r(e.req.header(`origin`)||``,e);n.length&&a(`Access-Control-Allow-Methods`,n.join(`,`));let i=t.allowHeaders;if(!i?.length){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(/\s*,\s*/))}return i?.length&&(a(`Access-Control-Allow-Headers`,i.join(`,`)),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await i(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};function i(i){let{cubes:a,drizzle:o,schema:s,extractSecurityContext:c,engineType:l,cors:u,basePath:d=`/cubejs-api/v1`,cache:f,mcp:p={enabled:!0},agent:m}=i;if(!i.semanticLayer&&(!a||a.length===0))throw Error(`Either semanticLayer or a non-empty cubes array must be provided`);let h=new n.Hono;u&&h.use(`/*`,r(u));let g=i.semanticLayer??new t.h({drizzle:o,schema:s,engineType:l,cache:f,rlsSetup:i.rlsSetup});if(!i.semanticLayer&&a&&a.forEach(e=>{g.registerCube(e)}),h.post(`${d}/load`,async t=>{try{let n=await t.req.json(),r=n.query||n,i=await c(t),a=g.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=t.req.header(`x-cache-control`)===`no-cache`,s=await g.executeMultiCubeQuery(r,i,{skipCache:o});return t.json(e.r(r,s,g))}catch(e){return console.error(`Query execution error:`,e),t.json({error:e instanceof Error?e.message:`Query execution failed`},500)}}),h.get(`${d}/load`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`},400);let r;try{r=JSON.parse(n)}catch{return t.json({error:`Invalid JSON in query parameter`},400)}let i=await c(t),a=g.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=t.req.header(`x-cache-control`)===`no-cache`,s=await g.executeMultiCubeQuery(r,i,{skipCache:o});return t.json(e.r(r,s,g))}catch(e){return console.error(`Query execution error:`,e),t.json({error:e instanceof Error?e.message:`Query execution failed`},500)}}),h.post(`${d}/batch`,async t=>{try{let{queries:n}=await t.req.json();if(!n||!Array.isArray(n))return t.json({error:`Request body must contain a "queries" array`},400);if(n.length===0)return t.json({error:`Queries array cannot be empty`},400);let r=await e.u(n,await c(t),g,{skipCache:t.req.header(`x-cache-control`)===`no-cache`});return t.json(r)}catch(e){return console.error(`Batch execution error:`,e),t.json({error:e instanceof Error?e.message:`Batch execution failed`},500)}}),h.get(`${d}/meta`,t=>{try{let n=g.getMetadata();return t.json(e.a(n))}catch(e){return console.error(`Metadata error:`,e),t.json({error:e instanceof Error?e.message:`Failed to fetch metadata`},500)}}),h.post(`${d}/sql`,async t=>{try{let n=await t.req.json(),r=await c(t),i=g.validateQuery(n);if(!i.isValid)return t.json({error:`Query validation failed: ${i.errors.join(`, `)}`},400);let a=n.measures?.[0]||n.dimensions?.[0];if(!a)return t.json({error:`No measures or dimensions specified`},400);let o=a.split(`.`)[0],s=await g.generateSQL(o,n,r);return t.json(e.o(n,s))}catch(e){return console.error(`SQL generation error:`,e),t.json({error:e instanceof Error?e.message:`SQL generation failed`},500)}}),h.get(`${d}/sql`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`},400);let r=JSON.parse(n),i=await c(t),a=g.validateQuery(r);if(!a.isValid)return t.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=r.measures?.[0]||r.dimensions?.[0];if(!o)return t.json({error:`No measures or dimensions specified`},400);let s=o.split(`.`)[0],l=await g.generateSQL(s,r,i);return t.json(e.o(r,l))}catch(e){return console.error(`SQL generation error:`,e),t.json({error:e instanceof Error?e.message:`SQL generation failed`},500)}}),h.post(`${d}/dry-run`,async t=>{try{let n=await t.req.json(),r=await e.f(n.query||n,await c(t),g);return t.json(r)}catch(e){return console.error(`Dry-run error:`,e),t.json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1},400)}}),h.get(`${d}/dry-run`,async t=>{try{let n=t.req.query(`query`);if(!n)return t.json({error:`Query parameter is required`,valid:!1},400);let r=await e.f(JSON.parse(n),await c(t),g);return t.json(r)}catch(e){return console.error(`Dry-run error:`,e),t.json({error:e instanceof Error?e.message:`Dry-run validation failed`,valid:!1},400)}}),h.post(`${d}/explain`,async e=>{try{let t=await e.req.json(),n=t.query||t,r=t.options||{},i=await c(e),a=g.validateQuery(n);if(!a.isValid)return e.json({error:`Query validation failed: ${a.errors.join(`, `)}`},400);let o=await g.explainQuery(n,i,r);return e.json(o)}catch(t){return console.error(`Explain error:`,t),e.json({error:t instanceof Error?t.message:`Explain query failed`},500)}}),m&&h.post(`${d}/agent/chat`,async e=>{try{let{handleAgentChat:t}=await Promise.resolve().then(()=>require(`../handler-DzUX7CBs.cjs`)),{message:n,sessionId:r,history:i}=await e.req.json();if(!n||typeof n!=`string`)return e.json({error:`message is required and must be a string`},400);let a=(m.apiKey||``).trim();if(m.allowClientApiKey){let t=e.req.header(`x-agent-api-key`);t&&(a=t.trim())}if(!a)return e.json({error:`No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header.`},401);let o=m.allowClientApiKey?e.req.header(`x-agent-provider`):void 0,s=m.allowClientApiKey?e.req.header(`x-agent-model`):void 0,l=m.allowClientApiKey?e.req.header(`x-agent-provider-endpoint`):void 0,u=await c(e),d=m.buildSystemContext?.(u),f=new TextEncoder,p=new ReadableStream({async start(e){try{let c=t({message:n,sessionId:r,history:i,semanticLayer:g,securityContext:u,agentConfig:m,apiKey:a,systemContext:d,providerOverride:o,modelOverride:s,baseURLOverride:l});for await(let t of c){let n=`data: ${JSON.stringify(t)}\n\n`;e.enqueue(f.encode(n))}}catch(t){let n={type:`error`,data:{message:t instanceof Error?t.message:`Stream failed`}};e.enqueue(f.encode(`data: ${JSON.stringify(n)}\n\n`))}finally{e.close()}}});return new Response(p,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})}catch(t){return console.error(`Agent chat error:`,t),e.json({error:t instanceof Error?t.message:`Agent chat failed`},500)}}),p.enabled!==!1){let e={uri:`drizzle-cube://schema`,name:`Cube Schema`,description:`Current cube metadata as JSON`,mimeType:`application/json`,text:JSON.stringify(g.getMetadata(),null,2)},n=[...t.o(),e],r=t.a(),i=p.basePath??`/mcp`;h.post(`${i}`,async e=>{let i=t.p(e.req.header(`origin`),p.allowedOrigins?{allowedOrigins:p.allowedOrigins}:{});if(!i.valid)return e.json(t.n(null,-32600,i.reason),403);let a=e.req.header(`accept`);if(!t.f(a))return e.json(t.n(null,-32600,`Accept header must include both application/json and text/event-stream`),400);let o=t.c(e.req.header());if(!o.ok)return e.json({error:`Unsupported MCP protocol version`,supported:o.supported},426);let s=t.l(await e.req.json().catch(()=>null));if(!s)return e.json(t.n(null,-32600,`Invalid JSON-RPC 2.0 request`),400);let l=t.m(a),u=s.method===`initialize`;try{let i=await t.i(s.method,s.params,{semanticLayer:g,extractSecurityContext:c,rawRequest:e,rawResponse:null,negotiatedProtocol:o.negotiated,resources:n,prompts:r});if(t.s(s))return e.body(null,202);let a=t.r(s.id??null,i),d=u&&i&&typeof i==`object`&&`sessionId`in i?i.sessionId:void 0,f={};if(d&&(f[t.t]=d),l){let e=new TextEncoder,n=t.u(),r=new ReadableStream({start(r){r.enqueue(e.encode(`id: ${n}\n\n`)),r.enqueue(e.encode(t.d(a,n))),r.close()}});return new Response(r,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`,...f}})}return e.json(a,200,f)}catch(n){if(t.s(s))return console.error(`MCP notification processing error:`,n),e.body(null,202);console.error(`MCP RPC error:`,n);let r=n?.code??-32603,i=n?.data,a=n.message||`MCP request failed`,o=t.n(s.id??null,r,a,i);if(l){let e=new TextEncoder,n=t.u(),r=new ReadableStream({start(r){r.enqueue(e.encode(`id: ${n}\n\n`)),r.enqueue(e.encode(t.d(o,n))),r.close()}});return new Response(r,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})}return e.json(o,200)}}),h.delete(`${i}`,e=>e.json({error:`Session termination not supported`},405)),h.get(`${i}`,e=>{let n=new TextEncoder,r=t.u(),i,a=new ReadableStream({start(e){e.enqueue(n.encode(t.d({jsonrpc:`2.0`,method:`mcp/ready`,params:{protocol:`streamable-http`}},r,15e3))),i=setInterval(()=>{e.enqueue(n.encode(`: keep-alive
2
2
 
3
3
  `))},15e3)},cancel(){clearInterval(i)}});return new Response(a,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`}})})}return h}function a(e,t){let n=i(t);return e.route(`/`,n),e}function o(e){return a(new n.Hono,e)}exports.createCubeApp=o,exports.createCubeRoutes=i,exports.mountCubeRoutes=a;
@@ -1,5 +1,5 @@
1
1
  import { Hono } from 'hono';
2
- import { SemanticQuery, SecurityContext, DatabaseExecutor, DrizzleDatabase, Cube, CacheConfig } from '../../server';
2
+ import { SemanticQuery, SecurityContext, DatabaseExecutor, DrizzleDatabase, Cube, CacheConfig, RLSSetupFn } from '../../server';
3
3
  import { AgentConfig } from '../../server/agent/types';
4
4
  import { SemanticLayerCompiler } from '../../server/compiler';
5
5
  import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
@@ -86,6 +86,12 @@ export interface HonoAdapterOptions {
86
86
  * Requires `@anthropic-ai/sdk` as a peer dependency.
87
87
  */
88
88
  agent?: AgentConfig;
89
+ /**
90
+ * Row-Level Security setup function.
91
+ * When provided, every query execution opens a transaction, calls this function
92
+ * to configure RLS (e.g., set JWT claims and switch Postgres roles), then runs the query.
93
+ */
94
+ rlsSetup?: RLSSetupFn;
89
95
  }
90
96
  /**
91
97
  * Create Hono routes for Cube.js-compatible API
@@ -1,5 +1,5 @@
1
- import { a as e, f as t, o as n, r, u as i } from "../utils-B7VkyzMv.js";
2
- import { a, c as o, d as s, f as c, h as l, i as u, l as d, m as f, n as p, o as m, p as h, r as g, s as _, t as v, u as y } from "../mcp-transport-DWSNkwUY.js";
1
+ import { a as e, f as t, o as n, r, u as i } from "../utils-DkKcpkx5.js";
2
+ import { a, c as o, d as s, f as c, h as l, i as u, l as d, m as f, n as p, o as m, p as h, r as g, s as _, t as v, u as y } from "../mcp-transport-Cdisv8il.js";
3
3
  import { Hono as b } from "hono";
4
4
  //#region node_modules/hono/dist/middleware/cors/index.js
5
5
  var x = (e) => {
@@ -51,7 +51,8 @@ function S(S) {
51
51
  drizzle: w,
52
52
  schema: T,
53
53
  engineType: D,
54
- cache: A
54
+ cache: A,
55
+ rlsSetup: S.rlsSetup
55
56
  });
56
57
  if (!S.semanticLayer && C && C.forEach((e) => {
57
58
  P.registerCube(e);
@@ -158,7 +159,7 @@ function S(S) {
158
159
  }
159
160
  }), M && N.post(`${k}/agent/chat`, async (e) => {
160
161
  try {
161
- let { handleAgentChat: t } = await import("../handler-rPpxuopb.js"), { message: n, sessionId: r, history: i } = await e.req.json();
162
+ let { handleAgentChat: t } = await import("../handler-J55KQKe5.js"), { message: n, sessionId: r, history: i } = await e.req.json();
162
163
  if (!n || typeof n != "string") return e.json({ error: "message is required and must be a string" }, 400);
163
164
  let a = (M.apiKey || "").trim();
164
165
  if (M.allowClientApiKey) {
@@ -1,4 +1,4 @@
1
- import { c as e, d as t, h as n, p as r, s as i } from "./utils-B7VkyzMv.js";
1
+ import { c as e, d as t, h as n, p as r, s as i } from "./utils-DkKcpkx5.js";
2
2
  import { a } from "./mcp-prompts-BAutSQYA.js";
3
3
  //#region node_modules/drizzle-orm/entity.js
4
4
  var o = Symbol.for("drizzle:entityKind");
@@ -7241,11 +7241,23 @@ var gn = class {
7241
7241
  cacheConfig;
7242
7242
  logicalPlanBuilder;
7243
7243
  planOptimiser;
7244
- constructor(e, t) {
7244
+ rlsSetup;
7245
+ constructor(e, t, n) {
7245
7246
  if (this.dbExecutor = e, this.databaseAdapter = e.databaseAdapter, !this.databaseAdapter) throw Error("DatabaseExecutor must have a databaseAdapter property");
7246
7247
  this.queryBuilder = new Lt(this.databaseAdapter);
7247
- let n = new zt(), r = new Bt(this.queryBuilder);
7248
- this.drizzlePlanBuilder = new hn(this.queryBuilder, r, this.databaseAdapter), this.comparisonQueryBuilder = new Yt(this.databaseAdapter), this.funnelQueryBuilder = new Xt(this.databaseAdapter), this.flowQueryBuilder = new Zt(this.databaseAdapter), this.retentionQueryBuilder = new nn(this.databaseAdapter), this.logicalPlanBuilder = new rn(n), this.planOptimiser = new an(), this.cacheConfig = t;
7248
+ let r = new zt(), i = new Bt(this.queryBuilder);
7249
+ this.drizzlePlanBuilder = new hn(this.queryBuilder, i, this.databaseAdapter), this.comparisonQueryBuilder = new Yt(this.databaseAdapter), this.funnelQueryBuilder = new Xt(this.databaseAdapter), this.flowQueryBuilder = new Zt(this.databaseAdapter), this.retentionQueryBuilder = new nn(this.databaseAdapter), this.logicalPlanBuilder = new rn(r), this.planOptimiser = new an(), this.cacheConfig = t, this.rlsSetup = n;
7250
+ }
7251
+ async withRLSContext(e, t) {
7252
+ if (!this.rlsSetup) return t();
7253
+ let n = this.dbExecutor.db;
7254
+ if (!n.transaction) throw Error("rlsSetup requires a database driver that supports transactions (db.transaction)");
7255
+ let r = this.rlsSetup;
7256
+ return n.transaction(async (n) => {
7257
+ await r(n, e);
7258
+ let i = Object.create(this.dbExecutor);
7259
+ return i.db = n, this.dbExecutor = i, t();
7260
+ });
7249
7261
  }
7250
7262
  async execute(e, t, n, r) {
7251
7263
  try {
@@ -7285,7 +7297,7 @@ var gn = class {
7285
7297
  } catch (e) {
7286
7298
  this.cacheConfig.onError?.(e, "get");
7287
7299
  }
7288
- return await this.executeQueryByModeWithCache(i, e, t, n, a);
7300
+ return await this.withRLSContext(n, () => this.executeQueryByModeWithCache(i, e, t, n, a));
7289
7301
  } catch (e) {
7290
7302
  if (e instanceof Error) {
7291
7303
  let t = e;
@@ -7485,8 +7497,8 @@ var gn = class {
7485
7497
  for (let e of i) if (!a.has(e.name)) {
7486
7498
  a.add(e.name);
7487
7499
  try {
7488
- if (e.public) continue;
7489
- e.sql(t).where || console.warn(`[drizzle-cube] WARNING: Cube '${e.name}' has no security filtering. If this cube contains public data, add 'public: true' to suppress this warning. Otherwise, ensure sql() returns: { from: table, where: eq(table.orgId, ctx.securityContext.orgId) }`);
7500
+ if (e.public || this.rlsSetup) continue;
7501
+ e.sql(t).where || console.warn(`[drizzle-cube] WARNING: Cube '${e.name}' has no security filtering. If this cube contains public data, add 'public: true' to suppress this warning. Otherwise, ensure sql() returns: { from: table, where: eq(table.orgId, ctx.securityContext.orgId) }. For databases that support Row Level Security (e.g. PostgreSQL), you can configure rlsSetup to run session-level commands (SET LOCAL, SET ROLE) instead.`);
7490
7502
  } catch {}
7491
7503
  }
7492
7504
  }
@@ -7541,7 +7553,7 @@ var gn = class {
7541
7553
  }
7542
7554
  async explainQuery(e, t, n, r) {
7543
7555
  let i = await this.dryRunSQL(e, t, n);
7544
- return this.dbExecutor.explainQuery(i.sql, i.params || [], r);
7556
+ return this.withRLSContext(n, () => this.dbExecutor.explainQuery(i.sql, i.params || [], r));
7545
7557
  }
7546
7558
  async dryRunSQL(e, t, n) {
7547
7559
  let r = this.resolveQueryMode(t);
@@ -7722,33 +7734,36 @@ var gn = class {
7722
7734
  }
7723
7735
  }, _n = class e {
7724
7736
  cubes = /* @__PURE__ */ new Map();
7725
- dbExecutor;
7726
7737
  metadataCache;
7727
7738
  cacheConfig;
7739
+ rlsSetup;
7740
+ db;
7741
+ schema;
7742
+ engineType;
7728
7743
  constructor(e) {
7729
- e?.databaseExecutor ? this.dbExecutor = e.databaseExecutor : e?.drizzle && (this.dbExecutor = mt(e.drizzle, e.schema, e.engineType)), this.cacheConfig = e?.cache;
7744
+ e?.databaseExecutor ? (this.db = e.databaseExecutor.db, this.schema = e.databaseExecutor.schema, this.engineType = e.databaseExecutor.getEngineType()) : e?.drizzle && (this.db = e.drizzle, this.schema = e.schema, this.engineType = e.engineType), this.cacheConfig = e?.cache, this.rlsSetup = e?.rlsSetup;
7730
7745
  }
7731
7746
  setDatabaseExecutor(e) {
7732
- this.dbExecutor = e;
7747
+ this.db = e.db, this.schema = e.schema, this.engineType = e.getEngineType();
7733
7748
  }
7734
7749
  getEngineType() {
7735
- return this.dbExecutor?.getEngineType();
7750
+ return this.engineType;
7736
7751
  }
7737
7752
  setDrizzle(e, t, n) {
7738
- this.dbExecutor = mt(e, t, n);
7753
+ this.db = e, this.schema = t, this.engineType = n;
7739
7754
  }
7740
7755
  hasExecutor() {
7741
- return !!this.dbExecutor;
7756
+ return !!this.db;
7742
7757
  }
7743
- requireExecutor() {
7744
- if (!this.dbExecutor) throw Error("Database executor not configured");
7745
- return this.dbExecutor;
7758
+ createDbExecutor() {
7759
+ if (!this.db) throw Error("Database executor not configured");
7760
+ return mt(this.db, this.schema, this.engineType);
7746
7761
  }
7747
7762
  createQueryExecutor(e = !1) {
7748
- return new gn(this.requireExecutor(), e ? this.cacheConfig : void 0);
7763
+ return new gn(this.createDbExecutor(), e ? this.cacheConfig : void 0, this.rlsSetup);
7749
7764
  }
7750
7765
  formatSqlResult(e) {
7751
- let t = this.requireExecutor().getEngineType();
7766
+ let t = this.getEngineType() ?? "postgres";
7752
7767
  return {
7753
7768
  sql: i(e.sql, t),
7754
7769
  params: e.params