@budibase/pro 2.6.19-alpha.14 → 2.6.19-alpha.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -0
- package/dist/package.json +5 -5
- package/dist/src/api/controllers/apps/backups.d.ts +7 -0
- package/dist/src/api/controllers/global/auditLogs.d.ts +6 -0
- package/dist/src/api/controllers/global/environmentVariables.d.ts +6 -0
- package/dist/src/api/controllers/global/groups.d.ts +10 -0
- package/dist/src/api/controllers/global/index.d.ts +2 -0
- package/dist/src/api/controllers/global/scim/groups.d.ts +5 -0
- package/dist/src/api/controllers/global/scim/users.d.ts +5 -0
- package/dist/src/api/controllers/schedules/index.d.ts +9 -0
- package/dist/src/api/errors.d.ts +4 -0
- package/dist/src/api/index.d.ts +6 -0
- package/dist/src/api/routes/apps/backups.d.ts +4 -0
- package/dist/src/api/routes/global/auditLogs.d.ts +4 -0
- package/dist/src/api/routes/global/environmentVariables.d.ts +4 -0
- package/dist/src/api/routes/global/groups.d.ts +4 -0
- package/dist/src/api/routes/global/scim.d.ts +4 -0
- package/dist/src/api/routes/schedules/index.d.ts +4 -0
- package/dist/src/constants/index.d.ts +4 -0
- package/dist/src/constants/licenses.d.ts +14 -0
- package/dist/src/constants/misc.d.ts +1 -0
- package/dist/src/constants/quotas.d.ts +71 -0
- package/dist/src/constants/version.d.ts +6 -0
- package/dist/src/db/auditLogs.d.ts +9 -0
- package/dist/src/db/automations.d.ts +22 -0
- package/dist/src/db/backups.d.ts +16 -0
- package/dist/src/db/environmentVariables.d.ts +8 -0
- package/dist/src/db/groups.d.ts +43 -0
- package/dist/src/db/index.d.ts +5 -0
- package/dist/src/db/licenseInfo.d.ts +7 -0
- package/dist/src/db/quotas/index.d.ts +2 -0
- package/dist/src/db/quotas/quotas.d.ts +16 -0
- package/dist/src/db/quotas/utils.d.ts +8 -0
- package/dist/src/db/utils/pagination.d.ts +8 -0
- package/dist/src/db/utils/retention.d.ts +2 -0
- package/dist/src/db/utils/views.d.ts +6 -0
- package/dist/src/db/views/groups.d.ts +5 -0
- package/dist/src/db/views/index.d.ts +2 -0
- package/dist/src/db/views/staticViews.d.ts +1 -0
- package/dist/src/index.d.ts +7 -0
- package/dist/src/mappers/groups.d.ts +3 -0
- package/dist/src/mappers/index.d.ts +2 -0
- package/dist/src/mappers/users.d.ts +5 -0
- package/dist/src/middleware/doInScimContext.d.ts +2 -0
- package/dist/src/middleware/feature.d.ts +2 -0
- package/dist/src/middleware/index.d.ts +4 -0
- package/dist/src/middleware/licensing.d.ts +3 -0
- package/dist/src/middleware/requireSCIM.d.ts +2 -0
- package/dist/src/sdk/api/api.d.ts +2 -0
- package/dist/src/sdk/api/index.d.ts +1 -0
- package/dist/src/sdk/auditLogs/auditLogs.d.ts +14 -0
- package/dist/src/sdk/auditLogs/index.d.ts +1 -0
- package/dist/src/sdk/auditLogs/utils.d.ts +12 -0
- package/dist/src/sdk/automations/index.d.ts +1 -0
- package/dist/src/sdk/automations/logging/index.d.ts +10 -0
- package/dist/src/sdk/backups/backup.d.ts +35 -0
- package/dist/src/sdk/backups/index.d.ts +35 -0
- package/dist/src/sdk/backups/processing.d.ts +2 -0
- package/dist/src/sdk/backups/queue.d.ts +3 -0
- package/dist/src/sdk/branding/branding.d.ts +2 -0
- package/dist/src/sdk/branding/index.d.ts +1 -0
- package/dist/src/sdk/environmentVariables/environmentVariables.d.ts +9 -0
- package/dist/src/sdk/environmentVariables/index.d.ts +1 -0
- package/dist/src/sdk/features/features.d.ts +11 -0
- package/dist/src/sdk/features/index.d.ts +1 -0
- package/dist/src/sdk/groups/groups.d.ts +33 -0
- package/dist/src/sdk/groups/index.d.ts +1 -0
- package/dist/src/sdk/index.d.ts +14 -0
- package/dist/src/sdk/init.d.ts +2 -0
- package/dist/src/sdk/licensing/cache/cache.d.ts +4 -0
- package/dist/src/sdk/licensing/cache/index.d.ts +1 -0
- package/dist/src/sdk/licensing/cache/redis.d.ts +1 -0
- package/dist/src/sdk/licensing/index.d.ts +2 -0
- package/dist/src/sdk/licensing/licenses/client.d.ts +4 -0
- package/dist/src/sdk/licensing/licenses/index.d.ts +3 -0
- package/dist/src/sdk/licensing/licenses/licenses.d.ts +5 -0
- package/dist/src/sdk/licensing/licenses/offline.d.ts +4 -0
- package/dist/src/sdk/plugins/index.d.ts +4 -0
- package/dist/src/sdk/quotas/helpers/apps.d.ts +6 -0
- package/dist/src/sdk/quotas/helpers/automations.d.ts +5 -0
- package/dist/src/sdk/quotas/helpers/dayPasses.d.ts +2 -0
- package/dist/src/sdk/quotas/helpers/groups.d.ts +2 -0
- package/dist/src/sdk/quotas/helpers/index.d.ts +8 -0
- package/dist/src/sdk/quotas/helpers/plugins.d.ts +3 -0
- package/dist/src/sdk/quotas/helpers/queries.d.ts +5 -0
- package/dist/src/sdk/quotas/helpers/rows.d.ts +8 -0
- package/dist/src/sdk/quotas/helpers/users.d.ts +2 -0
- package/dist/src/sdk/quotas/index.d.ts +3 -0
- package/dist/src/sdk/quotas/quotas.d.ts +57 -0
- package/dist/src/sdk/scim/index.d.ts +1 -0
- package/dist/src/sdk/scim/users.d.ts +25 -0
- package/dist/src/sdk/users/index.d.ts +1 -0
- package/dist/src/sdk/users/users.d.ts +1 -0
- package/dist/src/sdk/utils/apps.d.ts +1 -0
- package/dist/src/sdk/utils/index.d.ts +1 -0
- package/dist/src/types/api.d.ts +13 -0
- package/dist/src/types/documents/index.d.ts +1 -0
- package/dist/src/types/documents/license.d.ts +5 -0
- package/dist/src/types/index.d.ts +4 -0
- package/dist/src/types/init.d.ts +27 -0
- package/dist/src/types/license.d.ts +18 -0
- package/dist/src/utilities/api.d.ts +12 -0
- package/dist/src/utilities/delay.d.ts +2 -0
- package/dist/src/utilities/fileSystem.d.ts +1 -0
- package/dist/src/utilities/index.d.ts +1 -0
- package/package.json +6 -6
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@budibase/types"),t=require("@budibase/backend-core"),i=require("node-fetch"),o=require("lru-cache"),n=require("fs"),r=require("path"),a=require("os"),s=require("jsonwebtoken"),d=require("@koa/router"),u=require("joi"),l=require("scim2-parse-filter"),c=require("scim-patch"),p=require("lodash"),v=require("@budibase/shared-core");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var g,y=f(i),m=f(o),h=f(n),b=f(r),A=f(s),S=f(d),O=f(u),I=f(p);function _(e,t){var i={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++)t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}return i}function E(e,t,i,o){return new(i||(i=Promise))((function(n,r){function a(e){try{d(o.next(e))}catch(e){r(e)}}function s(e){try{d(o.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,s)}d((o=o.apply(e,t||[])).next())}))}let T;exports.Method=void 0,(g=exports.Method||(exports.Method={})).POST="POST",g.GET="GET",g.PATCH="PATCH",g.DELETE="DELETE",g.PUT="PUT";process.on("exit",(()=>E(void 0,void 0,void 0,(function*(){yield E(void 0,void 0,void 0,(function*(){T&&(yield T.finish())}))}))));const w=()=>E(void 0,void 0,void 0,(function*(){return T||(yield E(void 0,void 0,void 0,(function*(){T=yield new t.redis.Client(t.redis.utils.Databases.LICENSES).init()}))),T}));class D{constructor(e){this.apiCall=e=>(i="",o={})=>E(this,void 0,void 0,(function*(){o.headers||(o.headers={}),o.headers["Content-Type"]||(o.headers=Object.assign({"Content-Type":"application/json",Accept:"application/json"},o.headers));const n="application/json"===o.headers["Content-Type"];t.logging.correlation.setHeader(o.headers);const r={method:e,body:n?JSON.stringify(o.body):o.body,headers:o.headers,credentials:"include"};return y.default(`${this.host}${i}`,r)})),this.post=this.apiCall(exports.Method.POST),this.get=this.apiCall(exports.Method.GET),this.patch=this.apiCall(exports.Method.PATCH),this.del=this.apiCall(exports.Method.DELETE),this.put=this.apiCall(exports.Method.PUT),this.host=e}}const P=()=>{const e=new Date;return new Date(e.getFullYear(),e.getMonth()+1,1).toISOString()},U=e=>{e.quotaReset=P()},R=()=>{const e=new Date;return`${e.getMonth()+1}-${e.getFullYear()}`},k=()=>({usageQuota:{[e.StaticQuotaName.APPS]:0,[e.StaticQuotaName.ROWS]:0,[e.StaticQuotaName.PLUGINS]:0,[e.StaticQuotaName.USERS]:0,[e.StaticQuotaName.USER_GROUPS]:0,triggers:{}},monthly:{[R()]:B()}}),N=()=>{const e=Object.assign(Object.assign({_id:t.db.StaticDatabases.GLOBAL.docs.usageQuota,quotaReset:P()},k()),{apps:{}});return j(e),e},B=()=>({[e.MonthlyQuotaName.QUERIES]:0,[e.MonthlyQuotaName.AUTOMATIONS]:0,[e.MonthlyQuotaName.DAY_PASSES]:0,triggers:{}}),j=e=>{const t=R();e.monthly||(e.monthly={}),e.monthly[t]||(e.monthly[t]=B()),e.monthly.current=e.monthly[t]},L=(i,o)=>{if(o&&i)switch(i){case e.MonthlyQuotaName.AUTOMATIONS:return e.BreakdownQuotaName.AUTOMATIONS;case e.MonthlyQuotaName.QUERIES:return t.db.isTableId(o)?e.BreakdownQuotaName.ROW_QUERIES:t.db.isDatasourceId(o)?e.BreakdownQuotaName.DATASOURCE_QUERIES:void 0}};var C=Object.freeze({__proto__:null,setQuotaReset:U,getCurrentMonthString:R,generateBaseQuotaUsage:k,generateNewQuotaUsage:N,generateNewMonthlyQuotas:B,setCurrentMonth:j,getBreakdownName:L});const{Writethrough:$}=t.cache.writethrough,G=()=>new $(t.tenancy.getGlobalDB()),Q=()=>E(void 0,void 0,void 0,(function*(){const e=G();let i;try{i=yield e.get(t.db.StaticDatabases.GLOBAL.docs.usageQuota),j(i),U(i)}catch(t){if(404!==t.status)throw t;{i=N();const t=yield e.put(i);i._rev=t.rev}}return delete i.usageLimits,delete i.usageQuota.automationRuns,delete i.usageQuota.emails,delete i.usageQuota.storage,delete i.usageQuota.views,delete i.usageQuota.publishedApps,delete i.usageQuota.developers,i})),x=(e,t,i)=>E(void 0,void 0,void 0,(function*(){return z(t,i,{total:e})})),q=(i,o,n,r={},a)=>{var s;let d;try{d=t.db.getProdAppID((null==r?void 0:r.appId)||t.context.getAppId())}catch(e){}if(!d||!a.app||!e.APP_QUOTA_NAMES.includes(o))return i;(null===(s=i.apps)||void 0===s?void 0:s[d])||(i.apps=Object.assign(Object.assign({},i.apps),{[d]:k()}));const u=i.apps[d];switch(n){case e.QuotaUsageType.STATIC:u.usageQuota[o]=a.app;break;case e.QuotaUsageType.MONTHLY:const t=R(),i=o;let n=u.monthly[t];n||(u.monthly[t]=B(),n=u.monthly[t]),n[i]=a.app,e.BREAKDOWN_QUOTA_NAMES.includes(i)&&(null==r?void 0:r.id)&&(n=((e,t,i,o)=>{const n=L(t,i);return n&&(null==o?void 0:o.breakdown)?(e.breakdown||(e.breakdown={}),e.breakdown[n]||(e.breakdown[n]={parent:t,values:{}}),e.breakdown[n].values[i]=o.breakdown,e):e})(n,i,r.id,a))}return i},M=(i,o,n,r)=>{var a,s,d,u,l;if(!e.APP_QUOTA_NAMES.includes(n))return{};let c;try{c=t.db.getProdAppID(t.context.getAppId())}catch(e){}if(!c||!i.apps||!i.apps[c])return{app:0};const p=i.apps[c];switch(o){case e.QuotaUsageType.STATIC:if(null===(a=p.usageQuota)||void 0===a?void 0:a[n])return{app:p.usageQuota[n]};break;case e.QuotaUsageType.MONTHLY:const t=R(),i=n;if(!(null===(d=null===(s=p.monthly)||void 0===s?void 0:s[t])||void 0===d?void 0:d[i]))break;const o=p.monthly[t],c=o[i];let v;const f=L(i,r);return f&&r&&(null===(u=o.breakdown)||void 0===u?void 0:u[f])&&(v=null===(l=o.breakdown[f])||void 0===l?void 0:l.values[r]),{app:c,breakdown:v||0}}return{app:0}},F=(t,i,o,n,r={})=>{if(o===e.QuotaUsageType.STATIC)t.usageQuota[i]=n.total,((e,t,i)=>{t.usageQuota.triggers||(t.usageQuota.triggers={}),i&&(t.usageQuota.triggers[e]=i)})(i,t,n.triggers);else{if(o!==e.QuotaUsageType.MONTHLY)throw new Error(`Invalid usage type: ${o}`);{const e=R();t.monthly[e][i]=n.total,((e,t,i,o)=>{i.monthly[t].triggers||(i.monthly[t].triggers={}),o&&(i.monthly[t].triggers[e]=o)})(i,e,t,n.triggers)}}return q(t,i,o,r,n)},z=(e,t,i,o={})=>E(void 0,void 0,void 0,(function*(){const n=G();let r=yield Q();r=F(r,e,t,i,o);const a=yield n.put(r);return r._rev=a.rev,r})),K=(t,i,o)=>E(void 0,void 0,void 0,(function*(){const n=yield Q();let r=0,a={};switch(t){case e.QuotaUsageType.STATIC:if(n.usageQuota[i]){const e=i;r=n.usageQuota[e],a=M(n,t,i,o)}break;case e.QuotaUsageType.MONTHLY:const s=R(),d=i;n.monthly[s][d]&&(r=n.monthly[s][d],a=M(n,t,i,o));break;default:throw new Error(`Invalid usage type: ${t}`)}return!e.APP_QUOTA_NAMES.includes(i)||a.app||a.breakdown||(a.app=a.app||0,a.breakdown=a.breakdown||0),{total:r,app:a.app,breakdown:a.breakdown}})),Y=e=>E(void 0,void 0,void 0,(function*(){const i=(e=>({_id:t.StaticDatabases.GLOBAL.docs.licenseInfo,licenseKey:e}))(e);return(e=>E(void 0,void 0,void 0,(function*(){const i=t.tenancy.getGlobalDB(),o=yield i.put(e);return e._rev=o.rev,e})))(i)})),V=()=>E(void 0,void 0,void 0,(function*(){const e=t.tenancy.getGlobalDB();try{return yield e.get(t.StaticDatabases.GLOBAL.docs.licenseInfo)}catch(e){if(404===e.status)return;throw e}}));function H(){return E(this,void 0,void 0,(function*(){const i=t.context.getAuditLogsDB();let o;try{o=yield i.get("_design/database")}catch(e){404===e.status&&(o={_id:"_design/database"})}o.indexes={[e.SearchIndex.AUDIT]:{index:function(e){if(e._id&&!e._id.startsWith("al_"))return;const t=["_id","_rev","metadata"];let i=Object.values(e.metadata).join(" ");for(let o of Object.keys(e)){if(t.includes(o))continue;const n=e[o];"string"==typeof n&&(index(o,n.toLowerCase(),{facet:!0}),i+=` ${n}`)}if(e.fallback)for(let t of Object.values(e.fallback))t&&"string"==typeof t&&(i+=` ${t}`);index("all",i)}.toString(),analyzer:{default:"whitespace",fields:{all:"standard"},name:"perfield"}}},yield i.put(o)}))}const{ViewName:W,SEPARATOR:J,DocumentType:X,createView:Z}=t.db,ee=X.USER+J;var te;function ie(){return E(this,void 0,void 0,(function*(){const e=t.tenancy.getGlobalDB(),i=`function(doc) {\n if (doc._id.startsWith("${ee}") && Array.isArray(doc.userGroups)) {\n for (let groupId of doc.userGroups) {\n emit("${te.SEARCH_BY_ID}" + groupId, { email: doc.email, userId: doc._id })\n emit("${te.SEARCH_BY_EMAIL}" + groupId + doc.email, { email: doc.email, userId: doc._id })\n }\n }\n }`;yield Z(e,i,W.USER_BY_GROUP)}))}!function(e){e.SEARCH_BY_ID="g_",e.SEARCH_BY_EMAIL="e_"}(te||(te={}));const oe=`${t.DocumentType.GROUP}${t.SEPARATOR}`;function ne(e,i){return E(this,void 0,void 0,(function*(){const o=t.tenancy.getGlobalDB(),n=yield t.db.queryView(t.db.ViewName.USER_BY_GROUP,function(e,i={}){e||(e="");const{emailSearch:o,bookmark:n}=i,r=_(i,["emailSearch","bookmark"]);return o?Object.assign(Object.assign({},r),{startkey:`${te.SEARCH_BY_EMAIL}${e}${n||o}`,endkey:`${te.SEARCH_BY_EMAIL}${e}${o}${t.UNICODE_MAX}`}):Object.assign(Object.assign({},i),{startkey:`${te.SEARCH_BY_ID}${e}`,endkey:`${te.SEARCH_BY_ID}${e}${t.UNICODE_MAX}`,startkey_docid:n})}(e,i),o,ie,{arrayResponse:!0});return n.map((e=>({_id:e.userId,email:e.email})))||[]}))}function re(e){return E(this,void 0,void 0,(function*(){return e.users=yield ne(e._id),e}))}function ae(){return E(this,void 0,void 0,(function*(){const e=t.tenancy.getGlobalDB();try{const i=(yield e.allDocs(function(e,i={}){e||(e="");const o=(null==e?void 0:e.startsWith(t.DocumentType.GROUP))?"":oe;return Object.assign(Object.assign({},i),{startkey:`${o}${e}`,endkey:`${o}${e}${t.UNICODE_MAX}`})}(null,{include_docs:!0}))).rows.map((e=>e.doc)),o=[];for(let e of i)o.push(re(e));return yield Promise.all(o)}catch(e){throw e}}))}function se(e){return E(this,void 0,void 0,(function*(){const i=t.tenancy.getGlobalDB();try{const t=yield i.get(e);return yield re(t)}catch(e){throw e}}))}function de(e,i={enriched:!0}){return E(this,void 0,void 0,(function*(){const o=t.tenancy.getGlobalDB();try{const t=(yield o.allDocs({keys:e,include_docs:!0})).rows.map((e=>e.doc));if(null==i?void 0:i.enriched){const e=[];for(let i of t)e.push(re(i));return yield Promise.all(e)}return t}catch(e){throw e}}))}function ue(e,i){return E(this,void 0,void 0,(function*(){const o=t.tenancy.getGlobalDB(),n=yield o.get(e);let r=yield o.remove(e,i);return yield function(e){var i;return E(this,void 0,void 0,(function*(){const o=yield re(e),n=null===(i=o.users)||void 0===i?void 0:i.map((e=>e._id)),r=yield t.users.bulkGetGlobalUsersById(n),a=[];for(let t of r){if(!t.userGroups)continue;const i=t.userGroups.length;t.userGroups=t.userGroups.filter((t=>t!==e._id)),t.userGroups.length!==i&&a.push(t)}a.length&&(yield t.users.bulkUpdateGlobalUsers(a))}))}(n),r}))}function le(e,t){var i;const o=e.rows.map((e=>e.doc?e.doc:e));if(!(null==t?void 0:t.paginate))return{data:o,hasNextPage:!1};const n=o.length>(null==t?void 0:t.pageSize);return{data:o.slice(0,null==t?void 0:t.pageSize),hasNextPage:n,nextPage:n?null===(i=o[null==t?void 0:t.pageSize])||void 0===i?void 0:i._id:void 0}}const{ViewName:ce,AutomationViewMode:pe,SEPARATOR:ve,DocumentType:fe,createView:ge}=t.db,ye=fe.AUTOMATION_LOG+ve,me=fe.APP_BACKUP+ve;const he=t=>({[e.StaticQuotaName.ROWS]:{name:"Rows",value:t,triggers:[90,100]}}),be=t=>({[e.StaticQuotaName.APPS]:{name:"Apps",value:t,triggers:[100]}}),Ae=t=>({[e.StaticQuotaName.USERS]:{name:"Users",value:t,triggers:[80,100]}}),Se=t=>({[e.StaticQuotaName.USER_GROUPS]:{name:"User Groups",value:t,triggers:[80,100]}}),Oe=t=>({[e.StaticQuotaName.PLUGINS]:{name:"Plugins",value:t,triggers:[90,100]}}),Ie=t=>({[e.MonthlyQuotaName.QUERIES]:{name:"Queries",value:t,triggers:[]}}),_e=t=>({[e.MonthlyQuotaName.AUTOMATIONS]:{name:"Automations",value:t,triggers:[80,90,100]}}),Ee=t=>({[e.MonthlyQuotaName.DAY_PASSES]:{name:"Day Passes",value:t,triggers:[80,90,100]}}),Te=t=>({[e.ConstantQuotaName.AUTOMATION_LOG_RETENTION_DAYS]:{name:"Automation Logs",value:t,triggers:[]}}),we=t=>({[e.ConstantQuotaName.APP_BACKUPS_RETENTION_DAYS]:{name:"App Backups",value:t,triggers:[]}});var De=Object.freeze({__proto__:null,UNLIMITED:-1,rows:he,apps:be,users:Ae,userGroups:Se,plugins:Oe,queries:Ie,automations:_e,dayPasses:Ee,automationLogRetentionDays:Te,appBackupRetentionDays:we});const Pe=-1,Ue={features:[],quotas:{usage:{monthly:Object.assign(Object.assign(Object.assign({},Ie(Pe)),_e(200)),Ee(Pe)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},be(Pe)),he(2e3)),Ae(5)),Se(0)),Oe(10))},constant:Object.assign(Object.assign({},Te(1)),we(0))},plan:{type:e.PlanType.FREE,usesInvoicing:!1,model:e.PlanModel.PER_USER}},Re={features:[],quotas:{usage:{monthly:Object.assign(Object.assign(Object.assign({},Ie(Pe)),_e(Pe)),Ee(Pe)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},he(Pe)),be(Pe)),Ae(Pe)),Se(0)),Oe(10))},constant:Object.assign(Object.assign({},Te(1)),we(0))},plan:{type:e.PlanType.FREE,usesInvoicing:!1,model:e.PlanModel.PER_USER}},ke={features:[],quotas:{usage:{monthly:Object.assign(Object.assign(Object.assign({},Ie(Pe)),_e(Pe)),Ee(Pe)),static:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},be(Pe)),he(Pe)),Ae(Pe)),Se(Pe)),Oe(Pe))},constant:Object.assign(Object.assign({},Te(Pe)),we(Pe))},plan:{type:e.PlanType.FREE,usesInvoicing:!1,model:e.PlanModel.PER_USER}};var Ne=Object.freeze({__proto__:null,UNLIMITED:Pe,CLOUD_FREE_LICENSE:Ue,SELF_FREE_LICENSE:Re,UNLIMITED_LICENSE:ke});const Be=()=>{if(t.env.isDev()){const e="dev-version.txt",i=b.default.join(t.objectStore.budibaseTempDir(),e);if(h.default.existsSync(i))return h.default.readFileSync(i,"utf8");{const e=t.utils.newid();return h.default.writeFileSync(i,e),e}}return je()},je=()=>{const e=t.env.VERSION;if(!e)throw new Error("No budibase pro version was specified");return e};var Le=Object.freeze({__proto__:null,getLicenseVersion:Be,getProVersion:je});const Ce=9;var $e=Object.freeze({__proto__:null,licenses:Ne,quotas:De,versions:Le,GENERIC_PAGE_SIZE:Ce});const Ge=new Date(864e13).toISOString(),Qe=864e5;function xe(t){var i,o,n;return E(this,void 0,void 0,(function*(){const r=yield ft(),a=(null===(n=null===(o=null===(i=r.quotas)||void 0===i?void 0:i[e.QuotaType.CONSTANT])||void 0===o?void 0:o[t])||void 0===n?void 0:n.value)||0;return a===Pe?new Date(Ge).toISOString():new Date((new Date).getTime()-Qe*a).toISOString()}))}const qe=`${t.db.DocumentType.APP_BACKUP}${t.db.SEPARATOR}`;function Me(i,o,n={}){return E(this,void 0,void 0,(function*(){const r=yield function(){return E(this,void 0,void 0,(function*(){return xe(e.ConstantQuotaName.APP_BACKUPS_RETENTION_DAYS)}))}(),a=t.db.getProdAppID(i);let s=a,d=a;if(o.trigger&&o.type){let e=`${t.db.SEPARATOR}${o.trigger}`;e+=`${t.db.SEPARATOR}${o.type}`,s+=e,d+=e}return(!o.startDate||o.startDate<r)&&(o.startDate=r),o.startDate&&(d+=`${t.db.SEPARATOR}${o.startDate}`),o.endDate&&(s+=`${t.db.SEPARATOR}${o.endDate}`),Object.assign(Object.assign({},n),{descending:!0,startkey:`${qe}${s}${t.db.UNICODE_MAX}`,endkey:`${qe}${d}`})}))}function Fe(e,i){return E(this,void 0,void 0,(function*(){let o=[];try{const n=t.db.getQueryIndex(t.db.ViewName.APP_BACKUP_BY_TRIGGER);o=yield e.query(n,i)}catch(o){if(null!=o&&"not_found"===o.error)return yield function(){return E(this,void 0,void 0,(function*(){const e=t.tenancy.getGlobalDB(),i=`function(doc) {\n if (doc._id.startsWith("${me}") && doc.type && doc.trigger) {\n let full = doc.appId + "${ve}"\n full += doc.trigger.toLowerCase() + "${ve}"\n full += doc.type.toLowerCase() + "${ve}"\n emit("${me}" + full + doc.timestamp) \n }\n }`;yield ge(e,i,ce.APP_BACKUP_BY_TRIGGER)}))}(),Fe(e,i);throw o}return o}))}function ze(e,i={}){return E(this,void 0,void 0,(function*(){const o=t.tenancy.getGlobalDB(),n=t.db.getProdAppID(e.appId);let r=(a=n,s=e.timestamp,`${qe}${a}${t.db.SEPARATOR}${s}`);var a,s;const d=Object.assign(Object.assign({},e),{_id:r,appId:n,name:e.name});return i.filename&&(d.filename=i.filename),i.docId&&i.docRev&&(d._id=i.docId,d._rev=i.docRev),e.createdBy&&(d.createdBy=t.db.getGlobalIDFromUserMetadataID(e.createdBy)),yield o.put(d)}))}function Ke(e){return E(this,void 0,void 0,(function*(){const i=t.tenancy.getGlobalDB();return yield i.get(e)}))}const Ye=new m.default({max:1e3});function Ve(){return t.StaticDatabases.GLOBAL.docs.environmentVariables}function He(){return E(this,void 0,void 0,(function*(){const e=Ve(),i=t.tenancy.getGlobalDB();let o,n=!1;try{o=yield i.get(e)}catch(e){if(404!=e.status)throw e;n=!0}const r=(a=null==o?void 0:o._rev,`${t.tenancy.getTenantId()}/${Ve()}/${a||""}`);var a;const s=Ye.get(r);if(s)return s;let d;return d=!n&&o?Object.assign(Object.assign({},o),{variables:JSON.parse(t.encryption.decrypt(o.variables,t.encryption.SecretOption.ENCRYPTION))}):{_id:e,variables:{}},Ye.set(r,d),d}))}const We=new D(t.env.ACCOUNT_PORTAL_URL),Je=e=>E(void 0,void 0,void 0,(function*(){try{const t=yield e.json();if(t.message)return t.message}catch(e){}try{const t=yield e.text();if(t)return t}catch(e){}})),Xe=e=>E(void 0,void 0,void 0,(function*(){let i,o;if(t.env.SELF_HOSTED){if(i=yield V(),!i)return;o={[t.constants.Header.LICENSE_KEY]:i.licenseKey}}else{const e=t.tenancy.getTenantId();o={[t.constants.Header.API_KEY]:t.env.ACCOUNT_PORTAL_API_KEY,[t.constants.Header.TENANT_ID]:e}}return e(o)}));let Ze=()=>E(void 0,void 0,void 0,(function*(){return Xe((i=>E(void 0,void 0,void 0,(function*(){const o=yield Q();if(null==o.usageQuota.users){const i=yield t.users.getUserCount();console.info(`Syncing user count quota to ${i}`),o.usageQuota.users=i,yield x(i,e.StaticQuotaName.USERS,e.QuotaUsageType.STATIC)}const n=yield t.installation.getInstallFromDB(),r=t.tenancy.getTenantId(),a=yield t.events.identification.getUniqueTenantId(r),s=je(),d={quotaUsage:o,install:{id:n.installId,tenantId:a,version:s}},u=yield We.post("/api/license",{headers:Object.assign({},i),body:d});if(404!==u.status&&403!==u.status){if(200!==u.status){const e=yield Je(u);throw new t.HTTPError(`Error getting license: ${e}`,u.status)}return u.json()}}))))}));t.env.isJest()&&(Ze=jest.fn());const et=Ze,tt=e=>Xe((i=>E(void 0,void 0,void 0,(function*(){const o=yield We.post("/api/license/usage/triggered",{headers:Object.assign({},i),body:e});if(200!==o.status){const e=yield Je(o);t.logging.logAlert(`Error triggering quota usage: ${e}`)}})))),it=e=>E(void 0,void 0,void 0,(function*(){const i={installVersion:je()},o=yield We.post("/api/license/activate",{headers:{[t.constants.Header.LICENSE_KEY]:e},body:i});if(403===o.status)throw new t.HTTPError("Invalid license key",400);if(200!==o.status){const e=yield Je(o);throw new t.HTTPError(`Error activating license key: ${e}`,o.status)}return o.json()}));var ot=Object.freeze({__proto__:null,getLicense:et,triggerQuota:tt,activateLicenseKey:it});const nt=t.env.isTest()?".budibase-test":".budibase",rt=r.join(a.tmpdir(),nt),at=r.join(rt,"offline_license.txt");h.default.existsSync(rt)||h.default.mkdirSync(rt);const st="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvz3jePLCFBXZ19c8Dpkv\nXtSgOhKFOcvQdo/LV0KJRUzQWDPWuO4ILtBtnqhjtIzZH4CH0qCYBet5L6Qr4CM1\nl2HXiAD1Q2rlHNW9wDaYyKb1F5f+v4RyqCAyzlkwRdksmkLeECTboojNnmRCrE3C\n8suunQP5bEScqEY2kclqzSf8e6xqMzPUg3mL/pNa1iEv7TuLbU9nJfgR36l0WmZY\n94fWnSaT8OSXSqcxsaByf06gfS3HAoTJNc7eqz1Hf9fUORQGPUAnFK8cT3SfdA36\nd/o3ZWE1TTj1zYwlCLN5qRKr3hU8nC3xEYNEbkB9SfTRaOq9Q7P8WmfLkoCPm3pR\nmwIDAQAB\n-----END PUBLIC KEY-----\n";function dt(){try{return function(){if(h.default.existsSync(at)){const e=h.default.readFileSync(at,{encoding:"utf-8"});return A.default.verify(e,st,{algorithms:["RS256"]})}}()}catch(e){console.error("error retrieving offline license",e)}}var ut=Object.freeze({__proto__:null,getOfflineLicense:dt,writeOfflineLicenseToDisk:function(e){h.default.writeFileSync(at,e,{encoding:"utf-8"})},deleteOfflineLicense:function(){h.default.rmSync(at,{force:!0})}});const lt=()=>E(void 0,void 0,void 0,(function*(){let e=yield et();return!e&&t.env.isDev()&&(e=dt()),e})),ct=()=>t.env.SELF_HOSTED?Re:Ue,pt=()=>E(void 0,void 0,void 0,(function*(){yield gt(),yield ft()}));let vt=(e,i={refreshVersion:!0})=>E(void 0,void 0,void 0,(function*(){const o=Be(),n=t.tenancy.getTenantId(),r=yield w();let a=yield r.get(n);if(a&&a.version!==o&&i.refreshVersion&&(console.log(`Refreshing license version from=${a.version} to=${o}`),yield r.delete(n),a=void 0),!a){const t=i.populateLicense?i.populateLicense:lt;if(a=yield t(n),!a){a=(i.populateFreeLicense?i.populateFreeLicense:ct)(e,n)}a.refreshedAt=(new Date).toISOString(),a.version=o,yield r.store(n,a,3600)}return a}));t.env.isJest()&&(vt=jest.fn());const ft=vt,gt=()=>E(void 0,void 0,void 0,(function*(){const e=t.tenancy.getTenantId(),i=yield w();yield i.delete(e)}));var yt=Object.freeze({__proto__:null,refresh:pt,getCachedLicense:ft,invalidate:gt}),mt=Object.freeze({__proto__:null,cache:yt,client:ot,offline:ut,getLicenseInfo:()=>E(void 0,void 0,void 0,(function*(){return V()})),deleteLicenseInfo:()=>E(void 0,void 0,void 0,(function*(){yield E(void 0,void 0,void 0,(function*(){const e=yield V();if(e)return t.tenancy.getGlobalDB().remove(t.StaticDatabases.GLOBAL.docs.licenseInfo,e._rev)})),yield pt()})),activateLicenseKey:e=>E(void 0,void 0,void 0,(function*(){yield it(e),yield Y(e),yield pt()})),getLicense:lt,getFreeLicense:ct});function ht(e){return E(this,void 0,void 0,(function*(){const t=yield ft();return null==t?void 0:t.features.includes(e)}))}function bt(e){return E(this,void 0,void 0,(function*(){if(!(yield ht(e)))throw new t.FeatureDisabledError(`${e} is not currently enabled`,e)}))}function At(t){return(...i)=>E(this,void 0,void 0,(function*(){return yield bt(e.Feature.APP_BACKUPS),t(...i)}))}function St(){return E(this,void 0,void 0,(function*(){return ht(e.Feature.APP_BACKUPS)}))}function Ot(){return E(this,void 0,void 0,(function*(){return ht(e.Feature.BRANDING)}))}function It(){return E(this,void 0,void 0,(function*(){return ht(e.Feature.ENFORCEABLE_SSO)}))}const _t=()=>E(void 0,void 0,void 0,(function*(){const i=e.Feature.SCIM,o=yield ht(i),n=yield t.configs.getSCIMConfig();if(!o||!(null==n?void 0:n.enabled))throw new t.FeatureDisabledError(`${i} is not currently enabled`,i);return!0}));var Et=Object.freeze({__proto__:null,checkFeature:bt,checkBackups:At,isBackupsEnabled:St,isBrandingEnabled:Ot,isEnforceableSSO:It,isSSOEnforced:function(e){return E(this,void 0,void 0,(function*(){if(t.env.ENABLE_SSO_MAINTENANCE_MODE)return!1;if(!(yield It()))return!1;let i;return i=(null==e?void 0:e.config)?e.config:yield t.configs.getSettingsConfig(),!!i.isSSOEnforced}))},checkSCIM:_t});const Tt={faviconUrl:void 0,faviconUrlEtag:void 0,emailBrandingEnabled:!0,testimonialsEnabled:!0,platformTitle:void 0,loginHeading:void 0,loginButton:void 0,metaDescription:void 0,metaImageUrl:void 0,metaTitle:void 0};var wt=Object.freeze({__proto__:null,getBrandingConfig:function(e){return E(this,void 0,void 0,(function*(){return(yield Ot())?{faviconUrl:e.faviconUrl,faviconUrlEtag:e.faviconUrlEtag,emailBrandingEnabled:e.emailBrandingEnabled,testimonialsEnabled:e.testimonialsEnabled,platformTitle:e.platformTitle,loginHeading:e.loginHeading,loginButton:e.loginButton,metaDescription:e.metaDescription,metaImageUrl:e.metaImageUrl,metaTitle:e.metaTitle}:Tt}))}});const Dt=(e,t,i)=>Ut(1,e,t,i),Pt=(e,t,i,o)=>Ut(e,t,i,o),Ut=(e,t,i,o={})=>E(void 0,void 0,void 0,(function*(){let n;return yield Lt(e,t,i,{dryRun:!0,suppressErrorLog:o.suppressErrorLog,id:o.id}),o.fn&&(n=yield o.fn()),yield Lt(e,t,i,{dryRun:!1,valueFn:o.valueFn,suppressErrorLog:o.suppressErrorLog,id:o.id}),n})),Rt=(e,t,i={})=>Lt(-1,e,t,i),kt=(e,t,i,o={})=>Lt(-e,t,i,o),Nt=(e,t,i)=>E(void 0,void 0,void 0,(function*(){return x(i,e,t)})),Bt=(i,o,n,r)=>E(void 0,void 0,void 0,(function*(){try{yield t.locks.doWithLock({type:e.LockType.TRY_ONCE,name:e.LockName.TRIGGER_QUOTA,resource:i,ttl:1e4},(()=>E(void 0,void 0,void 0,(function*(){const e={percentage:n,name:o.name};r&&(e.resetDate=r),yield tt(e)}))))}catch(e){t.logging.logAlert("Error triggering quota",e)}})),jt=(t,i,o,n)=>E(void 0,void 0,void 0,(function*(){const r=yield Q(),a=t===e.QuotaUsageType.MONTHLY?r.quotaReset:void 0,s=yield((t,i,o)=>{if(t==e.QuotaUsageType.STATIC){const e=o.usageQuota.triggers;return e&&e[i]||{}}{const e=R(),t=o.monthly[e].triggers;return t&&t[i]||{}}})(t,i,r),d=n.triggers;let u=o/n.value*100;u>100&&(u=100);for(const[e,t]of d.entries()){if(u>=t&&-1!==n.value){if(!s[t]){s[t]=(new Date).toISOString();(!(u>=(d[e+1]||100))||u===t)&&(yield Bt(i,n,u,a))}}else s[t]=void 0}return s})),Lt=(i,o,n,r={})=>E(void 0,void 0,void 0,(function*(){let a=null;try{a=t.context.getAppId()}catch(e){}if(e.APP_QUOTA_NAMES.includes(o)&&!a)throw new Error("App context required for quota update");try{const a=yield Ct(e.QuotaType.USAGE,o,n);let{total:s,app:d,breakdown:u}=yield K(n,o,r.id);s+=i,null!=d&&(d+=i),null!=u&&(u+=i);let l={};if(r.dryRun||(l=yield jt(n,o,s,a)),-1!==a.value&&s>a.value&&i>0)throw new t.UsageLimitError(`Licensed ${a.name} of ${a.value} has been exceeded`,a.name);if(s=Math.max(0,s),d&&(d=Math.max(0,d)),u&&(u=Math.max(0,u)),r.dryRun)return;r.valueFn&&(s=yield r.valueFn(),d=s),yield z(o,n,{total:s,app:d,breakdown:u,triggers:l},r)}catch(e){throw r.suppressErrorLog||console.error(`Error updating usage quotas for ${o}`,e),e}})),Ct=(i,o,n)=>E(void 0,void 0,void 0,(function*(){const r=yield ft();if(!r){const e=t.tenancy.getTenantId();throw new Error("License not found for tenant id "+e)}if(n&&e.isStaticQuota(i,n,o))return r.quotas[i][n][o];if(n&&e.isMonthlyQuota(i,n,o))return r.quotas[i][n][o];if(e.isConstantQuota(i,o))return r.quotas[i][o];throw new Error("Invalid quota type")})),$t=(e,i)=>E(void 0,void 0,void 0,(function*(){try{return yield Lt(1,e,i,{dryRun:!0}),!1}catch(e){if(e.code===t.ErrorCode.USAGE_LIMIT_EXCEEDED)return!0;throw e}})),Gt=()=>E(void 0,void 0,void 0,(function*(){const e=yield t.db.getAllApps({dev:!0});return e?e.length:0})),Qt=864e5;function xt(i){return E(this,void 0,void 0,(function*(){const o=i.user;if(!o||!o._id)return;let n;o.dayPassRecordedAt&&(n=new Date(o.dayPassRecordedAt));const r=new Date(Date.now()-Qt);if(!n||n.getTime()<r.getTime())try{yield function(i){var o,n;return E(this,void 0,void 0,(function*(){t.env.SELF_HOSTED&&(null===(n=null===(o=i.license)||void 0===o?void 0:o.plan)||void 0===n?void 0:n.type)===e.PlanType.FREE||t.env.isDev()&&t.env.DISABLE_ACCOUNT_PORTAL||(yield Jt(i._id))}))}(o),yield function(){return E(this,void 0,void 0,(function*(){return Dt(e.MonthlyQuotaName.DAY_PASSES,e.QuotaUsageType.MONTHLY,{suppressErrorLog:!0})}))}(),yield function(e){return E(this,void 0,void 0,(function*(){const i=t.tenancy.getGlobalDB();let o=yield i.get(e._id);const n=new Date,r=(new Date).toISOString();e.dayPassRecordedAt=r,o.dayPassRecordedAt=r;try{console.log(`Recording day pass for user=${e._id}`),yield i.put(o)}catch(t){if(409!==t.status)throw t;if(console.warn(`Conflict recording day pass for user=${e._id}`),o=yield i.get(e._id),!o.dayPassRecordedAt||new Date(o.dayPassRecordedAt).getDay()!==n.getDay())throw console.error(`Day pass not recorded for user=${e._id}`),t;console.log(`Day pass already recorded for user=${e._id}`)}yield t.cache.user.invalidateUser(e._id)}))}(o)}catch(e){if("usage_limit_exceeded"!=e.code)throw e;t.utils.isServingApp(i)&&i.redirect("/")}}))}const qt=t=>E(void 0,void 0,void 0,(function*(){return Dt(e.StaticQuotaName.USER_GROUPS,e.QuotaUsageType.STATIC,{fn:t})})),Mt=()=>E(void 0,void 0,void 0,(function*(){return Rt(e.StaticQuotaName.USER_GROUPS,e.QuotaUsageType.STATIC)})),Ft=t=>E(void 0,void 0,void 0,(function*(){return Dt(e.StaticQuotaName.PLUGINS,e.QuotaUsageType.STATIC,{fn:t})})),zt=()=>E(void 0,void 0,void 0,(function*(){return Rt(e.StaticQuotaName.PLUGINS,e.QuotaUsageType.STATIC)})),Kt=t=>E(void 0,void 0,void 0,(function*(){return Nt(e.StaticQuotaName.PLUGINS,e.QuotaUsageType.STATIC,t)}));var Yt=Object.freeze({__proto__:null,utils:C,bustCache:()=>E(void 0,void 0,void 0,(function*(){const e=G();try{const i=yield e.get(t.db.StaticDatabases.GLOBAL.docs.usageQuota);(null==i?void 0:i._rev)&&(yield e.remove(t.db.StaticDatabases.GLOBAL.docs.usageQuota,null==i?void 0:i._rev))}catch(e){if(404!==e.status)throw e}})),getQuotaUsage:Q,setUsage:x,setUsagePerApp:(e,t,i)=>E(void 0,void 0,void 0,(function*(){const o=G();let n=yield Q();const r=Object.values(e).reduce(((e,t)=>e+t),0);for(let[o,a]of Object.entries(e))n=F(n,t,i,{total:r,app:a},{appId:o});const a=yield o.put(n);return n._rev=a.rev,n})),setAppUsageValue:q,setAllUsage:z,getCurrentUsageValues:K,addApp:(t,{appId:i}={})=>E(void 0,void 0,void 0,(function*(){return Dt(e.StaticQuotaName.APPS,e.QuotaUsageType.STATIC,{fn:t,valueFn:Gt,id:i})})),removeApp:({appId:t}={})=>E(void 0,void 0,void 0,(function*(){return Rt(e.StaticQuotaName.APPS,e.QuotaUsageType.STATIC,{valueFn:Gt,id:t})})),addQuery:(t,{datasourceId:i}={})=>E(void 0,void 0,void 0,(function*(){return Dt(e.MonthlyQuotaName.QUERIES,e.QuotaUsageType.MONTHLY,{fn:t,id:i})})),addRow:(t,{tableId:i}={})=>E(void 0,void 0,void 0,(function*(){return Dt(e.StaticQuotaName.ROWS,e.QuotaUsageType.STATIC,{fn:t,id:i})})),removeRow:({tableId:t}={})=>E(void 0,void 0,void 0,(function*(){return Rt(e.StaticQuotaName.ROWS,e.QuotaUsageType.STATIC,{id:t})})),addRows:(t,i,{tableId:o}={})=>E(void 0,void 0,void 0,(function*(){return Pt(t,e.StaticQuotaName.ROWS,e.QuotaUsageType.STATIC,{fn:i,id:o})})),removeRows:(t,{tableId:i}={})=>E(void 0,void 0,void 0,(function*(){return kt(t,e.StaticQuotaName.ROWS,e.QuotaUsageType.STATIC,{id:i})})),addAutomation:(t,{automationId:i}={})=>E(void 0,void 0,void 0,(function*(){return Dt(e.MonthlyQuotaName.AUTOMATIONS,e.QuotaUsageType.MONTHLY,{fn:t,id:i})})),checkDayPass:xt,addGroup:qt,removeGroup:Mt,addPlugin:Ft,removePlugin:zt,updatePluginCount:Kt,addUsers:(i,o)=>E(void 0,void 0,void 0,(function*(){const n=yield Pt(i,e.StaticQuotaName.USERS,e.QuotaUsageType.STATIC,{fn:o,valueFn:t.users.getUserCount});return yield et(),n})),removeUsers:i=>E(void 0,void 0,void 0,(function*(){yield kt(i,e.StaticQuotaName.USERS,e.QuotaUsageType.STATIC,{valueFn:t.users.getUserCount}),yield et()})),increment:Dt,incrementMany:Pt,decrement:Rt,decrementMany:kt,set:Nt,updateUsage:Lt,getLicensedQuota:Ct,usageLimitIsExceeded:$t});const Vt=new D(t.env.ACCOUNT_PORTAL_URL),Ht=(e,i)=>E(void 0,void 0,void 0,(function*(){if(yield t.featureFlags.isEnabled(t.featureFlags.TenantFeatureFlag.LICENSING)){const t=yield Wt(),o=Object.assign(Object.assign({},i),{headers:Object.assign(Object.assign({},i.headers),t)});return e(o)}})),Wt=()=>E(void 0,void 0,void 0,(function*(){if(t.env.SELF_HOSTED){const e=yield V();if(e){const i=e.licenseKey;return{[t.constants.Header.LICENSE_KEY]:i}}return{}}{const e=t.tenancy.getTenantId();return{[t.constants.Header.API_KEY]:t.env.ACCOUNT_PORTAL_API_KEY,[t.constants.Header.TENANT_ID]:e}}})),Jt=e=>E(void 0,void 0,void 0,(function*(){const i={timestamp:Date.now()};return((e,i)=>E(void 0,void 0,void 0,(function*(){const o=yield Ht((t=>Vt.post(`/api/users/${e}/activity`,t)),{body:i});if(o){if(201!==o.status){const e=`Error creating account user activity: ${yield o.text()}`;throw t.logging.logAlert(e),new Error(e)}return o.json()}})))(e,i)}));var Xt=Object.freeze({__proto__:null,createActivity:Jt});const{SEPARATOR:Zt,UNICODE_MAX:ei,DocumentType:ti,AutomationViewMode:ii,ViewName:oi,getQueryIndex:ni}=t.db,ri=new Date(0).toISOString(),ai=100,si=()=>E(void 0,void 0,void 0,(function*(){return xe(e.ConstantQuotaName.AUTOMATION_LOG_RETENTION_DAYS)}));function di(e,t,{status:i,automationId:o}={},n={}){const r=o?`${o}${Zt}`:"",a=i?`${i}${Zt}`:"";let s;return s=i&&o?`${ii.ALL}${Zt}${a}${r}`:i?`${ii.STATUS}${Zt}${a}`:o?`${ii.AUTOMATION}${Zt}${r}`:`${ti.AUTOMATION_LOG}${Zt}`,Object.assign(Object.assign({},n),{descending:!0,startkey:`${s}${t}${ei}`,endkey:`${s}${e}`})}function ui(t){var i,o,n;let r=e.AutomationStatus.SUCCESS,a=!0;for(let s of t.steps){const t=null===(o=null===(i=s.outputs)||void 0===i?void 0:i.status)||void 0===o?void 0:o.toLowerCase(),d="stopped_error"===t;if(!a||d){if(d){r=e.AutomationStatus.STOPPED_ERROR;break}if(!(null===(n=s.outputs)||void 0===n?void 0:n.success)){r=e.AutomationStatus.ERROR;break}if("stopped"===t){r=e.AutomationStatus.STOPPED;break}}else a=!1}return r}function li(e,i,o={docs:!0}){return E(this,void 0,void 0,(function*(){let n=t.context.getProdAppDB();(yield n.exists())||(n=t.context.getDevAppDB());let r={status:o.status},a=(null==o?void 0:o.limit)?o.limit:(null==o?void 0:o.paginate)?Ce+1:void 0;const s=di(e,i,r,{include_docs:o.docs,limit:a});return(null==o?void 0:o.page)&&(s.startkey=o.page),le(yield n.allDocs(s),{paginate:null==o?void 0:o.paginate,pageSize:Ce})}))}function ci(e,i,o={}){return E(this,void 0,void 0,(function*(){let n,r=t.context.getProdAppDB();(yield r.exists())||(r=t.context.getDevAppDB());try{let t={automationId:null==o?void 0:o.automationId,status:null==o?void 0:o.status};const a=di(e,i,t,{include_docs:!0,limit:Ce});(null==o?void 0:o.page)&&(a.startkey=o.page),n=yield r.query(ni(oi.AUTOMATION_LOGS),a)}catch(n){if(null==n||"not_found"!==n.name&&"not_found"!==n.error)throw n;return yield function(){return E(this,void 0,void 0,(function*(){const e=t.context.getProdAppDB(),i=`function(doc) {\n if (doc._id.startsWith("${ye}")) {\n let autoId = doc.automationId + "${ve}"\n let status = doc.status + "${ve}"\n let autoKey = "${pe.AUTOMATION}${ve}" + autoId + doc.createdAt\n let statusKey = "${pe.STATUS}${ve}" + status + doc.createdAt\n let allKey = "${pe.ALL}${ve}" + status + autoId + doc.createdAt\n emit(statusKey)\n emit(autoKey)\n emit(allKey)\n }\n }`;yield ge(e,i,ce.AUTOMATION_LOGS)}))}(),ci(e,i,o)}return le(n)}))}function pi(e,i){return E(this,void 0,void 0,(function*(){const o=t.context.getProdAppDB(),n=e._id,r=e.name,a=ui(i),s=(new Date).toISOString(),d=function(e,t,i){return`${ti.AUTOMATION_LOG}${Zt}${e}${Zt}${i}${Zt}${t}`}(s,a,n),u=Object.assign(Object.assign({},i),{automationId:n,status:a,automationName:r,createdAt:s,_id:d});return yield o.put(u),d}))}function vi(e,{clearing:i}={clearing:!1}){return E(this,void 0,void 0,(function*(){const o=t.context.getProdAppDB();yield function(e,i){return E(this,void 0,void 0,(function*(){let o,n=5,r=!1;for(;n>0;n--)try{o=yield e(),r=!0;break}catch(e){}return r||t.logging.logAlert("Failed to backoff",i),o}))}((()=>E(this,void 0,void 0,(function*(){const n=yield o.get(t.db.DocumentType.APP_METADATA);for(let o of e){const e=o.split(t.db.SEPARATOR),r=`${e[e.length-3]}${t.db.SEPARATOR}${e[e.length-2]}`;let a={};n.automationErrors&&(a=n.automationErrors),Array.isArray(a[r])||(a[r]=[]);const s=a[r].indexOf(o);i&&-1!==s?a[r].splice(s,1):a[r].push(o),0===a[r].length&&delete a[r],n.automationErrors=a}yield o.put(n),yield t.cache.app.invalidateAppMetadata(n.appId,n)}))),"Failed to update app metadata with automation log error")}))}function fi(){return E(this,void 0,void 0,(function*(){const i=t.context.getProdAppDB();try{const o=yield function(){return E(this,void 0,void 0,(function*(){const e=yield si();try{return yield li(ri,e,{docs:!1,paginate:!1,limit:ai})}catch(e){return{data:[],hasNextPage:!1}}}))}();if(!o.data||0===o.data.length)return;const n=o.data.map((e=>({_id:e.id,_rev:e.value.rev,_deleted:!0}))),r=o.data.filter((i=>{const o=i.id.split(t.db.SEPARATOR);return o[o.length-1]===e.AutomationStatus.ERROR})).map((e=>e.id));yield i.bulkDocs(n),r.length&&(yield vi(r,{clearing:!0}))}catch(e){t.logging.logAlert(`Failed to cleanup automation log history - Database "${i.name}"`,e)}}))}const gi=si;var yi=Object.freeze({__proto__:null,oldestLogDate:gi,logSearch:function(e){return E(this,void 0,void 0,(function*(){return yield fi(),yield function(e,t,i,o){return E(this,void 0,void 0,(function*(){let n,r=(new Date).toISOString();const a=yield gi();return(!e||e<a)&&(e=a),n=i||t?yield ci(e,r,{automationId:i,status:t,page:o}):yield li(e,r,{status:t,page:o,docs:!0,paginate:!0}),n}))}(e.startDate,e.status,e.automationId,e.page)}))},storeLog:function(i,o){return E(this,void 0,void 0,(function*(){if(!t.db.isProdAppID(t.context.getAppId()))return;const n=ui(o),r=yield pi(i,o);n===e.AutomationStatus.ERROR&&(yield vi([r])),yield fi()}))}}),mi=Object.freeze({__proto__:null,logs:yi});class hi extends t.HTTPError{constructor(e){super(`Group name "${e}" is unavailable`,409)}}function bi(e,i){return E(this,void 0,void 0,(function*(){try{let o=[];for(let n of e)n.roles&&o.push(n.roles[t.db.getProdAppID(i)]);const n=yield Promise.all(o.map((e=>E(this,void 0,void 0,(function*(){return{[e]:yield t.roles.roleToNumber(e)}})))));let r,a=0;const s={};n.forEach((e=>{const[t,i]=Object.entries(e)[0];s[t]={roleId:t,roleNum:i}}));for(let{roleId:e,roleNum:t}of Object.values(s))t>a&&(a=t,r=e);return r}catch(o){throw t.logging.logAlert(`Error finding higest role for ${e.length} on app ${i}`,o),o}}))}function Ai(){return E(this,void 0,void 0,(function*(){return yield ae()}))}function Si(e){return E(this,void 0,void 0,(function*(){return yield se(e)}))}function Oi(e,t={enriched:!0}){return E(this,void 0,void 0,(function*(){return yield de(e,t)}))}function Ii(e){return E(this,void 0,void 0,(function*(){const i=yield function(e){return E(this,void 0,void 0,(function*(){try{const i=yield t.db.directCouchFind(t.tenancy.getGlobalDBName(),{selector:{name:{$regex:`^(?i)${e}$`}},limit:1}),[o]=i.rows;if(!o)return;return yield re(o)}catch(e){throw e}}))}(e);if(i)throw new hi(e)}))}function _i(e){return E(this,void 0,void 0,(function*(){let i=[],o=!e._id;if(delete e.users,e._id){const o=yield se(e._id);o.name!==e.name&&(yield Ii(e.name)),i.push(t.events.group.updated(e)),JSON.stringify(o.roles)!==JSON.stringify(e.roles)&&i.push(t.events.group.permissionsEdited(e))}else e._id=`${oe}${t.utils.newid()}`,yield Ii(e.name),i.push(t.events.group.created(e));try{yield Promise.all(i);const n=()=>function(e){return E(this,void 0,void 0,(function*(){const i=t.tenancy.getGlobalDB();return yield i.put(e)}))}(e);return o?yield qt(n):yield n()}catch(e){throw e}}))}function Ei(e,i){return E(this,void 0,void 0,(function*(){let o;try{o=yield se(e)}catch(e){throw new Error("Group not found")}try{let n=yield ue(e,i);return yield t.events.group.deleted(o),yield Mt(),n}catch(e){throw e}}))}function Ti(e,i){return E(this,void 0,void 0,(function*(){const o=yield se(e),n=yield t.users.bulkGetGlobalUsersById(i);let r=[];for(let t of n)t.userGroups||(t.userGroups=[]),t.userGroups.includes(e)||(t.userGroups.push(e),r.push(t));yield t.users.bulkUpdateGlobalUsers(r);let a=[];for(let e of i)a.push(t.cache.user.invalidateUser(e));return yield Promise.all(a),r.length&&(yield t.events.group.usersAdded(r.length,o)),r}))}function wi(e,i){return E(this,void 0,void 0,(function*(){const o=yield se(e),n=yield t.users.bulkGetGlobalUsersById(i);let r=[];for(let t of n){if(!t.userGroups||!t.userGroups.includes(e))continue;const i=t.userGroups.indexOf(e);t.userGroups.splice(i,1),r.push(t)}yield t.users.bulkUpdateGlobalUsers(r);let a=[];for(let e of i)a.push(t.cache.user.invalidateUser(e));return yield Promise.all(a),r.length&&(yield t.events.group.usersDeleted(r.length,o)),r}))}function Di(e,t){return E(this,void 0,void 0,(function*(){const i=yield Si(e);if(i.roles||(i.roles={}),t.appsToAdd)for(let e of t.appsToAdd)i.roles[e.appId]=e.roleId;if(t.appsToRemove)for(let e of t.appsToRemove)delete i.roles[e.appId];return yield _i(i)}))}var Pi=Object.freeze({__proto__:null,getGroupRoleId:function(e,i,o){var n;return E(this,void 0,void 0,(function*(){if(!e.userGroups)return null;let r;r=(null==o?void 0:o.groups)?o.groups.filter((t=>e.userGroups.includes(t._id))):yield de(e.userGroups,{enriched:!1});const a=t.db.getProdAppID(i);return(null===(n=e.roles)||void 0===n?void 0:n[a])?e.roles[a]:(r=r.filter((e=>{if(!(null==e?void 0:e.roles))return!1;return Object.keys(e.roles).includes(a)})),yield bi(r,i))}))},enrichUserRolesFromGroups:function(e){return E(this,void 0,void 0,(function*(){if(!e||!e.userGroups)return e;const t=yield Oi(e.userGroups,{enriched:!1});let i=[];for(let e of t)(null==e?void 0:e.roles)&&(i=i.concat(Object.keys(e.roles)));i=[...new Set(i)];for(let o of i){if(e.roles[o])continue;const i=yield bi(t,o);i&&(e.roles[o]=i)}return e}))},fetch:Ai,get:Si,getBulk:Oi,save:_i,remove:Ei,addUsers:Ti,removeUsers:wi,updateGroupApps:Di,cleanupApp:function(e){return E(this,void 0,void 0,(function*(){const i=yield Ai(),o=[];for(let t of i)t.roles&&t.roles[e]&&(delete t.roles[e],o.push(t));return yield function(e){return E(this,void 0,void 0,(function*(){const i=t.tenancy.getGlobalDB();return yield i.bulkDocs(e)}))}(o)}))}});var Ui=Object.freeze({__proto__:null,storePlugin:function(i,o,n){return E(this,void 0,void 0,(function*(){const a=t.tenancy.getGlobalDB(),s=i.package.version,d=i.package.name,u=i.package.description,l=i.schema.hash,c=t.objectStore.getPluginS3Dir(d),p=yield t.objectStore.uploadDirectory(t.objectStore.ObjectStoreBuckets.PLUGINS,o,c),v=p.find((e=>e.name.endsWith(".js"))),f=p.find((e=>e.name.endsWith(".svg")));if(!v)throw new Error("Plugin missing .js file.");if(i.schema.type===e.PluginType.DATASOURCE){const e=function(e,t){return h.default.readFileSync(r.join(e,t),"utf8")}(o,v.name);try{(0,eval)(e)}catch(e){const t=(null==e?void 0:e.message)?e.message:JSON.stringify(e);throw new Error(`JS invalid: ${t}`)}}const g=f?f.name:null,y=t.db.generatePluginID(d);let m;try{m=(yield a.get(y))._rev}catch(e){m=void 0}let b=Object.assign(Object.assign({_id:y,_rev:m},i),{name:d,version:s,hash:l,description:u});g&&(b.iconFileName=g),n&&(b=Object.assign(Object.assign({},b),{source:n}));const A=()=>E(this,void 0,void 0,(function*(){const e=yield a.put(b);return yield t.events.plugin.imported(b),Object.assign(Object.assign({},b),{_rev:e.rev})}));return m?yield A():yield Ft(A)}))},deletePlugin:function(e){return E(this,void 0,void 0,(function*(){const i=t.tenancy.getGlobalDB();try{const o=yield i.get(e),n=t.objectStore.getPluginS3Dir(o.name);yield t.objectStore.deleteFolder(t.objectStore.ObjectStoreBuckets.PLUGINS,n),yield i.remove(e,o._rev),yield t.events.plugin.deleted(o),yield zt()}catch(e){const t=(null==e?void 0:e.message)?null==e?void 0:e.message:e;throw new Error(`Failed to delete plugin: ${t}`)}}))},checkPluginQuotas:function(){return E(this,void 0,void 0,(function*(){const e=t.tenancy.getGlobalDB();try{const i=(yield e.allDocs(t.db.getPluginParams())).rows.length;console.log(`Syncing plugin count: ${i}`),yield Kt(i)}catch(e){t.logging.logAlert("Unable to retrieve plugins for quota check",e)}}))}});function Ri(){return!!t.env.ENCRYPTION_KEY}function ki(){return E(this,void 0,void 0,(function*(){const e=yield He();return Object.keys(e.variables)}))}function Ni(i){return E(this,void 0,void 0,(function*(){if(!(yield ft()).features.includes(e.Feature.ENVIRONMENT_VARIABLES))throw new Error("User does not have access to environment variables feature.");const o=yield He();o.variables=i(o.variables),yield function(e){return E(this,void 0,void 0,(function*(){const i=Ve(),o=t.tenancy.getGlobalDB();return yield o.put({_id:e._id||i,_rev:e._rev||void 0,variables:t.encryption.encrypt(JSON.stringify(e.variables),t.encryption.SecretOption.ENCRYPTION)})}))}(o)}))}function Bi(e,t){return E(this,void 0,void 0,(function*(){if(!Li(e))throw new Error("Variable name has characters that are not allowed");yield Ni((i=>(i[e]=t,i)))}))}function ji(e){return E(this,void 0,void 0,(function*(){yield Ni((t=>(delete t[e],t)))}))}function Li(e){return/^[a-zA-Z0-9-_]+$/.test(e)}var Ci=Object.freeze({__proto__:null,isEncryptionKeyAvailable:Ri,fetch:ki,fetchValues:function(t){return E(this,void 0,void 0,(function*(){const i=(yield He()).variables,o={};for(let[n,r]of Object.entries(i))switch(t){case e.AppEnvironment.DEVELOPMENT:o[n]=r.development;break;case e.AppEnvironment.PRODUCTION:default:o[n]=r.production}return o}))},update:Bi,remove:ji,isValid:Li});const $i=require("memorystream");function Gi(e){return E(this,void 0,void 0,(function*(){var i;e._id||(e._id=(i=e.timestamp,`${t.DocumentType.AUDIT_LOG}${t.SEPARATOR}${i}${t.SEPARATOR}${t.utils.newid()}`));try{const i=t.context.getAuditLogsDB(),o=yield i.put(e);return Object.assign(Object.assign({},e),{_rev:o.rev})}catch(e){t.logging.logAlert("Failed to write audit log",e)}}))}const{processStringSync:Qi,findHBSBlocks:xi}=require("@budibase/string-templates"),qi=t.constants.MIN_VALID_DATE.toISOString(),Mi=t.constants.MAX_VALID_DATE.toISOString();var Fi;function zi(e){return(e.startDate||e.endDate)&&(e.startDate=e.startDate||qi,e.endDate=e.endDate||Mi),e}function Ki(e,t){for(let i of t)e=e.replace(new RegExp(i,"g"),`\\${i}`);return e}function Yi(t,i,o){const n={_id:t,status:e.AuditLogResourceStatus.DELETED};switch(i){case Fi.APP:n.name=null==o?void 0:o.appName;break;case Fi.USER:n.email=null==o?void 0:o.email}return n}function Vi(e){const t=xi(e);for(let i of t){const t=` "${i}"`;e=e.replace(e.includes(t)?t:` ${i}`,""),e=Qi(e,{})}return e}function Hi(){return E(this,void 0,void 0,(function*(){return(yield ft()).features.includes(e.Feature.AUDIT_LOGS)}))}function Wi(e){return E(this,void 0,void 0,(function*(){const i=e.map((e=>e.userId)),o=e.filter((e=>e.appId)).map((e=>t.db.getDevAppID(e.appId))),n=yield t.users.bulkGetGlobalUsersById([...new Set(i)],{cleanup:!0}),r=yield t.db.getAppsByIDs([...new Set(o)]);let a=[];for(let i of e){const e=n.find((e=>(null==e?void 0:e._id)===i.userId)),o=r.find((e=>t.db.isSameAppID(null==e?void 0:e.appId,i.appId))),s={event:i.event,timestamp:i.timestamp,name:i.name,metadata:i.metadata,user:e||Yi(i.userId,Fi.USER,i.fallback)};i.appId&&(s.app=o||Yi(i.appId,Fi.APP,i.fallback)),a.push(s)}return a}))}function Ji(i){return E(this,void 0,void 0,(function*(){if(!(yield Hi()))throw new Error("Audit logs not available - license required.");const o=function(e){Array.isArray(e.appIds)&&(e.appIds=e.appIds.map((e=>t.db.getProdAppID(e)))),Array.isArray(e.events)&&(e.events=e.events.map((e=>Ki(e,[":"]))));const i={};function o(e,t){(null==t?void 0:t.length)&&(i.oneOf=Object.assign(Object.assign({},i.oneOf),{[e]:t}))}if(o("userId",e.userIds),o("appId",e.appIds),o("event",e.events),e.fullSearch){const t=Ki(e.fullSearch,[":"," "]);i.equal={all:`("${t}" OR ${t}*)`}}return(e.startDate||e.endDate)&&(e=zi(e),i.range={timestamp:{high:e.endDate,low:e.startDate}}),0===Object.keys(i).length&&(i.notEmpty={event:!0}),i}(i),n=yield function(i,o){return E(this,void 0,void 0,(function*(){const n=t.context.getAuditLogDBName();return yield t.db.paginatedSearch(n,e.SearchIndex.AUDIT,i,{disableEscaping:!0,indexer:H,limit:Ce,bookmark:o,sort:"timestamp",sortOrder:e.SortOrder.DESCENDING,sortType:e.SortType.STRING})}))}(o,i.bookmark);return{hasNextPage:n.hasNextPage,bookmark:n.bookmark,data:yield Wi(n.rows)}}))}function Xi(e){return function(e){const i=t.context.getAuditLogsDB(),o=new $i,n=i.dump(o,{filter:i=>{var o;const n=i;if(!(null===(o=n._id)||void 0===o?void 0:o.startsWith(t.DocumentType.AUDIT_LOG)))return!1;let r=!0;const a=(e,t)=>{e&&0!==e.length&&(r=!!(r&&t&&e.includes(t)))};if(a(e.userIds,n.userId),a(e.appIds,n.appId),a(e.events,n.event),(e.startDate||e.endDate)&&(r=r&&n.timestamp>=e.startDate&&n.timestamp<=e.endDate),e.fullSearch){const t=JSON.stringify(i);r=r&&t.includes(e.fullSearch)}return r}}),r=new $i;return o.on("data",(e=>{const t=JSON.parse(Buffer.from(e).toString());if(Array.isArray(t.docs)){let e="";for(let i of t.docs)e+=JSON.stringify(i)+"\n";r.write(e)}})),o.on("end",(()=>{r.end()})),{promise:n,stream:r}}(e=zi(e))}function Zi(){const t=Object.entries(e.AuditedEventFriendlyName).filter((e=>null!=e[1])),i={};for(let e of t)i[e[0]]=Vi(e[1]);return i}!function(e){e.USER="user",e.APP="app"}(Fi||(Fi={}));var eo=Object.freeze({__proto__:null,write:function(i,o,n){return E(this,void 0,void 0,(function*(){if(!(yield Hi())||!t.utils.isAudited(i))return;const r=function(t,i){const o=e.AuditedEventFriendlyName[t];if(!o)throw new Error("No friendly name found.");let n=Qi(o,i);return n.includes('""')&&(n=Vi(o)),n}(i,o);let a=new Date;(null==n?void 0:n.timestamp)&&(a=new Date(n.timestamp));const s={timestamp:a.toISOString(),event:i,name:r,userId:(null==n?void 0:n.userId)||e.AuditLogSystemUser,metadata:Object.assign(Object.assign({},o),null==n?void 0:n.hostInfo)},d={};try{if(null==n?void 0:n.appId){s.appId=t.db.getProdAppID(n.appId);const e=yield t.cache.app.getAppMetadata(n.appId);d.appName=e.name}if(null==n?void 0:n.userId){const e=yield t.users.getById(null==n?void 0:n.userId);d.email=e.email}}catch(e){t.logging.logAlert("Failed to retrieve fallback information for audit log",e)}return s.fallback=d,yield Gi(s)}))},fetch:Ji,download:Xi,definitions:Zi});let to;function io(){return to}function oo(e,t={}){return E(this,void 0,void 0,(function*(){return ze(e,t)}))}function no(t){const i=(new Date).toISOString();switch(t){case e.AppBackupStatus.COMPLETE:case e.AppBackupStatus.FAILED:return{timestamp:i,finishedAt:i};case e.AppBackupStatus.STARTED:return{timestamp:i,startedAt:i};case e.AppBackupStatus.PENDING:return{timestamp:i,createdAt:i}}}function ro(e){return E(this,void 0,void 0,(function*(){return Ke(e)}))}const ao={isEnabled:St,triggerAppRestore:At((function(t,i,o,n){return E(this,void 0,void 0,(function*(){const r=yield ro(i);let a;try{a=yield oo({appId:t,timestamp:(new Date).toISOString(),status:e.AppBackupStatus.PENDING,type:e.AppBackupType.RESTORE,createdBy:n})}catch(e){if(409===(null==e?void 0:e.status))return;throw e}return yield io().add({appId:t,docId:a.id,docRev:a.rev,import:{nameForBackup:o,backupId:i,createdBy:n}}),{restoreId:a.id,metadata:r}}))})),triggerAppBackup:At((function(i,o,n={}){return E(this,void 0,void 0,(function*(){let r;try{r=yield oo(Object.assign({appId:i,trigger:o,timestamp:(new Date).toISOString(),status:e.AppBackupStatus.PENDING,type:e.AppBackupType.BACKUP},n))}catch(e){if(409===e.status)return;throw e}return yield io().add({docId:r.id,docRev:r.rev,appId:i,export:Object.assign({trigger:o},n)}),yield t.events.backup.appBackupTriggered(i,r.id,e.AppBackupType.BACKUP,o,null==n?void 0:n.name),r.id}))})),downloadAppBackup:At((function(e){return E(this,void 0,void 0,(function*(){const i=yield Ke(e);if(!i.filename)throw new Error("Backup incomplete - cannot download.");return{metadata:i,path:yield t.objectStore.retrieveToTmp(t.objectStore.ObjectStoreBuckets.BACKUPS,i.filename)}}))})),fetchAppBackups:At((function(e,i){return E(this,void 0,void 0,(function*(){return function(e,i={}){return E(this,void 0,void 0,(function*(){const o=t.tenancy.getGlobalDB();let n;const r=i.limit||Ce,a=yield Me(e,i,{include_docs:!0,limit:r+1});i.page&&(a.startkey=i.page),n=i.trigger&&i.type?yield Fe(o,a):yield o.allDocs(a);const s=le(n,{paginate:i.paginate,pageSize:r}),d=[...new Set(s.data.filter((e=>e.createdBy)).map((e=>e.createdBy)))],u=yield t.users.bulkGetGlobalUsersById(d,{cleanup:!0});for(let e of u)for(let t of s.data)(null==e?void 0:e._id)===t.createdBy&&(t.createdBy=e);return s}))}(e,i)}))})),storeAppBackupMetadata:At(oo),updateBackupStatus:At((function(t,i,o,n,r){return E(this,void 0,void 0,(function*(){const a=yield ro(t);return yield ze(Object.assign(Object.assign(Object.assign({},a),no(o)),{contents:n,status:o,type:e.AppBackupType.BACKUP}),{filename:r,docId:t,docRev:i})}))})),updateRestoreStatus:At((function(t,i,o){return E(this,void 0,void 0,(function*(){const n=yield ro(t);return yield ze(Object.assign(Object.assign(Object.assign({},n),no(o)),{status:o,type:e.AppBackupType.RESTORE,trigger:e.AppBackupTrigger.MANUAL}),{docId:t,docRev:i})}))})),getAppBackup:At(ro),updateAppBackup:At((function(e,i){return E(this,void 0,void 0,(function*(){return function(e,i){return E(this,void 0,void 0,(function*(){const o=t.tenancy.getGlobalDB(),n=yield o.get(e);return n.name=i,yield o.put(n)}))}(e,i)}))})),deleteAppBackup:At((function(e){return E(this,void 0,void 0,(function*(){const i=yield Ke(e);return i.filename&&(yield t.objectStore.deleteFile(t.objectStore.ObjectStoreBuckets.BACKUPS,i.filename)),function(e){return E(this,void 0,void 0,(function*(){const i=t.tenancy.getGlobalDB(),o=yield i.get(e);yield i.remove(o._id,o._rev)}))}(e)}))}))};function so(i){return E(this,void 0,void 0,(function*(){yield io().process((o=>E(this,void 0,void 0,(function*(){const n=o.data;try{if(n.export)return function(i,o){return E(this,void 0,void 0,(function*(){const n=i.data,r=n.appId,a=n.export.trigger,s=n.export.name,d=t.tenancy.getTenantIDFromAppID(r);yield t.tenancy.doInTenant(d,(()=>E(this,void 0,void 0,(function*(){const{rev:t}=yield ao.updateBackupStatus(n.docId,n.docRev,e.AppBackupStatus.STARTED);return uo(a,d,r,{processing:o,doc:{id:n.docId,rev:t},name:s})}))))}))}(o,i);if(n.import)return function(i,o){return E(this,void 0,void 0,(function*(){const n=i.data,r=n.appId,a=n.import.backupId,s=n.import.nameForBackup,d=n.import.createdBy,u=t.tenancy.getTenantIDFromAppID(r);return t.tenancy.doInTenant(u,(()=>E(this,void 0,void 0,(function*(){const i=t.db.getDevAppID(r),{rev:l}=yield ao.updateRestoreStatus(n.docId,n.docRev,e.AppBackupStatus.STARTED);yield uo(e.AppBackupTrigger.RESTORING,u,r,{processing:o,createdBy:d,name:s});const{path:c}=yield ao.downloadAppBackup(a);yield function(e){return E(this,void 0,void 0,(function*(){const i=t.db.getDB(e,{skip_setup:!0});yield i.destroy()}))}(i);let p=e.AppBackupStatus.COMPLETE;try{yield o.importAppFn(i,t.db.getDB(i),{file:{type:"application/gzip",path:c},key:c})}catch(i){t.logging.logAlert("App restore error",i),p=e.AppBackupStatus.FAILED}yield ao.updateRestoreStatus(n.docId,l,p)}))))}))}(o,i)}catch(e){t.logging.logAlert(`Failed to perform backup for app ID: ${n.appId}`,e)}}))))}))}function uo(i,o,n,r){return E(this,void 0,void 0,(function*(){const o=t.db.getDevAppID(n),a=t.db.getProdAppID(n),s=(new Date).toISOString(),d=(t,o)=>E(this,void 0,void 0,(function*(){(null==r?void 0:r.doc)?yield ao.updateBackupStatus(r.doc.id,r.doc.rev,t,null==o?void 0:o.contents,null==o?void 0:o.filename):yield ao.storeAppBackupMetadata({appId:a,timestamp:s,trigger:i,status:t,name:null==r?void 0:r.name,type:e.AppBackupType.BACKUP,contents:null==o?void 0:o.contents,createdBy:null==r?void 0:r.createdBy},{filename:null==o?void 0:o.filename})}));try{const n=yield r.processing.exportAppFn(o,{tar:!0}),u=yield r.processing.statsFn(o);let l=`${a}/backup-${s}.tar.gz`;const c=t.objectStore.ObjectStoreBuckets.BACKUPS;yield t.objectStore.upload({path:n,type:"application/gzip",bucket:c,filename:l,metadata:{name:null==r?void 0:r.name,trigger:i,timestamp:s,appId:a}}),yield d(e.AppBackupStatus.COMPLETE,{filename:l,contents:u}),h.default.existsSync(n)&&h.default.rmSync(n)}catch(i){t.logging.logAlert("App backup error",i),yield d(e.AppBackupStatus.FAILED)}}))}var lo=Object.freeze({__proto__:null,init:so});var co=Object.assign(Object.assign({},ao),{processing:lo,init:e=>E(void 0,void 0,void 0,(function*(){to=t.queue.createQueue(t.queue.JobQueue.APP_BACKUP),yield so(e.processing)})),getBackupQueue:io});function po(e){return E(this,void 0,void 0,(function*(){return(yield t.db.getAllApps({all:!0,idsOnly:!0})).includes(e)}))}var vo=Object.freeze({__proto__:null,appExists:po});class fo{constructor(i){this.get=i=>E(this,void 0,void 0,(function*(){var o,n;const r=t.tenancy.getGlobalDB(),a=new t.db.QueryBuilder(r.name,e.SearchIndex.USER);a.setIndexBuilder(t.db.searchIndexes.createUserIndex),a.setLimit(i.pageSize),a.addEqual("scimInfo.isSync",!0);for(const[e,t]of Object.entries(null!==(n=null===(o=i.filters)||void 0===o?void 0:o.equal)&&void 0!==n?n:{}))a.addEqual(e,t);a.setSort("_id"),a.setSkip(i.skip);const s=yield a.run();return{users:s.rows,total:s.totalRows}})),this.find=e=>E(this,void 0,void 0,(function*(){return yield t.users.getById(e)})),this.create=e=>E(this,void 0,void 0,(function*(){return yield this.saveUser(e,{requirePassword:!1})})),this.update=e=>E(this,void 0,void 0,(function*(){return yield this.saveUser(e,{requirePassword:!1})})),this.remove=e=>E(this,void 0,void 0,(function*(){return yield this.removeUser(e)})),this.saveUser=i.functions.saveUser,this.removeUser=i.functions.removeUser}}const go=e=>{yo=new fo(e)};let yo;const mo=e=>yo.get(e),ho=e=>yo.find(e),bo=e=>yo.create(e),Ao=e=>yo.update(e),So=e=>yo.remove(e);var Oo=Object.freeze({__proto__:null,init:go,get:mo,find:ho,create:bo,update:Ao,remove:So});const Io=e=>E(void 0,void 0,void 0,(function*(){e.scimUserServiceConfig&&go(e.scimUserServiceConfig),e.backups&&(yield co.init(e.backups))}));var _o=Object.freeze({__proto__:null,branding:wt,licensing:mt,quotas:Yt,users:Xt,automations:mi,features:Et,groups:Pi,plugins:Ui,environmentVariables:Ci,auditLogs:eo,backups:co,utils:vo,init:Io,scimUsers:Oo});const Eo=e=>(t,i)=>E(void 0,void 0,void 0,(function*(){yield bt(e),yield i()}));var To=Object.freeze({__proto__:null,requireFeature:Eo});const wo=(e,i)=>E(void 0,void 0,void 0,(function*(){yield t.context.doInScimContext(i)})),Do=(e,t)=>E(void 0,void 0,void 0,(function*(){yield _t(),yield t()}));var Po=Object.freeze({__proto__:null,licensing:(i={checkDayPasses:!0,checkUsersLimit:!0,refreshVersion:!0})=>(o,n)=>E(void 0,void 0,void 0,(function*(){if((i.licensingCheck?i.licensingCheck:()=>!!o.user)(o)){if(t.env.SELF_HOSTED&&t.env.DEFAULT_LICENSE)return o.user.license=Re,n();o.user.license=yield ft(o,{populateLicense:i.populateLicense,populateFreeLicense:i.populateFreeLicense,refreshVersion:i.refreshVersion}),i.checkDayPasses&&(yield xt(o)),i.checkUsersLimit&&(t.utils.isServingApp(o)||t.utils.isServingBuilder(o)||t.utils.isServingBuilderPreview(o)||t.utils.isPublicApiRequest(o))&&(yield $t(e.StaticQuotaName.USERS,e.QuotaUsageType.STATIC))}return n()})),feature:To,doInScimContext:wo,requireSCIM:Do});const Uo=new S.default;Uo.post("/api/global/groups",t.auth.adminOnly,Eo(e.Feature.USER_GROUPS),t.auth.joiValidator.body(O.default.object({_id:O.default.string().optional(),_rev:O.default.string().optional(),color:O.default.string().required(),icon:O.default.string().required(),name:O.default.string().trim().required().max(50),role:O.default.string().optional(),users:O.default.array().optional(),apps:O.default.array().optional(),roles:O.default.object().optional(),createdAt:O.default.string().optional(),updatedAt:O.default.string().optional()}).required()),(e=>E(void 0,void 0,void 0,(function*(){const t=e.request.body;if(t.name=t.name.trim(),delete t.roles,t._id){const e=yield Si(t._id);t.roles=e.roles}const i=yield _i(t);e.body={_id:i.id,_rev:i.rev}})))).get("/api/global/groups",Eo(e.Feature.USER_GROUPS),(e=>E(void 0,void 0,void 0,(function*(){e.body={data:yield Ai()}})))).delete("/api/global/groups/:id/:rev",Eo(e.Feature.USER_GROUPS),t.auth.adminOnly,(e=>E(void 0,void 0,void 0,(function*(){const{id:t,rev:i}=e.params;try{yield Ei(t,i),e.body={message:"Group deleted successfully"}}catch(t){e.throw(t.status,t)}})))).get("/api/global/groups/:id",Eo(e.Feature.USER_GROUPS),t.auth.adminOnly,(e=>E(void 0,void 0,void 0,(function*(){try{e.body=yield Si(e.params.id)}catch(t){e.throw(t.status,t)}})))).get("/api/global/groups/:id/users",Eo(e.Feature.USER_GROUPS),t.auth.adminOnly,(e=>E(void 0,void 0,void 0,(function*(){var t,i;const{pageSize:o=10,bookmark:n,emailSearch:r}=e.request.query,a=e.params.id,s={limit:o+1},d=yield ne(a,Object.assign(Object.assign({},s),{emailSearch:r,bookmark:n})),u=r?null===(t=d[o])||void 0===t?void 0:t.email:null===(i=d[o])||void 0===i?void 0:i._id,l=!!u;e.body={users:d.slice(0,o),bookmark:u,hasNextPage:l}})))).post("/api/global/groups/:id/users",t.auth.adminOnly,Eo(e.Feature.USER_GROUPS),(e=>E(void 0,void 0,void 0,(function*(){const t=e.params.id,i=e.request.body.add,o=e.request.body.remove;let n,r;(i&&!Array.isArray(i)||o&&!Array.isArray(o))&&e.throw(400,"Must supply a list of users to add or to remove"),i&&(n=yield Ti(t,i)),o&&(r=yield wi(t,o)),e.body={added:n,removed:r}})))).post("/api/global/groups/:id/apps",t.auth.builderOrAdmin,Eo(e.Feature.USER_GROUPS),(e=>E(void 0,void 0,void 0,(function*(){const t=e.params.id,i=e.request.body.add,o=e.request.body.remove;(i&&!Array.isArray(i)||o&&!Array.isArray(o))&&e.throw(400,"Must supply a list of objects, with appId and roleId to add or remove"),e.body=yield Di(t,{appsToAdd:i,appsToRemove:o})}))));const Ro=new S.default;function ko(){return t.auth.joiValidator.body(O.default.object({name:O.default.string().optional(),production:O.default.string().required(),development:O.default.string().required()}))}function No(){return t.auth.joiValidator.body(O.default.object({userIds:O.default.array().items(O.default.string()).optional(),appIds:O.default.array().items(O.default.string()).optional(),events:O.default.array().items(O.default.string().valid(...Object.values(e.Event))).optional(),startDate:O.default.string().optional().allow(""),endDate:O.default.string().optional().allow(""),fullSearch:O.default.string().optional().allow(""),bookmark:O.default.string().optional().allow("")}))}Ro.get("/api/env/variables/status",t.auth.builderOrAdmin,(function(e){return E(this,void 0,void 0,(function*(){e.body={encryptionKeyAvailable:Ri()}}))})).get("/api/env/variables",t.auth.builderOrAdmin,(function(e){return E(this,void 0,void 0,(function*(){e.body={variables:yield ki()}}))})).post("/api/env/variables",t.auth.builderOrAdmin,ko(),(function(i){return E(this,void 0,void 0,(function*(){const{name:o,production:n,development:r}=i.request.body;yield Bi(o,{production:n,development:r});const a=[e.AppEnvironment.PRODUCTION];n!==r&&a.push(e.AppEnvironment.DEVELOPMENT),yield t.events.environmentVariable.created(o,a),i.status=200}))})).patch("/api/env/variables/:varName",t.auth.builderOrAdmin,ko(),(function(e){return E(this,void 0,void 0,(function*(){const{production:t,development:i}=e.request.body,o=e.params.varName;yield Bi(o,{production:t,development:i}),e.status=200}))})).delete("/api/env/variables/:varName",t.auth.builderOrAdmin,(function(e){return E(this,void 0,void 0,(function*(){const i=e.params.varName;yield ji(i),yield t.events.environmentVariable.deleted(i),e.status=200}))}));const Bo=new S.default;function jo(e,t){return E(this,void 0,void 0,(function*(){(yield po(t))||e.throw(400,`Provided app ID: ${t} - is invalid.`)}))}Bo.post("/api/global/auditlogs/search",t.auth.adminOnly,No(),(function(e){return E(this,void 0,void 0,(function*(){const i=e.request.body,o=yield Ji(i);yield t.events.auditLog.filtered(i),e.body=o}))})).get("/api/global/auditlogs/download",t.auth.adminOnly,t.middleware.querystringToBody,No(),(function(e){return E(this,void 0,void 0,(function*(){const i=e.request.body,{stream:o}=Xi(i);yield t.events.auditLog.downloaded(i),e.attachment(`audit-logs-${Date.now()}.log`),e.body=o}))})).get("/api/global/auditlogs/definitions",t.auth.adminOnly,(function(e){return E(this,void 0,void 0,(function*(){e.body={events:Zi()}}))}));const Lo=new S.default;Lo.post("/api/apps/:appId/backups",t.auth.builderOrAdmin,(function(t){var i;return E(this,void 0,void 0,(function*(){const o=t.params.appId;yield jo(t,o);const n=t.request.body,r=null===(i=t.user)||void 0===i?void 0:i._id,a=yield co.triggerAppBackup(o,e.AppBackupTrigger.MANUAL,{name:n.name,createdBy:r});a||t.throw(500,"Unable to start backup."),t.body={backupId:a,message:"Backup triggered - process starting."}}))})).post("/api/apps/:appId/backups/search",t.auth.builderOrAdmin,t.auth.joiValidator.body(O.default.object({trigger:O.default.string().valid(...Object.values(e.AppBackupTrigger)),type:O.default.string().valid(...Object.values(e.AppBackupType)),startDate:O.default.date(),endDate:O.default.date(),page:O.default.string()})),(function(t){return E(this,void 0,void 0,(function*(){const i=t.params.appId;yield jo(t,i);const o=t.request.body;(null==o?void 0:o.trigger)&&(o.trigger=o.trigger.toLowerCase(),Object.values(e.AppBackupTrigger).includes(o.trigger)||t.throw(400,"Provided trigger is not a valid option.")),t.body=yield co.fetchAppBackups(i,Object.assign({paginate:!0},o))}))})).get("/api/apps/:appId/backups/:backupId/file",t.auth.builderOrAdmin,(function(e){return E(this,void 0,void 0,(function*(){const t=e.params.appId;yield jo(e,t);const i=e.params.backupId,{metadata:o,path:n}=yield co.downloadAppBackup(i);e.attachment(`backup-${o.timestamp}.tar.gz`),e.body=h.default.createReadStream(n)}))})).patch("/api/apps/:appId/backups/:backupId",t.auth.builderOrAdmin,(function(e){return E(this,void 0,void 0,(function*(){const t=e.params.appId;yield jo(e,t);const i=e.params.backupId,o=e.request.body;e.body=yield co.updateAppBackup(i,o.name)}))})).delete("/api/apps/:appId/backups/:backupId",t.auth.builderOrAdmin,(function(e){return E(this,void 0,void 0,(function*(){const t=e.params.appId;yield jo(e,t);const i=e.params.backupId;yield co.deleteAppBackup(i),e.body={message:"Backup deleted successfully."}}))})).post("/api/apps/:appId/backups/:backupId/import",t.auth.builderOrAdmin,(function(e){var i;return E(this,void 0,void 0,(function*(){const o=e.params.appId;yield jo(e,o);const n=e.params.backupId,r=e.request.body.name,a=yield co.triggerAppRestore(o,n,r,null===(i=e.user)||void 0===i?void 0:i._id);a||e.throw(500,"Unable to start restore."),yield t.events.backup.appBackupRestored(a.metadata),e.body={restoredId:null==a?void 0:a.restoreId,message:"Restore triggered - process starting."}}))}));const Co=new S.default;function $o(){return t.auth.joiValidator.body(O.default.object({type:O.default.string().valid(...Object.keys(e.ScheduleType)).required(),name:O.default.string().required(),startDate:O.default.date().required(),repeat:O.default.string().valid(...Object.keys(e.ScheduleRepeatPeriod)).required(),metadata:O.default.alternatives().conditional(".type",{switch:[{is:e.ScheduleType.APP_BACKUP,then:{apps:O.default.array().items(O.default.string()).required()}}]})}))}function Go(e,t){const i=e.request.query[t];if(void 0!==i)return+i}Co.get("/api/schedules/:type",t.auth.builderOrAdmin,Eo(e.Feature.APP_BACKUPS),(function(e){e.params.type,e.status=501})).put("/api/schedules/:scheduleId",t.auth.builderOrAdmin,Eo(e.Feature.APP_BACKUPS),$o(),(function(e){e.params.scheduleId,e.body,e.status=501})).delete("/api/schedules/:scheduleId",t.auth.builderOrAdmin,Eo(e.Feature.APP_BACKUPS),(function(e){e.params.scheduleId,e.status=501})).post("/api/schedules",t.auth.builderOrAdmin,Eo(e.Feature.APP_BACKUPS),$o(),(function(e){e.body,e.status=501}));const Qo=e=>E(void 0,void 0,void 0,(function*(){const{id:t}=e.params;"string"!=typeof t&&e.throw(404),yield So(t),e.status=204}));function xo(e,t){for(const i of t.split(","))delete e[i]}const qo=new S.default({prefix:"/api/global/scim/v2"});qo.use(Do),qo.use(wo),qo.get("/users",(e=>E(void 0,void 0,void 0,(function*(){var t;const i=null!==(t=Go(e,"pageSize"))&&void 0!==t?t:20,o=Go(e,"startIndex");let n;e.request.query.filter&&(n=Ko(e.request.query.filter));const r=yield mo({pageSize:i,skip:o,filters:n});e.body={schemas:["urn:ietf:params:scim:api:messages:2.0:ListResponse"],totalResults:r.total,Resources:r.users.map(Fo),startIndex:(o||0)+1,itemsPerPage:i}})))),qo.get("/users/:id",(e=>E(void 0,void 0,void 0,(function*(){const{id:t}=e.params;"string"!=typeof t&&e.throw(404);const i=yield ho(t);e.body=Fo(i)})))),qo.post("/users",(e=>E(void 0,void 0,void 0,(function*(){const i=zo(e.request.body);try{const t=yield bo(i);e.body=Fo(t)}catch(i){throw i instanceof t.EmailUnavailableError&&e.throw(409,"Email already in use"),i}})))),qo.patch("/users/:id",(e=>E(void 0,void 0,void 0,(function*(){const t=yield ho(e.params.id);t||e.throw(404);const i=Fo(t),o=e.request.body;try{c.patchBodyValidation(o)}catch(e){}if(function(e){var t,i;const o=e.Operations.find((e=>("Replace"===e.op||"replace"===e.op)&&"active"===e.path));return!!o&&(!1===o.value||"false"===(null===(i=null===(t=o.value)||void 0===t?void 0:t.toLowerCase)||void 0===i?void 0:i.call(t)))}(o))return Qo(e);let n;try{n=c.scimPatch(i,o.Operations)}catch(e){}n||e.throw(500);const r=zo(n);yield Ao(r),e.body=Fo(r)})))),qo.delete("/users/:id",Qo),qo.get("/groups",(e=>E(void 0,void 0,void 0,(function*(){let t=(yield Ai()).map(Vo);const{filter:i,excludedAttributes:o}=e.request.query;if(i){const e=l.filter(l.parse(i));t=t.filter(e)}o&&t.forEach((e=>{xo(e,o)})),e.body={schemas:["urn:ietf:params:scim:api:messages:2.0:ListResponse"],totalResults:t.length,Resources:t,startIndex:1,itemsPerPage:t.length}})))),qo.post("/groups",(e=>E(void 0,void 0,void 0,(function*(){const t=Ho(e.request.body),i=yield _i(t),o=yield Si(i.id);e.body=Vo(o)})))),qo.get("/groups/:id",(e=>E(void 0,void 0,void 0,(function*(){const{id:t}=e.params;"string"!=typeof t&&e.throw(404);const i=yield Si(t),o=Vo(i),{excludedAttributes:n}=e.request.query;n&&xo(o,n),e.body=o})))),qo.delete("/groups/:id",(e=>E(void 0,void 0,void 0,(function*(){const{id:t}=e.params;"string"!=typeof t&&e.throw(404);const{_rev:i}=yield Si(t);yield Ei(t,i),e.status=204})))),qo.patch("/groups/:id",(e=>E(void 0,void 0,void 0,(function*(){const{id:t}=e.params,i=yield Si(t);i||e.throw(404);const o=Vo(i),n=e.request.body;try{c.patchBodyValidation(n)}catch(t){e.throw(400)}const{true:r,false:a}=I.default.groupBy(n.Operations,(e=>"members"===e.path));if(null==a?void 0:a.length){const t=c.scimPatch(o,a);t||e.throw(500);const n=Object.assign(Object.assign({},Ho(t)),{_rev:i._rev});yield _i(n)}if(null==r?void 0:r.length){const e=[],i=[];for(const{op:t,value:o}of r)switch(t){case"add":case"Add":for(const t of o)e.push(yield ho(t.value));break;case"remove":case"Remove":for(const e of o)i.push(yield ho(e.value));break;case"replace":case"Replace":throw new Error("Replacing members is not allowed");default:v.utils.unreachable(t)}e.length&&(yield Ti(t,e.map((e=>e._id)))),i.length&&(yield wi(t,i.map((e=>e._id))))}e.body=Vo(yield Si(t))}))));var Mo=Object.freeze({__proto__:null,groups:Uo,environmentVariables:Ro,auditLogs:Bo,appBackups:Lo,schedules:Co,scim:qo});const Fo=t=>{const i=_(t.scimInfo||{},["isSync","roles"]),o=Object.assign(Object.assign({},i),{schemas:["urn:ietf:params:scim:schemas:core:2.0:User"],id:t._id,meta:{resourceType:"User",created:new Date(t.createdAt),lastModified:new Date(t.updatedAt)},active:t.status===e.UserStatus.ACTIVE});return(t.firstName||t.lastName)&&(o.name={formatted:[t.firstName,t.lastName].filter((e=>e)).join(" "),familyName:t.lastName,givenName:t.firstName}),o};const zo=i=>{var o,n;const r=(null==(a=i)?void 0:a.id)?i:void 0;var a;const s=function(e){var i,o;return t.utils.validEmail(e.userName)?e.userName:e.emails?(null===(i=e.emails.find((e=>e.primary)))||void 0===i?void 0:i.value)||(null===(o=e.emails[0])||void 0===o?void 0:o.value):void 0}(i);if(!s)throw new Error("Email is required");let d;switch(i.active){case"True":case"true":case!0:d=!0;break;case"False":case"false":case!1:d=!1;break;default:!function(e,t=`No such case in exhaustive switch: ${e}`){throw new Error(t)}(i.active)}return{tenantId:"",_id:null==r?void 0:r.id,userId:null==r?void 0:r.id,email:s,firstName:null===(o=i.name)||void 0===o?void 0:o.givenName,lastName:null===(n=i.name)||void 0===n?void 0:n.familyName,scimInfo:Object.assign(Object.assign({},i),{isSync:!0}),roles:{},status:d?e.UserStatus.ACTIVE:e.UserStatus.INACTIVE,createdAt:null==r?void 0:r.meta.created.getTime(),updatedAt:null==r?void 0:r.meta.lastModified.toISOString()}},Ko=e=>{const t={equal:{}};return function e(i){switch(i.op){case"eq":const o=i.attrPath;let n;if("emails.value"===o)n="email";else n=`scimInfo.${o}`;t.equal[n]=i.compValue;break;case"and":for(const t of i.filters)e(t);break;default:console.warn("Filter not handled",{filter:i})}}(l.parse(e)),t};var Yo=Object.freeze({__proto__:null,toScimUserResponse:Fo,fromScimUser:zo,userFilters:Ko});const Vo=e=>{var t;return{schemas:["urn:ietf:params:scim:schemas:core:2.0:Group"],id:e._id,externalId:e.scimInfo.externalId,meta:{resourceType:"Group",created:new Date(e.createdAt),lastModified:new Date(e.updatedAt)},displayName:e.name,members:null===(t=e.users)||void 0===t?void 0:t.map((e=>({value:e._id})))}},Ho=e=>{const t=(e=>!!(null==e?void 0:e.id))(e)?e:void 0;return{_id:null==t?void 0:t.id,name:e.displayName,scimInfo:{externalId:e.externalId,isSync:!0},icon:"UserGroup",color:"var(--spectrum-global-color-blue-600)",createdAt:null==t?void 0:t.meta.created.getTime(),updatedAt:null==t?void 0:t.meta.lastModified.toISOString()}};var Wo=Object.freeze({__proto__:null,toScimGroupResponse:Vo,fromScimGroup:Ho}),Jo=Object.freeze({__proto__:null,user:Yo,group:Wo});exports.api=Mo,exports.auditLogs=eo,exports.automations=mi,exports.backups=co,exports.branding=wt,exports.constants=$e,exports.environmentVariables=Ci,exports.features=Et,exports.groups=Pi,exports.init=Io,exports.licensing=mt,exports.mappers=Jo,exports.middleware=Po,exports.plugins=Ui,exports.quotas=Yt,exports.scimUsers=Oo,exports.sdk=_o,exports.users=Xt,exports.utils=vo;
|
package/dist/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"dist"
|
|
5
5
|
],
|
|
6
6
|
"license": "UNLICENSED",
|
|
7
|
-
"version": "2.6.19-alpha.
|
|
7
|
+
"version": "2.6.19-alpha.16",
|
|
8
8
|
"description": "Budibase Pro (Backend)",
|
|
9
9
|
"main": "dist/index.js",
|
|
10
10
|
"types": "dist/src/index.d.ts",
|
|
@@ -26,10 +26,10 @@
|
|
|
26
26
|
],
|
|
27
27
|
"author": "Budibase",
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@budibase/backend-core": "2.6.19-alpha.
|
|
30
|
-
"@budibase/shared-core": "2.6.19-alpha.
|
|
31
|
-
"@budibase/string-templates": "2.6.19-alpha.
|
|
32
|
-
"@budibase/types": "2.6.19-alpha.
|
|
29
|
+
"@budibase/backend-core": "2.6.19-alpha.16",
|
|
30
|
+
"@budibase/shared-core": "2.6.19-alpha.16",
|
|
31
|
+
"@budibase/string-templates": "2.6.19-alpha.16",
|
|
32
|
+
"@budibase/types": "2.6.19-alpha.16",
|
|
33
33
|
"@koa/router": "8.0.8",
|
|
34
34
|
"bull": "4.10.1",
|
|
35
35
|
"joi": "17.6.0",
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { UserCtx } from "@budibase/types";
|
|
2
|
+
export declare function manualBackup(ctx: UserCtx): Promise<void>;
|
|
3
|
+
export declare function importBackup(ctx: UserCtx): Promise<void>;
|
|
4
|
+
export declare function deleteBackup(ctx: UserCtx): Promise<void>;
|
|
5
|
+
export declare function fetchBackups(ctx: UserCtx): Promise<void>;
|
|
6
|
+
export declare function updateBackup(ctx: UserCtx): Promise<void>;
|
|
7
|
+
export declare function downloadBackup(ctx: UserCtx): Promise<void>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { SearchAuditLogsRequest, SearchAuditLogsResponse, DownloadAuditLogsRequest, DefinitionsAuditLogsResponse, UserCtx } from "@budibase/types";
|
|
3
|
+
import { Readable } from "stream";
|
|
4
|
+
export declare function search(ctx: UserCtx<SearchAuditLogsRequest, SearchAuditLogsResponse>): Promise<void>;
|
|
5
|
+
export declare function download(ctx: UserCtx<DownloadAuditLogsRequest, Readable>): Promise<void>;
|
|
6
|
+
export declare function definitions(ctx: UserCtx<void, DefinitionsAuditLogsResponse>): Promise<void>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { CreateEnvironmentVariableRequest, GetEnvironmentVariablesResponse, StatusEnvironmentVariableResponse, UpdateEnvironmentVariableRequest, UserCtx } from "@budibase/types";
|
|
2
|
+
export declare function status(ctx: UserCtx<void, StatusEnvironmentVariableResponse>): Promise<void>;
|
|
3
|
+
export declare function fetch(ctx: UserCtx<void, GetEnvironmentVariablesResponse>): Promise<void>;
|
|
4
|
+
export declare function create(ctx: UserCtx<CreateEnvironmentVariableRequest, void>): Promise<void>;
|
|
5
|
+
export declare function update(ctx: UserCtx<UpdateEnvironmentVariableRequest, void>): Promise<void>;
|
|
6
|
+
export declare function destroy(ctx: UserCtx<void, void>): Promise<void>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const save: (ctx: UserCtx) => Promise<void>;
|
|
2
|
+
export declare const updateGroupUsers: (ctx: UserCtx) => Promise<void>;
|
|
3
|
+
export declare const updateGroupApps: (ctx: UserCtx) => Promise<void>;
|
|
4
|
+
export declare const fetch: (ctx: Ctx<SearchGroupRequest, SearchGroupResponse>) => Promise<void>;
|
|
5
|
+
export declare const destroy: (ctx: UserCtx) => Promise<void>;
|
|
6
|
+
/**
|
|
7
|
+
* Gets a group by ID from the global database.
|
|
8
|
+
*/
|
|
9
|
+
export declare const find: (ctx: UserCtx) => Promise<void>;
|
|
10
|
+
export declare const searchUsers: (ctx: Ctx<{}, SearchUserGroupResponse>) => Promise<void>;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const get: (ctx: Ctx<void, ScimGroupListResponse>) => Promise<void>;
|
|
2
|
+
export declare const create: (ctx: Ctx<ScimCreateGroupRequest, ScimGroupResponse>) => Promise<void>;
|
|
3
|
+
export declare const find: (ctx: Ctx<void, ScimGroupResponse>) => Promise<void>;
|
|
4
|
+
export declare const remove: (ctx: Ctx) => Promise<void>;
|
|
5
|
+
export declare const update: (ctx: Ctx<ScimUpdateRequest, ScimGroupResponse>) => Promise<void>;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const get: (ctx: Ctx<void, ScimUserListResponse>) => Promise<void>;
|
|
2
|
+
export declare const find: (ctx: Ctx<void, ScimUserResponse>) => Promise<void>;
|
|
3
|
+
export declare const create: (ctx: Ctx<ScimCreateUserRequest, ScimUserResponse>) => Promise<void>;
|
|
4
|
+
export declare const update: (ctx: Ctx<ScimUpdateRequest, ScimUserResponse>) => Promise<void>;
|
|
5
|
+
export declare const remove: (ctx: Ctx) => Promise<void>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { BBContext } from "@budibase/types";
|
|
2
|
+
/**
|
|
3
|
+
* This file is a work in progress - to be filled out
|
|
4
|
+
* in a future update.
|
|
5
|
+
*/
|
|
6
|
+
export declare function createSchedule(ctx: BBContext): void;
|
|
7
|
+
export declare function fetchSchedules(ctx: BBContext): void;
|
|
8
|
+
export declare function updateSchedule(ctx: BBContext): void;
|
|
9
|
+
export declare function deleteSchedule(ctx: BBContext): void;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { default as groups } from "./routes/global/groups";
|
|
2
|
+
export { default as environmentVariables } from "./routes/global/environmentVariables";
|
|
3
|
+
export { default as auditLogs } from "./routes/global/auditLogs";
|
|
4
|
+
export { default as appBackups } from "./routes/apps/backups";
|
|
5
|
+
export { default as schedules } from "./routes/schedules";
|
|
6
|
+
export { default as scim } from "./routes/global/scim";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { License } from "@budibase/types";
|
|
2
|
+
export declare const UNLIMITED = -1;
|
|
3
|
+
/**
|
|
4
|
+
* The license used when no license is present.
|
|
5
|
+
*/
|
|
6
|
+
export declare const CLOUD_FREE_LICENSE: License;
|
|
7
|
+
/**
|
|
8
|
+
* The license used when no license is present.
|
|
9
|
+
*/
|
|
10
|
+
export declare const SELF_FREE_LICENSE: License;
|
|
11
|
+
/**
|
|
12
|
+
* Unlimited license to support unit tests.
|
|
13
|
+
*/
|
|
14
|
+
export declare const UNLIMITED_LICENSE: License;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const GENERIC_PAGE_SIZE = 9;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export declare const UNLIMITED = -1;
|
|
2
|
+
export declare const rows: (value: number) => {
|
|
3
|
+
[x: number]: {
|
|
4
|
+
name: string;
|
|
5
|
+
value: number;
|
|
6
|
+
triggers: number[];
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export declare const apps: (value: number) => {
|
|
10
|
+
[x: number]: {
|
|
11
|
+
name: string;
|
|
12
|
+
value: number;
|
|
13
|
+
triggers: number[];
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
export declare const users: (value: number) => {
|
|
17
|
+
[x: number]: {
|
|
18
|
+
name: string;
|
|
19
|
+
value: number;
|
|
20
|
+
triggers: number[];
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
export declare const userGroups: (value: number) => {
|
|
24
|
+
[x: number]: {
|
|
25
|
+
name: string;
|
|
26
|
+
value: number;
|
|
27
|
+
triggers: number[];
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
export declare const plugins: (value: number) => {
|
|
31
|
+
[x: number]: {
|
|
32
|
+
name: string;
|
|
33
|
+
value: number;
|
|
34
|
+
triggers: number[];
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
export declare const queries: (value: number) => {
|
|
38
|
+
[x: number]: {
|
|
39
|
+
name: string;
|
|
40
|
+
value: number;
|
|
41
|
+
triggers: never[];
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
export declare const automations: (value: number) => {
|
|
45
|
+
[x: number]: {
|
|
46
|
+
name: string;
|
|
47
|
+
value: number;
|
|
48
|
+
triggers: number[];
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
export declare const dayPasses: (value: number) => {
|
|
52
|
+
[x: number]: {
|
|
53
|
+
name: string;
|
|
54
|
+
value: number;
|
|
55
|
+
triggers: number[];
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
export declare const automationLogRetentionDays: (value: number) => {
|
|
59
|
+
[x: number]: {
|
|
60
|
+
name: string;
|
|
61
|
+
value: number;
|
|
62
|
+
triggers: never[];
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
export declare const appBackupRetentionDays: (value: number) => {
|
|
66
|
+
[x: number]: {
|
|
67
|
+
name: string;
|
|
68
|
+
value: number;
|
|
69
|
+
triggers: never[];
|
|
70
|
+
};
|
|
71
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { AuditLogDoc, SearchFilters, AuditLogSearchParams } from "@budibase/types";
|
|
3
|
+
import { Readable } from "stream";
|
|
4
|
+
export declare function save(doc: AuditLogDoc): Promise<any>;
|
|
5
|
+
export declare function search(search: SearchFilters, bookmark?: string): Promise<any>;
|
|
6
|
+
export declare function dump(params: AuditLogSearchParams): {
|
|
7
|
+
promise: Promise<void>;
|
|
8
|
+
stream: Readable;
|
|
9
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Automation, AutomationLogPage, AutomationResults } from "@budibase/types";
|
|
2
|
+
export declare const oldestLogDate: () => Promise<string>;
|
|
3
|
+
export declare function getStatus(results: AutomationResults): any;
|
|
4
|
+
export declare function generateAutomationLogID(isoDate: string, status: string, automationId: string): string;
|
|
5
|
+
export declare function getAllLogs(startDate: string, endDate: string, opts?: {
|
|
6
|
+
docs: boolean;
|
|
7
|
+
status?: string;
|
|
8
|
+
paginate?: boolean;
|
|
9
|
+
page?: string;
|
|
10
|
+
limit?: number;
|
|
11
|
+
}): Promise<AutomationLogPage>;
|
|
12
|
+
export declare function getLogsByView(startDate: string, endDate: string, viewParams?: {
|
|
13
|
+
automationId?: string;
|
|
14
|
+
status?: string;
|
|
15
|
+
page?: string;
|
|
16
|
+
}): Promise<AutomationLogPage>;
|
|
17
|
+
export declare function writeLog(automation: Automation, results: AutomationResults): Promise<string>;
|
|
18
|
+
export declare function updateAppMetadataWithErrors(logIds: string[], { clearing }?: {
|
|
19
|
+
clearing: boolean;
|
|
20
|
+
}): Promise<void>;
|
|
21
|
+
export declare function getExpiredLogs(): Promise<AutomationLogPage>;
|
|
22
|
+
export declare function clearOldHistory(): Promise<void>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { AppBackupFetchOpts, AppBackupMetadata } from "@budibase/types";
|
|
2
|
+
export declare function oldestBackupDate(): Promise<string>;
|
|
3
|
+
export declare function generateAppBackupID(appId: string, timestamp: string): string;
|
|
4
|
+
export declare function fetchAppBackups(appId: string, opts?: AppBackupFetchOpts): Promise<{
|
|
5
|
+
data: AppBackup[];
|
|
6
|
+
hasNextPage: boolean;
|
|
7
|
+
nextPage?: string | undefined;
|
|
8
|
+
}>;
|
|
9
|
+
export declare function storeAppBackupMetadata(metadata: AppBackupMetadata, opts?: {
|
|
10
|
+
filename?: string;
|
|
11
|
+
docId?: string;
|
|
12
|
+
docRev?: string;
|
|
13
|
+
}): Promise<PutResponse>;
|
|
14
|
+
export declare function updateAppBackupMetadata(backupId: string, name: string): Promise<PutResponse>;
|
|
15
|
+
export declare function deleteAppBackupMetadata(backupId: string): Promise<void>;
|
|
16
|
+
export declare function getAppBackupMetadata(backupId: string): Promise<AppBackup>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { EnvironmentVariablesDocDecrypted } from "@budibase/types";
|
|
2
|
+
export declare function getEnvVarID(): any;
|
|
3
|
+
export declare function getCacheEnvVarID(rev?: string): string;
|
|
4
|
+
export declare function get(): Promise<EnvironmentVariablesDocDecrypted>;
|
|
5
|
+
export declare function update(doc: EnvironmentVariablesDocDecrypted): Promise<{
|
|
6
|
+
id: string;
|
|
7
|
+
rev: string;
|
|
8
|
+
}>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { DatabaseQueryOpts, UserGroup } from "@budibase/types";
|
|
2
|
+
declare type UserGroupsViewParams = DatabaseQueryOpts & {
|
|
3
|
+
emailSearch?: string;
|
|
4
|
+
bookmark?: string;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Gets parameters for retrieving groups.
|
|
8
|
+
*/
|
|
9
|
+
export declare function getUserGroupsParams(groupId: string | null | undefined, otherProps?: {}): {
|
|
10
|
+
startkey: string;
|
|
11
|
+
endkey: string;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Gets parameters for retrieving groups.
|
|
15
|
+
*/
|
|
16
|
+
export declare function getGroupUsersParams(groupId: string, otherProps?: UserGroupsViewParams): DatabaseQueryOpts;
|
|
17
|
+
/**
|
|
18
|
+
* Generates a new user group ID
|
|
19
|
+
* @returns {string} The new user group ID which info can be stored under.
|
|
20
|
+
*/
|
|
21
|
+
export declare function generateUserGroupID(): string;
|
|
22
|
+
export declare function getGroupUsers(groupId: string, params?: UserGroupsViewParams): Promise<{
|
|
23
|
+
_id: any;
|
|
24
|
+
email: any;
|
|
25
|
+
}[]>;
|
|
26
|
+
export declare function fetch(): Promise<any[]>;
|
|
27
|
+
export declare function get(groupId: string): Promise<UserGroup>;
|
|
28
|
+
export declare function getBulk(groupIds: string[], opts?: {
|
|
29
|
+
enriched: boolean;
|
|
30
|
+
}): Promise<UserGroup[]>;
|
|
31
|
+
export declare function save(group: UserGroup): Promise<{
|
|
32
|
+
id: string;
|
|
33
|
+
rev: string;
|
|
34
|
+
}>;
|
|
35
|
+
export declare function bulkSave(groups: UserGroup[]): Promise<{
|
|
36
|
+
id: string;
|
|
37
|
+
rev?: string;
|
|
38
|
+
}[]>;
|
|
39
|
+
export declare function destroy(groupId: string, revision: string): Promise<{
|
|
40
|
+
id: string;
|
|
41
|
+
}>;
|
|
42
|
+
export declare function getByName(name: string): Promise<any>;
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { SelfHostLicenseInfo } from "../types";
|
|
2
|
+
export declare const create: (licenseKey: string) => Promise<SelfHostLicenseInfo>;
|
|
3
|
+
export declare const get: () => Promise<SelfHostLicenseInfo | undefined>;
|
|
4
|
+
export declare const destroy: () => Promise<{
|
|
5
|
+
id?: string;
|
|
6
|
+
rev?: string;
|
|
7
|
+
} | void>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { QuotaUsage, UsageValues } from "@budibase/types";
|
|
2
|
+
export declare const bustCache: () => Promise<void>;
|
|
3
|
+
export declare const getQuotaUsage: () => Promise<QuotaUsage>;
|
|
4
|
+
export declare const setUsage: (value: number, name: MeteredQuotaName, type: QuotaUsageType) => Promise<QuotaUsage>;
|
|
5
|
+
export declare const setUsagePerApp: (appValues: {
|
|
6
|
+
[key: string]: number;
|
|
7
|
+
}, name: MeteredQuotaName, type: QuotaUsageType) => Promise<QuotaUsage>;
|
|
8
|
+
export declare const setAppUsageValue: (quotaUsage: QuotaUsage, name: MeteredQuotaName, type: QuotaUsageType, opts: {
|
|
9
|
+
id?: string | undefined;
|
|
10
|
+
appId?: string | undefined;
|
|
11
|
+
} | undefined, values: UsageValues) => QuotaUsage;
|
|
12
|
+
export declare const setAllUsage: (name: MeteredQuotaName, type: QuotaUsageType, values: SetUsageValues, opts?: {
|
|
13
|
+
id?: string;
|
|
14
|
+
appId?: string;
|
|
15
|
+
}) => Promise<QuotaUsage>;
|
|
16
|
+
export declare const getCurrentUsageValues: (type: QuotaUsageType, name: MeteredQuotaName, id?: string) => Promise<UsageValues>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { BreakdownQuotaName } from "@budibase/types";
|
|
2
|
+
export declare const setQuotaReset: (usage: QuotaUsage) => void;
|
|
3
|
+
export declare const getCurrentMonthString: () => string;
|
|
4
|
+
export declare const generateBaseQuotaUsage: () => BaseQuotaUsage;
|
|
5
|
+
export declare const generateNewQuotaUsage: () => QuotaUsage;
|
|
6
|
+
export declare const generateNewMonthlyQuotas: () => MonthlyUsage;
|
|
7
|
+
export declare const setCurrentMonth: (usage: QuotaUsage) => void;
|
|
8
|
+
export declare const getBreakdownName: (name: MonthlyQuotaName, id?: string) => BreakdownQuotaName | undefined;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A separate view that allows us to perform queries by the automation ID and time series, while the
|
|
3
|
+
* main all_docs allows access to time series only
|
|
4
|
+
*/
|
|
5
|
+
export declare function createLogByAutomationView(): Promise<void>;
|
|
6
|
+
export declare function createAppBackupTriggerView(): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function createAuditLogSearchIndex(): Promise<void>;
|