@budibase/backend-core 2.13.39 → 2.13.41

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 CHANGED
@@ -1608,24 +1608,11 @@ var init_db2 = __esm({
1608
1608
  }
1609
1609
  });
1610
1610
 
1611
- // src/constants/misc.ts
1612
- var UserStatus, Cookie, Header, GlobalRole, Config, MIN_VALID_DATE, MAX_VALID_DATE, DEFAULT_TENANT_ID;
1613
- var init_misc = __esm({
1614
- "src/constants/misc.ts"() {
1611
+ // ../shared-core/src/constants/api.ts
1612
+ var Header;
1613
+ var init_api2 = __esm({
1614
+ "../shared-core/src/constants/api.ts"() {
1615
1615
  "use strict";
1616
- UserStatus = /* @__PURE__ */ ((UserStatus3) => {
1617
- UserStatus3["ACTIVE"] = "active";
1618
- UserStatus3["INACTIVE"] = "inactive";
1619
- return UserStatus3;
1620
- })(UserStatus || {});
1621
- Cookie = /* @__PURE__ */ ((Cookie2) => {
1622
- Cookie2["Auth"] = "budibase:auth";
1623
- Cookie2["Init"] = "budibase:init";
1624
- Cookie2["ACCOUNT_RETURN_URL"] = "budibase:account:returnurl";
1625
- Cookie2["DatasourceAuth"] = "budibase:datasourceauth";
1626
- Cookie2["OIDC_CONFIG"] = "budibase:oidc:config";
1627
- return Cookie2;
1628
- })(Cookie || {});
1629
1616
  Header = /* @__PURE__ */ ((Header2) => {
1630
1617
  Header2["API_KEY"] = "x-budibase-api-key";
1631
1618
  Header2["LICENSE_KEY"] = "x-budibase-license-key";
@@ -1643,1944 +1630,2361 @@ var init_misc = __esm({
1643
1630
  Header2["CSRF_TOKEN"] = "x-csrf-token";
1644
1631
  Header2["CORRELATION_ID"] = "x-budibase-correlation-id";
1645
1632
  Header2["AUTHORIZATION"] = "authorization";
1633
+ Header2["MIGRATING_APP"] = "x-budibase-migrating-app";
1646
1634
  return Header2;
1647
1635
  })(Header || {});
1648
- GlobalRole = /* @__PURE__ */ ((GlobalRole2) => {
1649
- GlobalRole2["OWNER"] = "owner";
1650
- GlobalRole2["ADMIN"] = "admin";
1651
- GlobalRole2["BUILDER"] = "builder";
1652
- GlobalRole2["WORKSPACE_MANAGER"] = "workspace_manager";
1653
- return GlobalRole2;
1654
- })(GlobalRole || {});
1655
- Config = /* @__PURE__ */ ((Config3) => {
1656
- Config3["SETTINGS"] = "settings";
1657
- Config3["ACCOUNT"] = "account";
1658
- Config3["SMTP"] = "smtp";
1659
- Config3["GOOGLE"] = "google";
1660
- Config3["OIDC"] = "oidc";
1661
- Config3["OIDC_LOGOS"] = "logos_oidc";
1662
- Config3["SCIM"] = "scim";
1663
- return Config3;
1664
- })(Config || {});
1665
- MIN_VALID_DATE = /* @__PURE__ */ new Date(-2147483647e3);
1666
- MAX_VALID_DATE = /* @__PURE__ */ new Date(2147483647e3);
1667
- DEFAULT_TENANT_ID = "default";
1668
1636
  }
1669
1637
  });
1670
1638
 
1671
- // src/constants/index.ts
1672
- var constants_exports = {};
1673
- __export(constants_exports, {
1674
- APP_DEV: () => APP_DEV,
1675
- APP_DEV_PREFIX: () => APP_DEV_PREFIX,
1676
- APP_PREFIX: () => APP_PREFIX,
1677
- AutomationViewMode: () => AutomationViewMode,
1678
- BUDIBASE_DATASOURCE_TYPE: () => BUDIBASE_DATASOURCE_TYPE,
1679
- Config: () => Config,
1680
- Cookie: () => Cookie,
1681
- DEFAULT_TENANT_ID: () => DEFAULT_TENANT_ID,
1682
- DeprecatedViews: () => DeprecatedViews,
1683
- DocumentType: () => DocumentType,
1684
- GlobalRole: () => GlobalRole,
1685
- Header: () => Header,
1686
- InternalTable: () => InternalTable,
1687
- MAX_VALID_DATE: () => MAX_VALID_DATE,
1688
- MIN_VALID_DATE: () => MIN_VALID_DATE,
1689
- SEPARATOR: () => SEPARATOR,
1690
- StaticDatabases: () => StaticDatabases,
1691
- UNICODE_MAX: () => UNICODE_MAX,
1692
- UserStatus: () => UserStatus,
1693
- ViewName: () => ViewName
1694
- });
1639
+ // ../shared-core/src/constants/index.ts
1640
+ var OperatorOptions;
1695
1641
  var init_constants3 = __esm({
1696
- "src/constants/index.ts"() {
1697
- "use strict";
1698
- init_db2();
1699
- init_misc();
1700
- }
1701
- });
1702
-
1703
- // src/context/identity.ts
1704
- var identity_exports = {};
1705
- __export(identity_exports, {
1706
- doInAccountContext: () => doInAccountContext,
1707
- doInIdentityContext: () => doInIdentityContext2,
1708
- doInUserContext: () => doInUserContext,
1709
- getAccountUserId: () => getAccountUserId,
1710
- getIdentity: () => getIdentity2
1711
- });
1712
- function getIdentity2() {
1713
- return getIdentity();
1714
- }
1715
- function doInIdentityContext2(identity, task) {
1716
- return doInIdentityContext(identity, task);
1717
- }
1718
- function doInUserContext(user, ctx, task) {
1719
- const userContext = {
1720
- ...user,
1721
- _id: user._id,
1722
- type: "user" /* USER */,
1723
- hostInfo: {
1724
- ipAddress: ctx.request.ip,
1725
- // filled in by koa-useragent package
1726
- userAgent: ctx.userAgent._agent.source
1727
- }
1728
- };
1729
- return doInIdentityContext2(userContext, task);
1730
- }
1731
- function doInAccountContext(account, task) {
1732
- const _id = getAccountUserId(account);
1733
- const tenantId = account.tenantId;
1734
- const accountContext = {
1735
- _id,
1736
- type: "user" /* USER */,
1737
- tenantId,
1738
- account
1739
- };
1740
- return doInIdentityContext2(accountContext, task);
1741
- }
1742
- function getAccountUserId(account) {
1743
- let userId;
1744
- if (isCloudAccount(account)) {
1745
- userId = account.budibaseUserId;
1746
- } else {
1747
- userId = account.accountId;
1748
- }
1749
- return userId;
1750
- }
1751
- var init_identity = __esm({
1752
- "src/context/identity.ts"() {
1642
+ "../shared-core/src/constants/index.ts"() {
1753
1643
  "use strict";
1754
- init_src();
1755
- init_context2();
1644
+ init_api2();
1645
+ OperatorOptions = {
1646
+ Equals: {
1647
+ value: "equal",
1648
+ label: "Equals"
1649
+ },
1650
+ NotEquals: {
1651
+ value: "notEqual",
1652
+ label: "Not equals"
1653
+ },
1654
+ Empty: {
1655
+ value: "empty",
1656
+ label: "Is empty"
1657
+ },
1658
+ NotEmpty: {
1659
+ value: "notEmpty",
1660
+ label: "Is not empty"
1661
+ },
1662
+ StartsWith: {
1663
+ value: "string",
1664
+ label: "Starts with"
1665
+ },
1666
+ Like: {
1667
+ value: "fuzzy",
1668
+ label: "Like"
1669
+ },
1670
+ MoreThan: {
1671
+ value: "rangeLow",
1672
+ label: "More than or equal to"
1673
+ },
1674
+ LessThan: {
1675
+ value: "rangeHigh",
1676
+ label: "Less than or equal to"
1677
+ },
1678
+ Contains: {
1679
+ value: "contains",
1680
+ label: "Contains"
1681
+ },
1682
+ NotContains: {
1683
+ value: "notContains",
1684
+ label: "Does not contain"
1685
+ },
1686
+ In: {
1687
+ value: "oneOf",
1688
+ label: "Is in"
1689
+ },
1690
+ ContainsAny: {
1691
+ value: "containsAny",
1692
+ label: "Has any"
1693
+ }
1694
+ };
1756
1695
  }
1757
1696
  });
1758
1697
 
1759
- // src/environment.ts
1760
- function isTest() {
1761
- return isJest();
1762
- }
1763
- function isJest() {
1764
- return process.env.NODE_ENV === "jest" || process.env.JEST_WORKER_ID != null && process.env.JEST_WORKER_ID !== "null";
1765
- }
1766
- function isDev() {
1767
- return process.env.NODE_ENV !== "production";
1768
- }
1769
- function getAPIEncryptionKey() {
1770
- return process.env.API_ENCRYPTION_KEY ? process.env.API_ENCRYPTION_KEY : process.env.JWT_SECRET;
1771
- }
1772
- function httpLogging() {
1773
- if (process.env.HTTP_LOGGING === void 0) {
1774
- return true;
1775
- }
1776
- return process.env.HTTP_LOGGING;
1777
- }
1778
- function getPackageJsonFields() {
1779
- function findFileInAncestors(fileName, currentDir) {
1780
- const filePath = `${currentDir}/${fileName}`;
1781
- if ((0, import_fs.existsSync)(filePath)) {
1782
- return filePath;
1783
- }
1784
- const parentDir = `${currentDir}/..`;
1785
- if (parentDir === currentDir) {
1786
- return null;
1787
- }
1788
- return findFileInAncestors(fileName, parentDir);
1789
- }
1790
- try {
1791
- const packageJsonFile = findFileInAncestors("package.json", process.cwd());
1792
- const content = (0, import_fs.readFileSync)(packageJsonFile, "utf-8");
1793
- const parsedContent = JSON.parse(content);
1794
- return {
1795
- VERSION: process.env.BUDIBASE_VERSION || parsedContent.version,
1796
- SERVICE_NAME: parsedContent.name
1797
- };
1798
- } catch {
1799
- return { VERSION: process.env.BUDIBASE_VERSION || "", SERVICE_NAME: "" };
1800
- }
1801
- }
1802
- function isWorker() {
1803
- return environment.SERVICE_TYPE === "worker" /* WORKER */;
1804
- }
1805
- function isApps() {
1806
- return environment.SERVICE_TYPE === "apps" /* APPS */;
1807
- }
1808
- var import_fs, LOADED, DefaultBucketName, selfHosted, environment, environment_default;
1809
- var init_environment2 = __esm({
1810
- "src/environment.ts"() {
1698
+ // ../../node_modules/dayjs/dayjs.min.js
1699
+ var require_dayjs_min = __commonJS({
1700
+ "../../node_modules/dayjs/dayjs.min.js"(exports, module2) {
1811
1701
  "use strict";
1812
- import_fs = require("fs");
1813
- init_src();
1814
- LOADED = false;
1815
- if (!LOADED && isDev() && !isTest()) {
1816
- require("dotenv").config();
1817
- LOADED = true;
1818
- }
1819
- DefaultBucketName = {
1820
- BACKUPS: "backups",
1821
- APPS: "prod-budi-app-assets",
1822
- TEMPLATES: "templates",
1823
- GLOBAL: "global",
1824
- PLUGINS: "plugins"
1825
- };
1826
- selfHosted = !!parseInt(process.env.SELF_HOSTED || "");
1827
- environment = {
1828
- isTest,
1829
- isJest,
1830
- isDev,
1831
- isWorker,
1832
- isApps,
1833
- isProd: () => {
1834
- return !isDev();
1835
- },
1836
- JS_BCRYPT: process.env.JS_BCRYPT,
1837
- JWT_SECRET: process.env.JWT_SECRET,
1838
- JWT_SECRET_FALLBACK: process.env.JWT_SECRET_FALLBACK,
1839
- ENCRYPTION_KEY: process.env.ENCRYPTION_KEY,
1840
- API_ENCRYPTION_KEY: getAPIEncryptionKey(),
1841
- COUCH_DB_URL: process.env.COUCH_DB_URL || "http://localhost:4005",
1842
- COUCH_DB_SQL_URL: process.env.COUCH_DB_SQL_URL || "http://localhost:4984",
1843
- COUCH_DB_USERNAME: process.env.COUCH_DB_USER,
1844
- COUCH_DB_PASSWORD: process.env.COUCH_DB_PASSWORD,
1845
- GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
1846
- GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
1847
- SALT_ROUNDS: process.env.SALT_ROUNDS,
1848
- REDIS_URL: process.env.REDIS_URL || "localhost:6379",
1849
- REDIS_PASSWORD: process.env.REDIS_PASSWORD,
1850
- REDIS_CLUSTERED: process.env.REDIS_CLUSTERED,
1851
- MINIO_ACCESS_KEY: process.env.MINIO_ACCESS_KEY,
1852
- MINIO_SECRET_KEY: process.env.MINIO_SECRET_KEY,
1853
- AWS_REGION: process.env.AWS_REGION,
1854
- MINIO_URL: process.env.MINIO_URL,
1855
- MINIO_ENABLED: process.env.MINIO_ENABLED || 1,
1856
- INTERNAL_API_KEY: process.env.INTERNAL_API_KEY,
1857
- INTERNAL_API_KEY_FALLBACK: process.env.INTERNAL_API_KEY_FALLBACK,
1858
- MULTI_TENANCY: process.env.MULTI_TENANCY,
1859
- ACCOUNT_PORTAL_URL: process.env.ACCOUNT_PORTAL_URL || "https://account.budibase.app",
1860
- ACCOUNT_PORTAL_API_KEY: process.env.ACCOUNT_PORTAL_API_KEY || "",
1861
- DISABLE_ACCOUNT_PORTAL: process.env.DISABLE_ACCOUNT_PORTAL,
1862
- SELF_HOSTED: selfHosted,
1863
- COOKIE_DOMAIN: process.env.COOKIE_DOMAIN,
1864
- PLATFORM_URL: process.env.PLATFORM_URL || "",
1865
- POSTHOG_TOKEN: process.env.POSTHOG_TOKEN,
1866
- ENABLE_ANALYTICS: process.env.ENABLE_ANALYTICS,
1867
- TENANT_FEATURE_FLAGS: process.env.TENANT_FEATURE_FLAGS,
1868
- CLOUDFRONT_CDN: process.env.CLOUDFRONT_CDN,
1869
- CLOUDFRONT_PRIVATE_KEY_64: process.env.CLOUDFRONT_PRIVATE_KEY_64,
1870
- CLOUDFRONT_PUBLIC_KEY_ID: process.env.CLOUDFRONT_PUBLIC_KEY_ID,
1871
- BACKUPS_BUCKET_NAME: process.env.BACKUPS_BUCKET_NAME || DefaultBucketName.BACKUPS,
1872
- APPS_BUCKET_NAME: process.env.APPS_BUCKET_NAME || DefaultBucketName.APPS,
1873
- TEMPLATES_BUCKET_NAME: process.env.TEMPLATES_BUCKET_NAME || DefaultBucketName.TEMPLATES,
1874
- GLOBAL_BUCKET_NAME: process.env.GLOBAL_BUCKET_NAME || DefaultBucketName.GLOBAL,
1875
- PLUGIN_BUCKET_NAME: process.env.PLUGIN_BUCKET_NAME || DefaultBucketName.PLUGINS,
1876
- USE_COUCH: process.env.USE_COUCH || true,
1877
- MOCK_REDIS: process.env.MOCK_REDIS,
1878
- DEFAULT_LICENSE: process.env.DEFAULT_LICENSE,
1879
- SERVICE: process.env.SERVICE || "budibase",
1880
- LOG_LEVEL: process.env.LOG_LEVEL || "info",
1881
- SESSION_UPDATE_PERIOD: process.env.SESSION_UPDATE_PERIOD,
1882
- DEPLOYMENT_ENVIRONMENT: process.env.DEPLOYMENT_ENVIRONMENT || "docker-compose",
1883
- HTTP_LOGGING: httpLogging(),
1884
- ENABLE_AUDIT_LOG_IP_ADDR: process.env.ENABLE_AUDIT_LOG_IP_ADDR,
1885
- // smtp
1886
- SMTP_FALLBACK_ENABLED: process.env.SMTP_FALLBACK_ENABLED,
1887
- SMTP_USER: process.env.SMTP_USER,
1888
- SMTP_PASSWORD: process.env.SMTP_PASSWORD,
1889
- SMTP_HOST: process.env.SMTP_HOST,
1890
- SMTP_PORT: parseInt(process.env.SMTP_PORT || ""),
1891
- SMTP_FROM_ADDRESS: process.env.SMTP_FROM_ADDRESS,
1892
- DISABLE_JWT_WARNING: process.env.DISABLE_JWT_WARNING,
1893
- BLACKLIST_IPS: process.env.BLACKLIST_IPS,
1894
- SERVICE_TYPE: "unknown",
1895
- /**
1896
- * Enable to allow an admin user to login using a password.
1897
- * This can be useful to prevent lockout when configuring SSO.
1898
- * However, this should be turned OFF by default for security purposes.
1899
- */
1900
- ENABLE_SSO_MAINTENANCE_MODE: selfHosted ? process.env.ENABLE_SSO_MAINTENANCE_MODE : false,
1901
- ...getPackageJsonFields(),
1902
- DISABLE_PINO_LOGGER: process.env.DISABLE_PINO_LOGGER,
1903
- OFFLINE_MODE: process.env.OFFLINE_MODE,
1904
- _set(key, value) {
1905
- process.env[key] = value;
1906
- environment[key] = value;
1907
- },
1908
- ROLLING_LOG_MAX_SIZE: process.env.ROLLING_LOG_MAX_SIZE || "10M"
1909
- };
1910
- for (let [key, value] of Object.entries(environment)) {
1911
- if (value === "0") {
1912
- environment[key] = 0;
1913
- }
1914
- if (value === "false") {
1915
- environment[key] = 0;
1916
- }
1917
- }
1918
- environment_default = environment;
1919
- }
1920
- });
1921
-
1922
- // src/context/Context.ts
1923
- var import_async_hooks, Context;
1924
- var init_Context = __esm({
1925
- "src/context/Context.ts"() {
1926
- "use strict";
1927
- import_async_hooks = require("async_hooks");
1928
- Context = class _Context {
1929
- static {
1930
- this.storage = new import_async_hooks.AsyncLocalStorage();
1931
- }
1932
- static run(context, func) {
1933
- return _Context.storage.run(context, () => func());
1934
- }
1935
- static get() {
1936
- return _Context.storage.getStore();
1937
- }
1938
- };
1939
- }
1940
- });
1941
-
1942
- // src/docIds/conversions.ts
1943
- function isDevAppID(appId) {
1944
- if (!appId) {
1945
- throw NO_APP_ERROR;
1946
- }
1947
- return appId.startsWith(APP_DEV_PREFIX);
1948
- }
1949
- function isProdAppID(appId) {
1950
- if (!appId) {
1951
- throw NO_APP_ERROR;
1952
- }
1953
- return appId.startsWith(APP_PREFIX) && !isDevAppID(appId);
1954
- }
1955
- function isDevApp(app) {
1956
- if (!app) {
1957
- throw NO_APP_ERROR;
1958
- }
1959
- return isDevAppID(app.appId);
1960
- }
1961
- function getDevelopmentAppID(appId) {
1962
- if (!appId || appId.startsWith(APP_DEV_PREFIX)) {
1963
- return appId;
1964
- }
1965
- const split = appId.split(APP_PREFIX);
1966
- split.shift();
1967
- const rest = split.join(APP_PREFIX);
1968
- return `${APP_DEV_PREFIX}${rest}`;
1969
- }
1970
- function getProdAppID(appId) {
1971
- if (!appId || !appId.startsWith(APP_DEV_PREFIX)) {
1972
- return appId;
1973
- }
1974
- const split = appId.split(APP_DEV_PREFIX);
1975
- split.shift();
1976
- const rest = split.join(APP_DEV_PREFIX);
1977
- return `${APP_PREFIX}${rest}`;
1978
- }
1979
- function extractAppUUID(id) {
1980
- const split = id?.split("_") || [];
1981
- return split.length ? split[split.length - 1] : null;
1982
- }
1983
- var NO_APP_ERROR, getDevAppID;
1984
- var init_conversions = __esm({
1985
- "src/docIds/conversions.ts"() {
1986
- "use strict";
1987
- init_constants3();
1988
- NO_APP_ERROR = "No app provided";
1989
- getDevAppID = getDevelopmentAppID;
1990
- }
1991
- });
1992
-
1993
- // src/db/couch/connections.ts
1994
- var getCouchInfo, getUrlInfo;
1995
- var init_connections = __esm({
1996
- "src/db/couch/connections.ts"() {
1997
- "use strict";
1998
- init_environment2();
1999
- getCouchInfo = (connection) => {
2000
- const urlInfo = getUrlInfo(connection);
2001
- let username;
2002
- let password;
2003
- if (urlInfo.auth?.username) {
2004
- username = urlInfo.auth.username;
2005
- } else if (environment_default.COUCH_DB_USERNAME) {
2006
- username = environment_default.COUCH_DB_USERNAME;
2007
- } else if (!environment_default.isTest()) {
2008
- throw new Error("CouchDB username not set");
2009
- }
2010
- if (urlInfo.auth?.password) {
2011
- password = urlInfo.auth.password;
2012
- } else if (environment_default.COUCH_DB_PASSWORD) {
2013
- password = environment_default.COUCH_DB_PASSWORD;
2014
- } else if (!environment_default.isTest()) {
2015
- throw new Error("CouchDB password not set");
2016
- }
2017
- const authCookie = Buffer.from(`${username}:${password}`).toString("base64");
2018
- return {
2019
- url: urlInfo.url,
2020
- auth: {
2021
- username,
2022
- password
2023
- },
2024
- cookie: `Basic ${authCookie}`
2025
- };
2026
- };
2027
- getUrlInfo = (url = environment_default.COUCH_DB_URL) => {
2028
- let cleanUrl, username, password, host;
2029
- if (url) {
2030
- const protoRegex = /^https?:\/\//i;
2031
- if (!protoRegex.test(url)) {
2032
- url = `http://${url}`;
2033
- }
2034
- const split = url.split("://");
2035
- const protocol = split[0];
2036
- const rest = split.slice(1).join("://");
2037
- if (url.includes("@")) {
2038
- let parts = rest.split("@");
2039
- host = parts[parts.length - 1];
2040
- let auth = parts.slice(0, -1).join("@");
2041
- if (auth.includes(":")) {
2042
- const authParts = auth.split(":");
2043
- username = authParts[0];
2044
- password = authParts.slice(1).join(":");
2045
- } else {
2046
- username = auth;
2047
- }
1702
+ !function(t, e) {
1703
+ "object" == typeof exports && "undefined" != typeof module2 ? module2.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs = e();
1704
+ }(exports, function() {
1705
+ "use strict";
1706
+ var t = 1e3, e = 6e4, n = 36e5, r = "millisecond", i = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t2) {
1707
+ var e2 = ["th", "st", "nd", "rd"], n2 = t2 % 100;
1708
+ return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
1709
+ } }, m = function(t2, e2, n2) {
1710
+ var r2 = String(t2);
1711
+ return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
1712
+ }, v = { s: m, z: function(t2) {
1713
+ var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60;
1714
+ return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0");
1715
+ }, m: function t2(e2, n2) {
1716
+ if (e2.date() < n2.date())
1717
+ return -t2(n2, e2);
1718
+ var r2 = 12 * (n2.year() - e2.year()) + (n2.month() - e2.month()), i2 = e2.clone().add(r2, c), s2 = n2 - i2 < 0, u2 = e2.clone().add(r2 + (s2 ? -1 : 1), c);
1719
+ return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0);
1720
+ }, a: function(t2) {
1721
+ return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
1722
+ }, p: function(t2) {
1723
+ return { M: c, y: h, w: o, d: a, D: d, h: u, m: s, s: i, ms: r, Q: f }[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
1724
+ }, u: function(t2) {
1725
+ return void 0 === t2;
1726
+ } }, g = "en", D = {};
1727
+ D[g] = M;
1728
+ var p = "$isDayjsObject", S = function(t2) {
1729
+ return t2 instanceof _2 || !(!t2 || !t2[p]);
1730
+ }, w = function t2(e2, n2, r2) {
1731
+ var i2;
1732
+ if (!e2)
1733
+ return g;
1734
+ if ("string" == typeof e2) {
1735
+ var s2 = e2.toLowerCase();
1736
+ D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2);
1737
+ var u2 = e2.split("-");
1738
+ if (!i2 && u2.length > 1)
1739
+ return t2(u2[0]);
2048
1740
  } else {
2049
- host = rest;
2050
- }
2051
- cleanUrl = `${protocol}://${host}`;
2052
- }
2053
- return {
2054
- url: cleanUrl,
2055
- auth: {
2056
- username,
2057
- password
1741
+ var a2 = e2.name;
1742
+ D[a2] = e2, i2 = a2;
2058
1743
  }
1744
+ return !r2 && i2 && (g = i2), i2 || !r2 && g;
1745
+ }, O = function(t2, e2) {
1746
+ if (S(t2))
1747
+ return t2.clone();
1748
+ var n2 = "object" == typeof e2 ? e2 : {};
1749
+ return n2.date = t2, n2.args = arguments, new _2(n2);
1750
+ }, b = v;
1751
+ b.l = w, b.i = S, b.w = function(t2, e2) {
1752
+ return O(t2, { locale: e2.$L, utc: e2.$u, x: e2.$x, $offset: e2.$offset });
2059
1753
  };
2060
- };
2061
- }
2062
- });
2063
-
2064
- // src/helpers.ts
2065
- function checkSlashesInUrl(url) {
2066
- return url.replace(/(https?:\/\/)|(\/)+/g, "$1$2");
2067
- }
2068
- var init_helpers = __esm({
2069
- "src/helpers.ts"() {
2070
- "use strict";
2071
- }
2072
- });
2073
-
2074
- // src/db/couch/utils.ts
2075
- async function directCouchCall(path2, method = "GET", body2) {
2076
- let { url, cookie } = getCouchInfo();
2077
- const couchUrl = `${url}/${path2}`;
2078
- return await directCouchUrlCall({ url: couchUrl, cookie, method, body: body2 });
2079
- }
2080
- async function directCouchUrlCall({
2081
- url,
2082
- cookie,
2083
- method,
2084
- body: body2
2085
- }) {
2086
- const params2 = {
2087
- method,
2088
- headers: {
2089
- Authorization: cookie
2090
- }
2091
- };
2092
- if (body2 && method !== "GET") {
2093
- params2.body = JSON.stringify(body2);
2094
- params2.headers["Content-Type"] = "application/json";
2095
- }
2096
- return await (0, import_node_fetch.default)(checkSlashesInUrl(encodeURI(url)), params2);
2097
- }
2098
- async function directCouchQuery(path2, method = "GET", body2) {
2099
- const response = await directCouchCall(path2, method, body2);
2100
- if (response.status < 300) {
2101
- return await response.json();
2102
- } else {
2103
- throw "Cannot connect to CouchDB instance";
1754
+ var _2 = function() {
1755
+ function M2(t2) {
1756
+ this.$L = w(t2.locale, null, true), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = true;
1757
+ }
1758
+ var m2 = M2.prototype;
1759
+ return m2.parse = function(t2) {
1760
+ this.$d = function(t3) {
1761
+ var e2 = t3.date, n2 = t3.utc;
1762
+ if (null === e2)
1763
+ return /* @__PURE__ */ new Date(NaN);
1764
+ if (b.u(e2))
1765
+ return /* @__PURE__ */ new Date();
1766
+ if (e2 instanceof Date)
1767
+ return new Date(e2);
1768
+ if ("string" == typeof e2 && !/Z$/i.test(e2)) {
1769
+ var r2 = e2.match($);
1770
+ if (r2) {
1771
+ var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
1772
+ return n2 ? new Date(Date.UTC(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2)) : new Date(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2);
1773
+ }
1774
+ }
1775
+ return new Date(e2);
1776
+ }(t2), this.init();
1777
+ }, m2.init = function() {
1778
+ var t2 = this.$d;
1779
+ this.$y = t2.getFullYear(), this.$M = t2.getMonth(), this.$D = t2.getDate(), this.$W = t2.getDay(), this.$H = t2.getHours(), this.$m = t2.getMinutes(), this.$s = t2.getSeconds(), this.$ms = t2.getMilliseconds();
1780
+ }, m2.$utils = function() {
1781
+ return b;
1782
+ }, m2.isValid = function() {
1783
+ return !(this.$d.toString() === l);
1784
+ }, m2.isSame = function(t2, e2) {
1785
+ var n2 = O(t2);
1786
+ return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
1787
+ }, m2.isAfter = function(t2, e2) {
1788
+ return O(t2) < this.startOf(e2);
1789
+ }, m2.isBefore = function(t2, e2) {
1790
+ return this.endOf(e2) < O(t2);
1791
+ }, m2.$g = function(t2, e2, n2) {
1792
+ return b.u(t2) ? this[e2] : this.set(n2, t2);
1793
+ }, m2.unix = function() {
1794
+ return Math.floor(this.valueOf() / 1e3);
1795
+ }, m2.valueOf = function() {
1796
+ return this.$d.getTime();
1797
+ }, m2.startOf = function(t2, e2) {
1798
+ var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
1799
+ var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
1800
+ return r2 ? i2 : i2.endOf(a);
1801
+ }, $2 = function(t3, e3) {
1802
+ return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e3)), n2);
1803
+ }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
1804
+ switch (f2) {
1805
+ case h:
1806
+ return r2 ? l2(1, 0) : l2(31, 11);
1807
+ case c:
1808
+ return r2 ? l2(1, M3) : l2(0, M3 + 1);
1809
+ case o:
1810
+ var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
1811
+ return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
1812
+ case a:
1813
+ case d:
1814
+ return $2(v2 + "Hours", 0);
1815
+ case u:
1816
+ return $2(v2 + "Minutes", 1);
1817
+ case s:
1818
+ return $2(v2 + "Seconds", 2);
1819
+ case i:
1820
+ return $2(v2 + "Milliseconds", 3);
1821
+ default:
1822
+ return this.clone();
1823
+ }
1824
+ }, m2.endOf = function(t2) {
1825
+ return this.startOf(t2, false);
1826
+ }, m2.$set = function(t2, e2) {
1827
+ var n2, o2 = b.p(t2), f2 = "set" + (this.$u ? "UTC" : ""), l2 = (n2 = {}, n2[a] = f2 + "Date", n2[d] = f2 + "Date", n2[c] = f2 + "Month", n2[h] = f2 + "FullYear", n2[u] = f2 + "Hours", n2[s] = f2 + "Minutes", n2[i] = f2 + "Seconds", n2[r] = f2 + "Milliseconds", n2)[o2], $2 = o2 === a ? this.$D + (e2 - this.$W) : e2;
1828
+ if (o2 === c || o2 === h) {
1829
+ var y2 = this.clone().set(d, 1);
1830
+ y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
1831
+ } else
1832
+ l2 && this.$d[l2]($2);
1833
+ return this.init(), this;
1834
+ }, m2.set = function(t2, e2) {
1835
+ return this.clone().$set(t2, e2);
1836
+ }, m2.get = function(t2) {
1837
+ return this[b.p(t2)]();
1838
+ }, m2.add = function(r2, f2) {
1839
+ var d2, l2 = this;
1840
+ r2 = Number(r2);
1841
+ var $2 = b.p(f2), y2 = function(t2) {
1842
+ var e2 = O(l2);
1843
+ return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
1844
+ };
1845
+ if ($2 === c)
1846
+ return this.set(c, this.$M + r2);
1847
+ if ($2 === h)
1848
+ return this.set(h, this.$y + r2);
1849
+ if ($2 === a)
1850
+ return y2(1);
1851
+ if ($2 === o)
1852
+ return y2(7);
1853
+ var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
1854
+ return b.w(m3, this);
1855
+ }, m2.subtract = function(t2, e2) {
1856
+ return this.add(-1 * t2, e2);
1857
+ }, m2.format = function(t2) {
1858
+ var e2 = this, n2 = this.$locale();
1859
+ if (!this.isValid())
1860
+ return n2.invalidDate || l;
1861
+ var r2 = t2 || "YYYY-MM-DDTHH:mm:ssZ", i2 = b.z(this), s2 = this.$H, u2 = this.$m, a2 = this.$M, o2 = n2.weekdays, c2 = n2.months, f2 = n2.meridiem, h2 = function(t3, n3, i3, s3) {
1862
+ return t3 && (t3[n3] || t3(e2, r2)) || i3[n3].slice(0, s3);
1863
+ }, d2 = function(t3) {
1864
+ return b.s(s2 % 12 || 12, t3, "0");
1865
+ }, $2 = f2 || function(t3, e3, n3) {
1866
+ var r3 = t3 < 12 ? "AM" : "PM";
1867
+ return n3 ? r3.toLowerCase() : r3;
1868
+ };
1869
+ return r2.replace(y, function(t3, r3) {
1870
+ return r3 || function(t4) {
1871
+ switch (t4) {
1872
+ case "YY":
1873
+ return String(e2.$y).slice(-2);
1874
+ case "YYYY":
1875
+ return b.s(e2.$y, 4, "0");
1876
+ case "M":
1877
+ return a2 + 1;
1878
+ case "MM":
1879
+ return b.s(a2 + 1, 2, "0");
1880
+ case "MMM":
1881
+ return h2(n2.monthsShort, a2, c2, 3);
1882
+ case "MMMM":
1883
+ return h2(c2, a2);
1884
+ case "D":
1885
+ return e2.$D;
1886
+ case "DD":
1887
+ return b.s(e2.$D, 2, "0");
1888
+ case "d":
1889
+ return String(e2.$W);
1890
+ case "dd":
1891
+ return h2(n2.weekdaysMin, e2.$W, o2, 2);
1892
+ case "ddd":
1893
+ return h2(n2.weekdaysShort, e2.$W, o2, 3);
1894
+ case "dddd":
1895
+ return o2[e2.$W];
1896
+ case "H":
1897
+ return String(s2);
1898
+ case "HH":
1899
+ return b.s(s2, 2, "0");
1900
+ case "h":
1901
+ return d2(1);
1902
+ case "hh":
1903
+ return d2(2);
1904
+ case "a":
1905
+ return $2(s2, u2, true);
1906
+ case "A":
1907
+ return $2(s2, u2, false);
1908
+ case "m":
1909
+ return String(u2);
1910
+ case "mm":
1911
+ return b.s(u2, 2, "0");
1912
+ case "s":
1913
+ return String(e2.$s);
1914
+ case "ss":
1915
+ return b.s(e2.$s, 2, "0");
1916
+ case "SSS":
1917
+ return b.s(e2.$ms, 3, "0");
1918
+ case "Z":
1919
+ return i2;
1920
+ }
1921
+ return null;
1922
+ }(t3) || i2.replace(":", "");
1923
+ });
1924
+ }, m2.utcOffset = function() {
1925
+ return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
1926
+ }, m2.diff = function(r2, d2, l2) {
1927
+ var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
1928
+ return b.m(y2, m3);
1929
+ };
1930
+ switch (M3) {
1931
+ case h:
1932
+ $2 = D2() / 12;
1933
+ break;
1934
+ case c:
1935
+ $2 = D2();
1936
+ break;
1937
+ case f:
1938
+ $2 = D2() / 3;
1939
+ break;
1940
+ case o:
1941
+ $2 = (g2 - v2) / 6048e5;
1942
+ break;
1943
+ case a:
1944
+ $2 = (g2 - v2) / 864e5;
1945
+ break;
1946
+ case u:
1947
+ $2 = g2 / n;
1948
+ break;
1949
+ case s:
1950
+ $2 = g2 / e;
1951
+ break;
1952
+ case i:
1953
+ $2 = g2 / t;
1954
+ break;
1955
+ default:
1956
+ $2 = g2;
1957
+ }
1958
+ return l2 ? $2 : b.a($2);
1959
+ }, m2.daysInMonth = function() {
1960
+ return this.endOf(c).$D;
1961
+ }, m2.$locale = function() {
1962
+ return D[this.$L];
1963
+ }, m2.locale = function(t2, e2) {
1964
+ if (!t2)
1965
+ return this.$L;
1966
+ var n2 = this.clone(), r2 = w(t2, e2, true);
1967
+ return r2 && (n2.$L = r2), n2;
1968
+ }, m2.clone = function() {
1969
+ return b.w(this.$d, this);
1970
+ }, m2.toDate = function() {
1971
+ return new Date(this.valueOf());
1972
+ }, m2.toJSON = function() {
1973
+ return this.isValid() ? this.toISOString() : null;
1974
+ }, m2.toISOString = function() {
1975
+ return this.$d.toISOString();
1976
+ }, m2.toString = function() {
1977
+ return this.$d.toUTCString();
1978
+ }, M2;
1979
+ }(), k = _2.prototype;
1980
+ return O.prototype = k, [["$ms", r], ["$s", i], ["$m", s], ["$H", u], ["$W", a], ["$M", c], ["$y", h], ["$D", d]].forEach(function(t2) {
1981
+ k[t2[1]] = function(e2) {
1982
+ return this.$g(e2, t2[0], t2[1]);
1983
+ };
1984
+ }), O.extend = function(t2, e2) {
1985
+ return t2.$i || (t2(e2, _2, O), t2.$i = true), O;
1986
+ }, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
1987
+ return O(1e3 * t2);
1988
+ }, O.en = D[g], O.Ls = D, O.p = {}, O;
1989
+ });
2104
1990
  }
2105
- }
2106
- var import_node_fetch;
2107
- var init_utils = __esm({
2108
- "src/db/couch/utils.ts"() {
1991
+ });
1992
+
1993
+ // ../shared-core/src/helpers/helpers.ts
1994
+ var init_helpers = __esm({
1995
+ "../shared-core/src/helpers/helpers.ts"() {
2109
1996
  "use strict";
2110
- init_connections();
2111
- import_node_fetch = __toESM(require("node-fetch"));
2112
- init_helpers();
2113
1997
  }
2114
1998
  });
2115
1999
 
2116
- // src/db/couch/pouchDB.ts
2117
- function init(opts) {
2118
- Pouch = getPouch(opts);
2119
- initialised = true;
2000
+ // ../shared-core/src/helpers/integrations.ts
2001
+ var init_integrations = __esm({
2002
+ "../shared-core/src/helpers/integrations.ts"() {
2003
+ "use strict";
2004
+ init_src();
2005
+ }
2006
+ });
2007
+
2008
+ // ../shared-core/src/helpers/index.ts
2009
+ var init_helpers2 = __esm({
2010
+ "../shared-core/src/helpers/index.ts"() {
2011
+ "use strict";
2012
+ init_helpers();
2013
+ init_integrations();
2014
+ }
2015
+ });
2016
+
2017
+ // ../shared-core/src/filters.ts
2018
+ var import_dayjs, NoEmptyFilterStrings;
2019
+ var init_filters = __esm({
2020
+ "../shared-core/src/filters.ts"() {
2021
+ "use strict";
2022
+ init_src();
2023
+ import_dayjs = __toESM(require_dayjs_min());
2024
+ init_constants3();
2025
+ init_helpers2();
2026
+ NoEmptyFilterStrings = [
2027
+ OperatorOptions.StartsWith.value,
2028
+ OperatorOptions.Like.value,
2029
+ OperatorOptions.Equals.value,
2030
+ OperatorOptions.NotEquals.value,
2031
+ OperatorOptions.Contains.value,
2032
+ OperatorOptions.NotContains.value
2033
+ ];
2034
+ }
2035
+ });
2036
+
2037
+ // ../shared-core/src/utils.ts
2038
+ var utils_exports = {};
2039
+ __export(utils_exports, {
2040
+ filterValueToLabel: () => filterValueToLabel,
2041
+ parallelForeach: () => parallelForeach,
2042
+ unreachable: () => unreachable
2043
+ });
2044
+ function unreachable(value, message = `No such case in exhaustive switch: ${value}`) {
2045
+ throw new Error(message);
2120
2046
  }
2121
- function getPouchDB(dbName, opts) {
2122
- checkInitialised();
2123
- const db = new Pouch(dbName, opts);
2124
- const dbPut = db.put;
2125
- db.put = async (doc, options2 = {}) => {
2126
- if (!doc.createdAt) {
2127
- doc.createdAt = (/* @__PURE__ */ new Date()).toISOString();
2047
+ async function parallelForeach(items, task, maxConcurrency) {
2048
+ const promises = [];
2049
+ let index2 = 0;
2050
+ const processItem = async (item) => {
2051
+ try {
2052
+ await task(item);
2053
+ } finally {
2054
+ processNext();
2128
2055
  }
2129
- doc.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2130
- return dbPut(doc, options2);
2131
2056
  };
2132
- db.exists = async () => {
2133
- const info = await db.info();
2134
- return !info.error;
2057
+ const processNext = () => {
2058
+ if (index2 >= items.length) {
2059
+ return;
2060
+ }
2061
+ const item = items[index2];
2062
+ index2++;
2063
+ const promise = processItem(item);
2064
+ promises.push(promise);
2065
+ if (promises.length >= maxConcurrency) {
2066
+ Promise.race(promises).then(processNext);
2067
+ } else {
2068
+ processNext();
2069
+ }
2135
2070
  };
2136
- return db;
2071
+ processNext();
2072
+ await Promise.all(promises);
2137
2073
  }
2138
- async function closePouchDB(db) {
2139
- if (!db || environment_default.isTest()) {
2140
- return;
2141
- }
2142
- try {
2143
- return await db.close();
2144
- } catch (err) {
2145
- }
2074
+ function filterValueToLabel() {
2075
+ return Object.keys(OperatorOptions).reduce(
2076
+ (acc, key) => {
2077
+ const ops = OperatorOptions;
2078
+ const op = ops[key];
2079
+ acc[op["value"]] = op.label;
2080
+ return acc;
2081
+ },
2082
+ {}
2083
+ );
2146
2084
  }
2147
- var import_pouchdb, Pouch, initialised, getPouch, checkInitialised;
2148
- var init_pouchDB = __esm({
2149
- "src/db/couch/pouchDB.ts"() {
2085
+ var init_utils = __esm({
2086
+ "../shared-core/src/utils.ts"() {
2150
2087
  "use strict";
2151
- import_pouchdb = __toESM(require("pouchdb"));
2152
- init_environment2();
2153
- init_connections();
2154
- initialised = false;
2155
- getPouch = (opts = {}) => {
2156
- let { url, cookie } = getCouchInfo();
2157
- let POUCH_DB_DEFAULTS = {
2158
- prefix: url,
2159
- fetch: (url2, opts2) => {
2160
- opts2.headers.set("Authorization", cookie);
2161
- return import_pouchdb.default.fetch(url2, opts2);
2162
- }
2163
- };
2164
- if (opts.inMemory) {
2165
- const inMemory = require("pouchdb-adapter-memory");
2166
- import_pouchdb.default.plugin(inMemory);
2167
- POUCH_DB_DEFAULTS = {
2168
- // @ts-ignore
2169
- adapter: "memory"
2170
- };
2171
- }
2172
- if (opts.onDisk) {
2173
- POUCH_DB_DEFAULTS = {
2174
- // @ts-ignore
2175
- adapter: "leveldb"
2176
- };
2177
- }
2178
- if (opts.replication) {
2179
- const replicationStream = require("@budibase/pouchdb-replication-stream");
2180
- import_pouchdb.default.plugin(replicationStream.plugin);
2181
- import_pouchdb.default.adapter("writableStream", replicationStream.adapters.writableStream);
2182
- }
2183
- if (opts.find) {
2184
- const find2 = require("pouchdb-find");
2185
- import_pouchdb.default.plugin(find2);
2186
- }
2187
- return import_pouchdb.default.defaults(POUCH_DB_DEFAULTS);
2188
- };
2189
- checkInitialised = () => {
2190
- if (!initialised) {
2191
- throw new Error("init has not been called");
2192
- }
2193
- };
2088
+ init_constants3();
2194
2089
  }
2195
2090
  });
2196
2091
 
2197
- // src/docIds/newid.ts
2198
- function newid() {
2199
- return (0, import_uuid.v4)().replace(/-/g, "");
2092
+ // ../shared-core/src/sdk/documents/applications.ts
2093
+ var applications_exports = {};
2094
+ __export(applications_exports, {
2095
+ getDevAppID: () => getDevAppID,
2096
+ getProdAppID: () => getProdAppID
2097
+ });
2098
+ function getDevAppID(appId) {
2099
+ if (!appId) {
2100
+ throw new Error("No app ID provided");
2101
+ }
2102
+ if (appId.startsWith(APP_DEV_PREFIX2)) {
2103
+ return appId;
2104
+ }
2105
+ const split = appId.split(APP_PREFIX2);
2106
+ split.shift();
2107
+ const rest = split.join(APP_PREFIX2);
2108
+ return `${APP_DEV_PREFIX2}${rest}`;
2200
2109
  }
2201
- var import_uuid;
2202
- var init_newid = __esm({
2203
- "src/docIds/newid.ts"() {
2110
+ function getProdAppID(appId) {
2111
+ if (!appId) {
2112
+ throw new Error("No app ID provided");
2113
+ }
2114
+ if (!appId.startsWith(APP_DEV_PREFIX2)) {
2115
+ return appId;
2116
+ }
2117
+ const split = appId.split(APP_DEV_PREFIX2);
2118
+ split.shift();
2119
+ const rest = split.join(APP_DEV_PREFIX2);
2120
+ return `${APP_PREFIX2}${rest}`;
2121
+ }
2122
+ var APP_PREFIX2, APP_DEV_PREFIX2;
2123
+ var init_applications = __esm({
2124
+ "../shared-core/src/sdk/documents/applications.ts"() {
2204
2125
  "use strict";
2205
- import_uuid = require("uuid");
2126
+ init_src();
2127
+ APP_PREFIX2 = prefixed("app" /* APP */);
2128
+ APP_DEV_PREFIX2 = prefixed("app_dev" /* APP_DEV */);
2206
2129
  }
2207
2130
  });
2208
2131
 
2209
- // src/db/couch/DatabaseImpl.ts
2210
- function buildNano(couchInfo) {
2211
- return (0, import_nano.default)({
2212
- url: couchInfo.url,
2213
- requestDefaults: {
2214
- headers: {
2215
- Authorization: couchInfo.cookie
2216
- }
2217
- },
2218
- parseUrl: false
2219
- });
2132
+ // ../shared-core/src/sdk/documents/users.ts
2133
+ var users_exports = {};
2134
+ __export(users_exports, {
2135
+ canCreateApps: () => canCreateApps,
2136
+ containsUserID: () => containsUserID,
2137
+ getGlobalUserID: () => getGlobalUserID,
2138
+ hasAdminPermissions: () => hasAdminPermissions,
2139
+ hasAppBuilderPermissions: () => hasAppBuilderPermissions,
2140
+ hasAppCreatorPermissions: () => hasAppCreatorPermissions,
2141
+ hasBuilderPermissions: () => hasBuilderPermissions,
2142
+ hasCreatorPermissions: () => hasCreatorPermissions,
2143
+ isAdmin: () => isAdmin,
2144
+ isAdminOrBuilder: () => isAdminOrBuilder,
2145
+ isAdminOrGlobalBuilder: () => isAdminOrGlobalBuilder,
2146
+ isBuilder: () => isBuilder,
2147
+ isCreator: () => isCreator,
2148
+ isGlobalBuilder: () => isGlobalBuilder
2149
+ });
2150
+ function isBuilder(user, appId) {
2151
+ if (!user) {
2152
+ return false;
2153
+ }
2154
+ if (user.builder?.global) {
2155
+ return true;
2156
+ } else if (appId && user.builder?.apps?.includes(getProdAppID(appId))) {
2157
+ return true;
2158
+ }
2159
+ return false;
2220
2160
  }
2221
- function DatabaseWithConnection(dbName, connection, opts) {
2222
- if (!connection) {
2223
- throw new Error("Must provide connection details");
2161
+ function isGlobalBuilder(user) {
2162
+ return isBuilder(user) && !hasAppBuilderPermissions(user) || isAdmin(user);
2163
+ }
2164
+ function canCreateApps(user) {
2165
+ return isGlobalBuilder(user) || hasCreatorPermissions(user);
2166
+ }
2167
+ function isAdmin(user) {
2168
+ if (!user) {
2169
+ return false;
2224
2170
  }
2225
- return new DatabaseImpl(dbName, opts, connection);
2171
+ return hasAdminPermissions(user);
2226
2172
  }
2227
- var import_nano, DatabaseImpl;
2228
- var init_DatabaseImpl = __esm({
2229
- "src/db/couch/DatabaseImpl.ts"() {
2230
- "use strict";
2231
- import_nano = __toESM(require("@budibase/nano"));
2232
- init_src();
2233
- init_connections();
2234
- init_utils();
2235
- init_pouchDB();
2236
- init_newid();
2237
- DatabaseImpl = class _DatabaseImpl {
2238
- constructor(dbName, opts, connection) {
2239
- this.couchInfo = getCouchInfo();
2240
- this.name = dbName;
2241
- this.pouchOpts = opts || {};
2242
- if (connection) {
2243
- this.couchInfo = getCouchInfo(connection);
2244
- this.instanceNano = buildNano(this.couchInfo);
2245
- }
2246
- if (!_DatabaseImpl.nano) {
2247
- _DatabaseImpl.init();
2248
- }
2249
- }
2250
- static init() {
2251
- const couchInfo = getCouchInfo();
2252
- _DatabaseImpl.nano = buildNano(couchInfo);
2253
- }
2254
- async exists() {
2255
- const response = await directCouchUrlCall({
2256
- url: `${this.couchInfo.url}/${this.name}`,
2257
- method: "HEAD",
2258
- cookie: this.couchInfo.cookie
2259
- });
2260
- return response.status === 200;
2261
- }
2262
- nano() {
2263
- return this.instanceNano || _DatabaseImpl.nano;
2264
- }
2265
- async checkSetup() {
2266
- let shouldCreate = !this.pouchOpts?.skip_setup;
2267
- let exists2 = await this.exists();
2268
- if (!shouldCreate && !exists2) {
2269
- throw new Error("DB does not exist");
2270
- }
2271
- if (!exists2) {
2272
- try {
2273
- await this.nano().db.create(this.name);
2274
- } catch (err) {
2275
- if (err.statusCode !== 412) {
2276
- throw err;
2277
- }
2278
- }
2279
- }
2280
- return this.nano().db.use(this.name);
2281
- }
2282
- async updateOutput(fnc) {
2283
- try {
2284
- return await fnc();
2285
- } catch (err) {
2286
- if (err.statusCode) {
2287
- err.status = err.statusCode;
2288
- }
2289
- throw err;
2290
- }
2291
- }
2292
- async get(id) {
2293
- const db = await this.checkSetup();
2294
- if (!id) {
2295
- throw new Error("Unable to get doc without a valid _id.");
2296
- }
2297
- return this.updateOutput(() => db.get(id));
2298
- }
2299
- async getMultiple(ids, opts) {
2300
- ids = [...new Set(ids)];
2301
- const response = await this.allDocs({
2302
- keys: ids,
2303
- include_docs: true
2304
- });
2305
- const rowUnavailable = (row) => {
2306
- if (row.doc == null || "deleted" in row.value && row.value.deleted) {
2307
- return true;
2308
- }
2309
- return row.error === "not_found";
2310
- };
2311
- const rows = response.rows.filter((row) => !rowUnavailable(row));
2312
- const someMissing = rows.length !== response.rows.length;
2313
- if (!opts?.allowMissing && someMissing) {
2314
- const missing = response.rows.filter((row) => rowUnavailable(row));
2315
- const missingIds = missing.map((row) => row.key).join(", ");
2316
- throw new Error(`Unable to get documents: ${missingIds}`);
2317
- }
2318
- return rows.map((row) => row.doc);
2319
- }
2320
- async remove(idOrDoc, rev) {
2321
- const db = await this.checkSetup();
2322
- let _id;
2323
- let _rev;
2324
- if (isDocument(idOrDoc)) {
2325
- _id = idOrDoc._id;
2326
- _rev = idOrDoc._rev;
2327
- } else {
2328
- _id = idOrDoc;
2329
- _rev = rev;
2330
- }
2331
- if (!_id || !_rev) {
2332
- throw new Error("Unable to remove doc without a valid _id and _rev.");
2333
- }
2334
- return this.updateOutput(() => db.destroy(_id, _rev));
2335
- }
2336
- async post(document, opts) {
2337
- if (!document._id) {
2338
- document._id = newid();
2339
- }
2340
- return this.put(document, opts);
2341
- }
2342
- async put(document, opts) {
2343
- if (!document._id) {
2344
- throw new Error("Cannot store document without _id field.");
2345
- }
2346
- const db = await this.checkSetup();
2347
- if (!document.createdAt) {
2348
- document.createdAt = (/* @__PURE__ */ new Date()).toISOString();
2349
- }
2350
- document.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2351
- if (opts?.force && document._id) {
2352
- try {
2353
- const existing = await this.get(document._id);
2354
- if (existing) {
2355
- document._rev = existing._rev;
2356
- }
2357
- } catch (err) {
2358
- if (err.status !== 404) {
2359
- throw err;
2360
- }
2361
- }
2362
- }
2363
- return this.updateOutput(() => db.insert(document));
2364
- }
2365
- async bulkDocs(documents) {
2366
- const db = await this.checkSetup();
2367
- return this.updateOutput(() => db.bulk({ docs: documents }));
2368
- }
2369
- async allDocs(params2) {
2370
- const db = await this.checkSetup();
2371
- return this.updateOutput(() => db.list(params2));
2372
- }
2373
- async query(viewName, params2) {
2374
- const db = await this.checkSetup();
2375
- const [database, view] = viewName.split("/");
2376
- return this.updateOutput(() => db.view(database, view, params2));
2377
- }
2378
- async destroy() {
2379
- try {
2380
- return await this.nano().db.destroy(this.name);
2381
- } catch (err) {
2382
- if (err.statusCode === 404) {
2383
- return;
2384
- } else {
2385
- throw { ...err, status: err.statusCode };
2386
- }
2387
- }
2388
- }
2389
- async compact() {
2390
- const db = await this.checkSetup();
2391
- return this.updateOutput(() => db.compact());
2392
- }
2393
- // All below functions are in-frequently called, just utilise PouchDB
2394
- // for them as it implements them better than we can
2395
- async dump(stream2, opts) {
2396
- const pouch = getPouchDB(this.name);
2397
- return pouch.dump(stream2, opts);
2398
- }
2399
- async load(stream2) {
2400
- const pouch = getPouchDB(this.name);
2401
- return pouch.load(stream2);
2402
- }
2403
- async createIndex(opts) {
2404
- const pouch = getPouchDB(this.name);
2405
- return pouch.createIndex(opts);
2406
- }
2407
- async deleteIndex(opts) {
2408
- const pouch = getPouchDB(this.name);
2409
- return pouch.deleteIndex(opts);
2410
- }
2411
- async getIndexes() {
2412
- const pouch = getPouchDB(this.name);
2413
- return pouch.getIndexes();
2414
- }
2415
- };
2173
+ function isAdminOrBuilder(user, appId) {
2174
+ return isBuilder(user, appId) || isAdmin(user);
2175
+ }
2176
+ function isAdminOrGlobalBuilder(user, appId) {
2177
+ return isGlobalBuilder(user) || isAdmin(user);
2178
+ }
2179
+ function hasAppBuilderPermissions(user) {
2180
+ if (!user) {
2181
+ return false;
2416
2182
  }
2417
- });
2418
-
2419
- // src/db/constants.ts
2420
- function isInternalColumnName(name) {
2421
- return CONSTANT_INTERNAL_ROW_COLS.includes(name);
2183
+ const appLength = user.builder?.apps?.length;
2184
+ const isGlobalBuilder3 = !!user.builder?.global;
2185
+ return !isGlobalBuilder3 && appLength != null && appLength > 0;
2422
2186
  }
2423
- var CONSTANT_INTERNAL_ROW_COLS, CONSTANT_EXTERNAL_ROW_COLS;
2424
- var init_constants4 = __esm({
2425
- "src/db/constants.ts"() {
2426
- "use strict";
2427
- CONSTANT_INTERNAL_ROW_COLS = [
2428
- "_id",
2429
- "_rev",
2430
- "type",
2431
- "createdAt",
2432
- "updatedAt",
2433
- "tableId"
2434
- ];
2435
- CONSTANT_EXTERNAL_ROW_COLS = ["_id", "_rev", "tableId"];
2187
+ function hasAppCreatorPermissions(user) {
2188
+ if (!user) {
2189
+ return false;
2436
2190
  }
2437
- });
2438
-
2439
- // src/db/couch/index.ts
2440
- var init_couch = __esm({
2441
- "src/db/couch/index.ts"() {
2442
- "use strict";
2443
- init_connections();
2444
- init_DatabaseImpl();
2445
- init_utils();
2446
- init_pouchDB();
2447
- init_constants4();
2191
+ return _.flow(
2192
+ _.get("roles"),
2193
+ _.values,
2194
+ _.find((x) => x === "CREATOR"),
2195
+ (x) => !!x
2196
+ )(user);
2197
+ }
2198
+ function hasBuilderPermissions(user) {
2199
+ if (!user) {
2200
+ return false;
2448
2201
  }
2449
- });
2450
-
2451
- // src/db/db.ts
2452
- function getDB(dbName, opts) {
2453
- return new DatabaseImpl(dbName, opts);
2202
+ return user.builder?.global || hasAppBuilderPermissions(user) || hasCreatorPermissions(user);
2454
2203
  }
2455
- async function doWithDB(dbName, cb, opts) {
2456
- const db = getDB(dbName, opts);
2457
- return await cb(db);
2204
+ function hasAdminPermissions(user) {
2205
+ if (!user) {
2206
+ return false;
2207
+ }
2208
+ return !!user.admin?.global;
2458
2209
  }
2459
- async function directCouchAllDbs(queryString) {
2460
- let couchPath = "/_all_dbs";
2461
- if (queryString) {
2462
- couchPath += `?${queryString}`;
2210
+ function hasCreatorPermissions(user) {
2211
+ if (!user) {
2212
+ return false;
2463
2213
  }
2464
- return await directCouchQuery(couchPath);
2214
+ return !!user.builder?.creator;
2465
2215
  }
2466
- async function directCouchFind(dbName, opts) {
2467
- const json = await directCouchQuery(`${dbName}/_find`, "POST", opts);
2468
- return { rows: json.docs, bookmark: json.bookmark };
2216
+ function isCreator(user) {
2217
+ if (!user) {
2218
+ return false;
2219
+ }
2220
+ return isGlobalBuilder(user) || hasAdminPermissions(user) || hasCreatorPermissions(user) || hasAppBuilderPermissions(user) || hasAppCreatorPermissions(user);
2469
2221
  }
2470
- var init_db3 = __esm({
2471
- "src/db/db.ts"() {
2472
- "use strict";
2473
- init_couch();
2222
+ function getGlobalUserID(userId) {
2223
+ if (typeof userId !== "string") {
2224
+ return userId;
2474
2225
  }
2475
- });
2476
-
2477
- // src/context/mainContext.ts
2478
- function getGlobalDBName(tenantId) {
2479
- if (!tenantId) {
2480
- tenantId = getTenantId();
2226
+ const prefix = `${"ro" /* ROW */}${SEPARATOR}${"ta_users" /* USER_METADATA */}${SEPARATOR}`;
2227
+ if (!userId.startsWith(prefix)) {
2228
+ return userId;
2481
2229
  }
2482
- return baseGlobalDBName(tenantId);
2230
+ return userId.split(prefix)[1];
2483
2231
  }
2484
- function getAuditLogDBName(tenantId) {
2485
- if (!tenantId) {
2486
- tenantId = getTenantId();
2487
- }
2488
- if (tenantId === DEFAULT_TENANT_ID) {
2489
- return StaticDatabases.AUDIT_LOGS.name;
2490
- } else {
2491
- return `${tenantId}${SEPARATOR}${StaticDatabases.AUDIT_LOGS.name}`;
2232
+ function containsUserID(value) {
2233
+ if (typeof value !== "string") {
2234
+ return false;
2492
2235
  }
2236
+ return value.includes(`${"us" /* USER */}${SEPARATOR}`);
2493
2237
  }
2494
- function baseGlobalDBName(tenantId) {
2495
- if (!tenantId || tenantId === DEFAULT_TENANT_ID) {
2496
- return StaticDatabases.GLOBAL.name;
2497
- } else {
2498
- return `${tenantId}${SEPARATOR}${StaticDatabases.GLOBAL.name}`;
2238
+ var _;
2239
+ var init_users3 = __esm({
2240
+ "../shared-core/src/sdk/documents/users.ts"() {
2241
+ "use strict";
2242
+ init_src();
2243
+ init_applications();
2244
+ _ = __toESM(require("lodash/fp"));
2499
2245
  }
2246
+ });
2247
+
2248
+ // ../shared-core/src/sdk/documents/index.ts
2249
+ var init_documents2 = __esm({
2250
+ "../shared-core/src/sdk/documents/index.ts"() {
2251
+ "use strict";
2252
+ init_applications();
2253
+ init_users3();
2254
+ }
2255
+ });
2256
+
2257
+ // ../shared-core/src/sdk/index.ts
2258
+ var sdk_exports = {};
2259
+ __export(sdk_exports, {
2260
+ applications: () => applications_exports,
2261
+ users: () => users_exports
2262
+ });
2263
+ var init_sdk2 = __esm({
2264
+ "../shared-core/src/sdk/index.ts"() {
2265
+ "use strict";
2266
+ init_documents2();
2267
+ }
2268
+ });
2269
+
2270
+ // ../shared-core/src/table.ts
2271
+ var allowDisplayColumnByType, allowSortColumnByType;
2272
+ var init_table5 = __esm({
2273
+ "../shared-core/src/table.ts"() {
2274
+ "use strict";
2275
+ init_src();
2276
+ allowDisplayColumnByType = {
2277
+ ["string" /* STRING */]: true,
2278
+ ["longform" /* LONGFORM */]: true,
2279
+ ["options" /* OPTIONS */]: true,
2280
+ ["number" /* NUMBER */]: true,
2281
+ ["datetime" /* DATETIME */]: true,
2282
+ ["formula" /* FORMULA */]: true,
2283
+ ["auto" /* AUTO */]: true,
2284
+ ["internal" /* INTERNAL */]: true,
2285
+ ["barcodeqr" /* BARCODEQR */]: true,
2286
+ ["bigint" /* BIGINT */]: true,
2287
+ ["boolean" /* BOOLEAN */]: false,
2288
+ ["array" /* ARRAY */]: false,
2289
+ ["attachment" /* ATTACHMENT */]: false,
2290
+ ["link" /* LINK */]: false,
2291
+ ["json" /* JSON */]: false,
2292
+ ["bb_reference" /* BB_REFERENCE */]: false
2293
+ };
2294
+ allowSortColumnByType = {
2295
+ ["string" /* STRING */]: true,
2296
+ ["longform" /* LONGFORM */]: true,
2297
+ ["options" /* OPTIONS */]: true,
2298
+ ["number" /* NUMBER */]: true,
2299
+ ["datetime" /* DATETIME */]: true,
2300
+ ["auto" /* AUTO */]: true,
2301
+ ["internal" /* INTERNAL */]: true,
2302
+ ["barcodeqr" /* BARCODEQR */]: true,
2303
+ ["bigint" /* BIGINT */]: true,
2304
+ ["boolean" /* BOOLEAN */]: true,
2305
+ ["json" /* JSON */]: true,
2306
+ ["formula" /* FORMULA */]: false,
2307
+ ["attachment" /* ATTACHMENT */]: false,
2308
+ ["array" /* ARRAY */]: false,
2309
+ ["link" /* LINK */]: false,
2310
+ ["bb_reference" /* BB_REFERENCE */]: false
2311
+ };
2312
+ }
2313
+ });
2314
+
2315
+ // ../shared-core/src/index.ts
2316
+ var init_src2 = __esm({
2317
+ "../shared-core/src/index.ts"() {
2318
+ "use strict";
2319
+ init_constants3();
2320
+ init_filters();
2321
+ init_helpers2();
2322
+ init_utils();
2323
+ init_sdk2();
2324
+ init_table5();
2325
+ }
2326
+ });
2327
+
2328
+ // src/constants/misc.ts
2329
+ var UserStatus, Cookie, GlobalRole, Config, MIN_VALID_DATE, MAX_VALID_DATE, DEFAULT_TENANT_ID;
2330
+ var init_misc = __esm({
2331
+ "src/constants/misc.ts"() {
2332
+ "use strict";
2333
+ init_src2();
2334
+ UserStatus = /* @__PURE__ */ ((UserStatus3) => {
2335
+ UserStatus3["ACTIVE"] = "active";
2336
+ UserStatus3["INACTIVE"] = "inactive";
2337
+ return UserStatus3;
2338
+ })(UserStatus || {});
2339
+ Cookie = /* @__PURE__ */ ((Cookie2) => {
2340
+ Cookie2["Auth"] = "budibase:auth";
2341
+ Cookie2["Init"] = "budibase:init";
2342
+ Cookie2["ACCOUNT_RETURN_URL"] = "budibase:account:returnurl";
2343
+ Cookie2["DatasourceAuth"] = "budibase:datasourceauth";
2344
+ Cookie2["OIDC_CONFIG"] = "budibase:oidc:config";
2345
+ return Cookie2;
2346
+ })(Cookie || {});
2347
+ GlobalRole = /* @__PURE__ */ ((GlobalRole2) => {
2348
+ GlobalRole2["OWNER"] = "owner";
2349
+ GlobalRole2["ADMIN"] = "admin";
2350
+ GlobalRole2["BUILDER"] = "builder";
2351
+ GlobalRole2["WORKSPACE_MANAGER"] = "workspace_manager";
2352
+ return GlobalRole2;
2353
+ })(GlobalRole || {});
2354
+ Config = /* @__PURE__ */ ((Config3) => {
2355
+ Config3["SETTINGS"] = "settings";
2356
+ Config3["ACCOUNT"] = "account";
2357
+ Config3["SMTP"] = "smtp";
2358
+ Config3["GOOGLE"] = "google";
2359
+ Config3["OIDC"] = "oidc";
2360
+ Config3["OIDC_LOGOS"] = "logos_oidc";
2361
+ Config3["SCIM"] = "scim";
2362
+ return Config3;
2363
+ })(Config || {});
2364
+ MIN_VALID_DATE = /* @__PURE__ */ new Date(-2147483647e3);
2365
+ MAX_VALID_DATE = /* @__PURE__ */ new Date(2147483647e3);
2366
+ DEFAULT_TENANT_ID = "default";
2367
+ }
2368
+ });
2369
+
2370
+ // src/constants/index.ts
2371
+ var constants_exports2 = {};
2372
+ __export(constants_exports2, {
2373
+ APP_DEV: () => APP_DEV,
2374
+ APP_DEV_PREFIX: () => APP_DEV_PREFIX,
2375
+ APP_PREFIX: () => APP_PREFIX,
2376
+ AutomationViewMode: () => AutomationViewMode,
2377
+ BUDIBASE_DATASOURCE_TYPE: () => BUDIBASE_DATASOURCE_TYPE,
2378
+ Config: () => Config,
2379
+ Cookie: () => Cookie,
2380
+ DEFAULT_TENANT_ID: () => DEFAULT_TENANT_ID,
2381
+ DeprecatedViews: () => DeprecatedViews,
2382
+ DocumentType: () => DocumentType,
2383
+ GlobalRole: () => GlobalRole,
2384
+ Header: () => Header,
2385
+ InternalTable: () => InternalTable,
2386
+ MAX_VALID_DATE: () => MAX_VALID_DATE,
2387
+ MIN_VALID_DATE: () => MIN_VALID_DATE,
2388
+ SEPARATOR: () => SEPARATOR,
2389
+ StaticDatabases: () => StaticDatabases,
2390
+ UNICODE_MAX: () => UNICODE_MAX,
2391
+ UserStatus: () => UserStatus,
2392
+ ViewName: () => ViewName
2393
+ });
2394
+ var init_constants4 = __esm({
2395
+ "src/constants/index.ts"() {
2396
+ "use strict";
2397
+ init_db2();
2398
+ init_misc();
2399
+ }
2400
+ });
2401
+
2402
+ // src/context/identity.ts
2403
+ var identity_exports = {};
2404
+ __export(identity_exports, {
2405
+ doInAccountContext: () => doInAccountContext,
2406
+ doInIdentityContext: () => doInIdentityContext2,
2407
+ doInUserContext: () => doInUserContext,
2408
+ getAccountUserId: () => getAccountUserId,
2409
+ getIdentity: () => getIdentity2
2410
+ });
2411
+ function getIdentity2() {
2412
+ return getIdentity();
2500
2413
  }
2501
- function getPlatformURL() {
2502
- return environment_default.PLATFORM_URL;
2503
- }
2504
- function isMultiTenant() {
2505
- return !!environment_default.MULTI_TENANCY;
2414
+ function doInIdentityContext2(identity, task) {
2415
+ return doInIdentityContext(identity, task);
2506
2416
  }
2507
- function isTenantIdSet() {
2508
- const context = Context.get();
2509
- return !!context?.tenantId;
2417
+ function doInUserContext(user, ctx, task) {
2418
+ const userContext = {
2419
+ ...user,
2420
+ _id: user._id,
2421
+ type: "user" /* USER */,
2422
+ hostInfo: {
2423
+ ipAddress: ctx.request.ip,
2424
+ // filled in by koa-useragent package
2425
+ userAgent: ctx.userAgent._agent.source
2426
+ }
2427
+ };
2428
+ return doInIdentityContext2(userContext, task);
2510
2429
  }
2511
- function isTenancyEnabled() {
2512
- return environment_default.MULTI_TENANCY;
2430
+ function doInAccountContext(account, task) {
2431
+ const _id = getAccountUserId(account);
2432
+ const tenantId = account.tenantId;
2433
+ const accountContext = {
2434
+ _id,
2435
+ type: "user" /* USER */,
2436
+ tenantId,
2437
+ account
2438
+ };
2439
+ return doInIdentityContext2(accountContext, task);
2513
2440
  }
2514
- function getTenantIDFromAppID(appId) {
2515
- if (!appId) {
2516
- return void 0;
2517
- }
2518
- if (!isMultiTenant()) {
2519
- return DEFAULT_TENANT_ID;
2520
- }
2521
- const split = appId.split(SEPARATOR);
2522
- const hasDev = split[1] === "dev" /* DEV */;
2523
- if (hasDev && split.length === 3 || !hasDev && split.length === 2) {
2524
- return void 0;
2525
- }
2526
- if (hasDev) {
2527
- return split[2];
2441
+ function getAccountUserId(account) {
2442
+ let userId;
2443
+ if (isCloudAccount(account)) {
2444
+ userId = account.budibaseUserId;
2528
2445
  } else {
2529
- return split[1];
2446
+ userId = account.accountId;
2530
2447
  }
2448
+ return userId;
2531
2449
  }
2532
- function updateContext(updates) {
2533
- let context;
2534
- try {
2535
- context = Context.get();
2536
- } catch (err) {
2537
- context = {};
2450
+ var init_identity = __esm({
2451
+ "src/context/identity.ts"() {
2452
+ "use strict";
2453
+ init_src();
2454
+ init_context2();
2538
2455
  }
2539
- context = {
2540
- ...context,
2541
- ...updates
2542
- };
2543
- return context;
2456
+ });
2457
+
2458
+ // src/environment.ts
2459
+ function isTest() {
2460
+ return isJest();
2544
2461
  }
2545
- async function newContext(updates, task) {
2546
- guardMigration();
2547
- let context = updateContext(updates);
2548
- return Context.run(context, task);
2462
+ function isJest() {
2463
+ return process.env.NODE_ENV === "jest" || process.env.JEST_WORKER_ID != null && process.env.JEST_WORKER_ID !== "null";
2549
2464
  }
2550
- async function doInAutomationContext(params2) {
2551
- const tenantId = getTenantIDFromAppID(params2.appId);
2552
- return newContext(
2553
- {
2554
- tenantId,
2555
- appId: params2.appId,
2556
- automationId: params2.automationId
2557
- },
2558
- params2.task
2559
- );
2465
+ function isDev() {
2466
+ return process.env.NODE_ENV !== "production";
2560
2467
  }
2561
- async function doInContext(appId, task) {
2562
- const tenantId = getTenantIDFromAppID(appId);
2563
- return newContext(
2564
- {
2565
- tenantId,
2566
- appId
2567
- },
2568
- task
2569
- );
2468
+ function getAPIEncryptionKey() {
2469
+ return process.env.API_ENCRYPTION_KEY ? process.env.API_ENCRYPTION_KEY : process.env.JWT_SECRET;
2570
2470
  }
2571
- async function doInTenant(tenantId, task) {
2572
- if (!environment_default.MULTI_TENANCY) {
2573
- tenantId = tenantId || DEFAULT_TENANT_ID;
2471
+ function httpLogging() {
2472
+ if (process.env.HTTP_LOGGING === void 0) {
2473
+ return true;
2574
2474
  }
2575
- const updates = tenantId ? { tenantId } : {};
2576
- return newContext(updates, task);
2577
- }
2578
- async function doInAppContext(appId, task) {
2579
- return _doInAppContext(appId, task);
2475
+ return process.env.HTTP_LOGGING;
2580
2476
  }
2581
- async function _doInAppContext(appId, task, extraContextSettings) {
2582
- if (!appId) {
2583
- throw new Error("appId is required");
2584
- }
2585
- const tenantId = getTenantIDFromAppID(appId);
2586
- const updates = { appId, ...extraContextSettings };
2587
- if (tenantId) {
2588
- updates.tenantId = tenantId;
2589
- }
2590
- return newContext(updates, task);
2591
- }
2592
- async function doInIdentityContext(identity, task) {
2593
- if (!identity) {
2594
- throw new Error("identity is required");
2477
+ function getPackageJsonFields() {
2478
+ function findFileInAncestors(fileName, currentDir) {
2479
+ const filePath = `${currentDir}/${fileName}`;
2480
+ if ((0, import_fs.existsSync)(filePath)) {
2481
+ return filePath;
2482
+ }
2483
+ const parentDir = `${currentDir}/..`;
2484
+ if (parentDir === currentDir) {
2485
+ return null;
2486
+ }
2487
+ return findFileInAncestors(fileName, parentDir);
2595
2488
  }
2596
- const context = {
2597
- identity
2598
- };
2599
- if (identity.tenantId) {
2600
- context.tenantId = identity.tenantId;
2489
+ try {
2490
+ const packageJsonFile = findFileInAncestors("package.json", process.cwd());
2491
+ const content = (0, import_fs.readFileSync)(packageJsonFile, "utf-8");
2492
+ const parsedContent = JSON.parse(content);
2493
+ return {
2494
+ VERSION: process.env.BUDIBASE_VERSION || parsedContent.version,
2495
+ SERVICE_NAME: parsedContent.name
2496
+ };
2497
+ } catch {
2498
+ return { VERSION: process.env.BUDIBASE_VERSION || "", SERVICE_NAME: "" };
2601
2499
  }
2602
- return newContext(context, task);
2603
2500
  }
2604
- function guardMigration() {
2605
- const context = Context.get();
2606
- if (context?.isMigrating) {
2607
- throw new Error(
2608
- "The context cannot be changed, a migration is currently running"
2609
- );
2610
- }
2501
+ function isWorker() {
2502
+ return environment.SERVICE_TYPE === "worker" /* WORKER */;
2611
2503
  }
2612
- async function doInAppMigrationContext(appId, task) {
2613
- return _doInAppContext(appId, task, {
2614
- isMigrating: true
2615
- });
2504
+ function isApps() {
2505
+ return environment.SERVICE_TYPE === "apps" /* APPS */;
2616
2506
  }
2617
- function getIdentity() {
2618
- try {
2619
- const context = Context.get();
2620
- return context?.identity;
2621
- } catch (e) {
2507
+ var import_fs, LOADED, DefaultBucketName, selfHosted, environment, environment_default;
2508
+ var init_environment2 = __esm({
2509
+ "src/environment.ts"() {
2510
+ "use strict";
2511
+ import_fs = require("fs");
2512
+ init_src();
2513
+ LOADED = false;
2514
+ if (!LOADED && isDev() && !isTest()) {
2515
+ require("dotenv").config();
2516
+ LOADED = true;
2517
+ }
2518
+ DefaultBucketName = {
2519
+ BACKUPS: "backups",
2520
+ APPS: "prod-budi-app-assets",
2521
+ TEMPLATES: "templates",
2522
+ GLOBAL: "global",
2523
+ PLUGINS: "plugins"
2524
+ };
2525
+ selfHosted = !!parseInt(process.env.SELF_HOSTED || "");
2526
+ environment = {
2527
+ isTest,
2528
+ isJest,
2529
+ isDev,
2530
+ isWorker,
2531
+ isApps,
2532
+ isProd: () => {
2533
+ return !isDev();
2534
+ },
2535
+ JS_BCRYPT: process.env.JS_BCRYPT,
2536
+ JWT_SECRET: process.env.JWT_SECRET,
2537
+ JWT_SECRET_FALLBACK: process.env.JWT_SECRET_FALLBACK,
2538
+ ENCRYPTION_KEY: process.env.ENCRYPTION_KEY,
2539
+ API_ENCRYPTION_KEY: getAPIEncryptionKey(),
2540
+ COUCH_DB_URL: process.env.COUCH_DB_URL || "http://localhost:4005",
2541
+ COUCH_DB_SQL_URL: process.env.COUCH_DB_SQL_URL || "http://localhost:4984",
2542
+ COUCH_DB_USERNAME: process.env.COUCH_DB_USER,
2543
+ COUCH_DB_PASSWORD: process.env.COUCH_DB_PASSWORD,
2544
+ GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
2545
+ GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
2546
+ SALT_ROUNDS: process.env.SALT_ROUNDS,
2547
+ REDIS_URL: process.env.REDIS_URL || "localhost:6379",
2548
+ REDIS_PASSWORD: process.env.REDIS_PASSWORD,
2549
+ REDIS_CLUSTERED: process.env.REDIS_CLUSTERED,
2550
+ MINIO_ACCESS_KEY: process.env.MINIO_ACCESS_KEY,
2551
+ MINIO_SECRET_KEY: process.env.MINIO_SECRET_KEY,
2552
+ AWS_REGION: process.env.AWS_REGION,
2553
+ MINIO_URL: process.env.MINIO_URL,
2554
+ MINIO_ENABLED: process.env.MINIO_ENABLED || 1,
2555
+ INTERNAL_API_KEY: process.env.INTERNAL_API_KEY,
2556
+ INTERNAL_API_KEY_FALLBACK: process.env.INTERNAL_API_KEY_FALLBACK,
2557
+ MULTI_TENANCY: process.env.MULTI_TENANCY,
2558
+ ACCOUNT_PORTAL_URL: process.env.ACCOUNT_PORTAL_URL || "https://account.budibase.app",
2559
+ ACCOUNT_PORTAL_API_KEY: process.env.ACCOUNT_PORTAL_API_KEY || "",
2560
+ DISABLE_ACCOUNT_PORTAL: process.env.DISABLE_ACCOUNT_PORTAL,
2561
+ SELF_HOSTED: selfHosted,
2562
+ COOKIE_DOMAIN: process.env.COOKIE_DOMAIN,
2563
+ PLATFORM_URL: process.env.PLATFORM_URL || "",
2564
+ POSTHOG_TOKEN: process.env.POSTHOG_TOKEN,
2565
+ ENABLE_ANALYTICS: process.env.ENABLE_ANALYTICS,
2566
+ TENANT_FEATURE_FLAGS: process.env.TENANT_FEATURE_FLAGS,
2567
+ CLOUDFRONT_CDN: process.env.CLOUDFRONT_CDN,
2568
+ CLOUDFRONT_PRIVATE_KEY_64: process.env.CLOUDFRONT_PRIVATE_KEY_64,
2569
+ CLOUDFRONT_PUBLIC_KEY_ID: process.env.CLOUDFRONT_PUBLIC_KEY_ID,
2570
+ BACKUPS_BUCKET_NAME: process.env.BACKUPS_BUCKET_NAME || DefaultBucketName.BACKUPS,
2571
+ APPS_BUCKET_NAME: process.env.APPS_BUCKET_NAME || DefaultBucketName.APPS,
2572
+ TEMPLATES_BUCKET_NAME: process.env.TEMPLATES_BUCKET_NAME || DefaultBucketName.TEMPLATES,
2573
+ GLOBAL_BUCKET_NAME: process.env.GLOBAL_BUCKET_NAME || DefaultBucketName.GLOBAL,
2574
+ PLUGIN_BUCKET_NAME: process.env.PLUGIN_BUCKET_NAME || DefaultBucketName.PLUGINS,
2575
+ USE_COUCH: process.env.USE_COUCH || true,
2576
+ MOCK_REDIS: process.env.MOCK_REDIS,
2577
+ DEFAULT_LICENSE: process.env.DEFAULT_LICENSE,
2578
+ SERVICE: process.env.SERVICE || "budibase",
2579
+ LOG_LEVEL: process.env.LOG_LEVEL || "info",
2580
+ SESSION_UPDATE_PERIOD: process.env.SESSION_UPDATE_PERIOD,
2581
+ DEPLOYMENT_ENVIRONMENT: process.env.DEPLOYMENT_ENVIRONMENT || "docker-compose",
2582
+ HTTP_LOGGING: httpLogging(),
2583
+ ENABLE_AUDIT_LOG_IP_ADDR: process.env.ENABLE_AUDIT_LOG_IP_ADDR,
2584
+ // smtp
2585
+ SMTP_FALLBACK_ENABLED: process.env.SMTP_FALLBACK_ENABLED,
2586
+ SMTP_USER: process.env.SMTP_USER,
2587
+ SMTP_PASSWORD: process.env.SMTP_PASSWORD,
2588
+ SMTP_HOST: process.env.SMTP_HOST,
2589
+ SMTP_PORT: parseInt(process.env.SMTP_PORT || ""),
2590
+ SMTP_FROM_ADDRESS: process.env.SMTP_FROM_ADDRESS,
2591
+ DISABLE_JWT_WARNING: process.env.DISABLE_JWT_WARNING,
2592
+ BLACKLIST_IPS: process.env.BLACKLIST_IPS,
2593
+ SERVICE_TYPE: "unknown",
2594
+ /**
2595
+ * Enable to allow an admin user to login using a password.
2596
+ * This can be useful to prevent lockout when configuring SSO.
2597
+ * However, this should be turned OFF by default for security purposes.
2598
+ */
2599
+ ENABLE_SSO_MAINTENANCE_MODE: selfHosted ? process.env.ENABLE_SSO_MAINTENANCE_MODE : false,
2600
+ ...getPackageJsonFields(),
2601
+ DISABLE_PINO_LOGGER: process.env.DISABLE_PINO_LOGGER,
2602
+ OFFLINE_MODE: process.env.OFFLINE_MODE,
2603
+ _set(key, value) {
2604
+ process.env[key] = value;
2605
+ environment[key] = value;
2606
+ },
2607
+ ROLLING_LOG_MAX_SIZE: process.env.ROLLING_LOG_MAX_SIZE || "10M"
2608
+ };
2609
+ for (let [key, value] of Object.entries(environment)) {
2610
+ if (value === "0") {
2611
+ environment[key] = 0;
2612
+ }
2613
+ if (value === "false") {
2614
+ environment[key] = 0;
2615
+ }
2616
+ }
2617
+ environment_default = environment;
2622
2618
  }
2623
- }
2624
- function getTenantId() {
2625
- if (!isMultiTenant()) {
2626
- return DEFAULT_TENANT_ID;
2619
+ });
2620
+
2621
+ // src/context/Context.ts
2622
+ var import_async_hooks, Context;
2623
+ var init_Context = __esm({
2624
+ "src/context/Context.ts"() {
2625
+ "use strict";
2626
+ import_async_hooks = require("async_hooks");
2627
+ Context = class _Context {
2628
+ static {
2629
+ this.storage = new import_async_hooks.AsyncLocalStorage();
2630
+ }
2631
+ static run(context, func) {
2632
+ return _Context.storage.run(context, () => func());
2633
+ }
2634
+ static get() {
2635
+ return _Context.storage.getStore();
2636
+ }
2637
+ };
2627
2638
  }
2628
- const context = Context.get();
2629
- const tenantId = context?.tenantId;
2630
- if (!tenantId) {
2631
- throw new Error("Tenant id not found");
2639
+ });
2640
+
2641
+ // src/docIds/conversions.ts
2642
+ function isDevAppID(appId) {
2643
+ if (!appId) {
2644
+ throw NO_APP_ERROR;
2632
2645
  }
2633
- return tenantId;
2634
- }
2635
- function getAutomationId() {
2636
- const context = Context.get();
2637
- return context?.automationId;
2646
+ return appId.startsWith(APP_DEV_PREFIX);
2638
2647
  }
2639
- function getAppId() {
2640
- const context = Context.get();
2641
- const foundId = context?.appId;
2642
- if (!foundId && environment_default.isTest() && TEST_APP_ID) {
2643
- return TEST_APP_ID;
2644
- } else {
2645
- return foundId;
2648
+ function isProdAppID(appId) {
2649
+ if (!appId) {
2650
+ throw NO_APP_ERROR;
2646
2651
  }
2652
+ return appId.startsWith(APP_PREFIX) && !isDevAppID(appId);
2647
2653
  }
2648
- function doInEnvironmentContext(values2, task) {
2649
- if (!values2) {
2650
- throw new Error("Must supply environment variables.");
2654
+ function isDevApp(app) {
2655
+ if (!app) {
2656
+ throw NO_APP_ERROR;
2651
2657
  }
2652
- const updates = {
2653
- environmentVariables: values2
2654
- };
2655
- return newContext(updates, task);
2656
- }
2657
- function doInScimContext(task) {
2658
- const updates = {
2659
- isScim: true
2660
- };
2661
- return newContext(updates, task);
2658
+ return isDevAppID(app.appId);
2662
2659
  }
2663
- function getEnvironmentVariables() {
2664
- const context = Context.get();
2665
- if (!context.environmentVariables) {
2666
- return null;
2667
- } else {
2668
- return context.environmentVariables;
2660
+ function getDevelopmentAppID(appId) {
2661
+ if (!appId || appId.startsWith(APP_DEV_PREFIX)) {
2662
+ return appId;
2669
2663
  }
2664
+ const split = appId.split(APP_PREFIX);
2665
+ split.shift();
2666
+ const rest = split.join(APP_PREFIX);
2667
+ return `${APP_DEV_PREFIX}${rest}`;
2670
2668
  }
2671
- function getGlobalDB() {
2672
- const context = Context.get();
2673
- if (!context || environment_default.MULTI_TENANCY && !context.tenantId) {
2674
- throw new Error("Global DB not found");
2669
+ function getProdAppID2(appId) {
2670
+ if (!appId || !appId.startsWith(APP_DEV_PREFIX)) {
2671
+ return appId;
2675
2672
  }
2676
- return getDB(baseGlobalDBName(context?.tenantId));
2673
+ const split = appId.split(APP_DEV_PREFIX);
2674
+ split.shift();
2675
+ const rest = split.join(APP_DEV_PREFIX);
2676
+ return `${APP_PREFIX}${rest}`;
2677
2677
  }
2678
- function getAuditLogsDB() {
2679
- if (!getTenantId()) {
2680
- throw new Error("No tenant ID found - cannot open audit log DB");
2681
- }
2682
- return getDB(getAuditLogDBName());
2683
- }
2684
- function getAppDB(opts) {
2685
- const appId = getAppId();
2686
- if (!appId) {
2687
- throw new Error("Unable to retrieve app DB - no app ID.");
2688
- }
2689
- return getDB(appId, opts);
2690
- }
2691
- function getProdAppDB(opts) {
2692
- const appId = getAppId();
2693
- if (!appId) {
2694
- throw new Error("Unable to retrieve prod DB - no app ID.");
2695
- }
2696
- return getDB(getProdAppID(appId), opts);
2678
+ function extractAppUUID(id) {
2679
+ const split = id?.split("_") || [];
2680
+ return split.length ? split[split.length - 1] : null;
2697
2681
  }
2698
- function getDevAppDB(opts) {
2699
- const appId = getAppId();
2700
- if (!appId) {
2701
- throw new Error("Unable to retrieve dev DB - no app ID.");
2682
+ var NO_APP_ERROR, getDevAppID2;
2683
+ var init_conversions = __esm({
2684
+ "src/docIds/conversions.ts"() {
2685
+ "use strict";
2686
+ init_constants4();
2687
+ NO_APP_ERROR = "No app provided";
2688
+ getDevAppID2 = getDevelopmentAppID;
2702
2689
  }
2703
- return getDB(getDevelopmentAppID(appId), opts);
2704
- }
2705
- function isScim() {
2706
- const context = Context.get();
2707
- const scimCall = context?.isScim;
2708
- return !!scimCall;
2709
- }
2710
- var TEST_APP_ID, getProdAppId;
2711
- var init_mainContext = __esm({
2712
- "src/context/mainContext.ts"() {
2690
+ });
2691
+
2692
+ // src/db/couch/connections.ts
2693
+ var getCouchInfo, getUrlInfo;
2694
+ var init_connections = __esm({
2695
+ "src/db/couch/connections.ts"() {
2713
2696
  "use strict";
2714
2697
  init_environment2();
2715
- init_Context();
2716
- init_conversions();
2717
- init_db3();
2718
- init_constants3();
2719
- TEST_APP_ID = null;
2720
- getProdAppId = () => {
2721
- const appId = getAppId();
2722
- if (!appId) {
2723
- throw new Error("Could not get appId");
2698
+ getCouchInfo = (connection) => {
2699
+ const urlInfo = getUrlInfo(connection);
2700
+ let username;
2701
+ let password;
2702
+ if (urlInfo.auth?.username) {
2703
+ username = urlInfo.auth.username;
2704
+ } else if (environment_default.COUCH_DB_USERNAME) {
2705
+ username = environment_default.COUCH_DB_USERNAME;
2706
+ } else if (!environment_default.isTest()) {
2707
+ throw new Error("CouchDB username not set");
2724
2708
  }
2725
- return getProdAppID(appId);
2709
+ if (urlInfo.auth?.password) {
2710
+ password = urlInfo.auth.password;
2711
+ } else if (environment_default.COUCH_DB_PASSWORD) {
2712
+ password = environment_default.COUCH_DB_PASSWORD;
2713
+ } else if (!environment_default.isTest()) {
2714
+ throw new Error("CouchDB password not set");
2715
+ }
2716
+ const authCookie = Buffer.from(`${username}:${password}`).toString("base64");
2717
+ return {
2718
+ url: urlInfo.url,
2719
+ auth: {
2720
+ username,
2721
+ password
2722
+ },
2723
+ cookie: `Basic ${authCookie}`
2724
+ };
2725
+ };
2726
+ getUrlInfo = (url = environment_default.COUCH_DB_URL) => {
2727
+ let cleanUrl, username, password, host;
2728
+ if (url) {
2729
+ const protoRegex = /^https?:\/\//i;
2730
+ if (!protoRegex.test(url)) {
2731
+ url = `http://${url}`;
2732
+ }
2733
+ const split = url.split("://");
2734
+ const protocol = split[0];
2735
+ const rest = split.slice(1).join("://");
2736
+ if (url.includes("@")) {
2737
+ let parts = rest.split("@");
2738
+ host = parts[parts.length - 1];
2739
+ let auth = parts.slice(0, -1).join("@");
2740
+ if (auth.includes(":")) {
2741
+ const authParts = auth.split(":");
2742
+ username = authParts[0];
2743
+ password = authParts.slice(1).join(":");
2744
+ } else {
2745
+ username = auth;
2746
+ }
2747
+ } else {
2748
+ host = rest;
2749
+ }
2750
+ cleanUrl = `${protocol}://${host}`;
2751
+ }
2752
+ return {
2753
+ url: cleanUrl,
2754
+ auth: {
2755
+ username,
2756
+ password
2757
+ }
2758
+ };
2726
2759
  };
2727
2760
  }
2728
2761
  });
2729
2762
 
2730
- // src/context/index.ts
2731
- var context_exports = {};
2732
- __export(context_exports, {
2733
- DEFAULT_TENANT_ID: () => DEFAULT_TENANT_ID,
2734
- baseGlobalDBName: () => baseGlobalDBName,
2735
- doInAppContext: () => doInAppContext,
2736
- doInAppMigrationContext: () => doInAppMigrationContext,
2737
- doInAutomationContext: () => doInAutomationContext,
2738
- doInContext: () => doInContext,
2739
- doInEnvironmentContext: () => doInEnvironmentContext,
2740
- doInIdentityContext: () => doInIdentityContext,
2741
- doInScimContext: () => doInScimContext,
2742
- doInTenant: () => doInTenant,
2743
- getAppDB: () => getAppDB,
2744
- getAppId: () => getAppId,
2745
- getAuditLogDBName: () => getAuditLogDBName,
2746
- getAuditLogsDB: () => getAuditLogsDB,
2747
- getAutomationId: () => getAutomationId,
2748
- getDevAppDB: () => getDevAppDB,
2749
- getEnvironmentVariables: () => getEnvironmentVariables,
2750
- getGlobalDB: () => getGlobalDB,
2751
- getGlobalDBName: () => getGlobalDBName,
2752
- getIdentity: () => getIdentity,
2753
- getPlatformURL: () => getPlatformURL,
2754
- getProdAppDB: () => getProdAppDB,
2755
- getProdAppId: () => getProdAppId,
2756
- getTenantIDFromAppID: () => getTenantIDFromAppID,
2757
- getTenantId: () => getTenantId,
2758
- identity: () => identity_exports,
2759
- isMultiTenant: () => isMultiTenant,
2760
- isScim: () => isScim,
2761
- isTenancyEnabled: () => isTenancyEnabled,
2762
- isTenantIdSet: () => isTenantIdSet
2763
- });
2764
- var init_context2 = __esm({
2765
- "src/context/index.ts"() {
2763
+ // src/helpers.ts
2764
+ function checkSlashesInUrl(url) {
2765
+ return url.replace(/(https?:\/\/)|(\/)+/g, "$1$2");
2766
+ }
2767
+ var init_helpers3 = __esm({
2768
+ "src/helpers.ts"() {
2766
2769
  "use strict";
2767
- init_constants3();
2768
- init_identity();
2769
- init_mainContext();
2770
2770
  }
2771
2771
  });
2772
2772
 
2773
- // src/redis/utils.ts
2774
- var utils_exports = {};
2775
- __export(utils_exports, {
2776
- Databases: () => Databases,
2777
- SEPARATOR: () => SEPARATOR2,
2778
- SelectableDatabase: () => SelectableDatabase,
2779
- addDbPrefix: () => addDbPrefix,
2780
- getRedisConnectionDetails: () => getRedisConnectionDetails,
2781
- getRedisOptions: () => getRedisOptions,
2782
- removeDbPrefix: () => removeDbPrefix
2783
- });
2784
- function getRedisConnectionDetails() {
2785
- let password = environment_default.REDIS_PASSWORD;
2786
- let url = environment_default.REDIS_URL.split("//");
2787
- url = url.length > 1 ? url[1] : url[0];
2788
- url = url.split("@");
2789
- if (url.length > 1) {
2790
- password = url[0].split(":")[1];
2791
- url = url[1];
2792
- } else {
2793
- url = url[0];
2794
- }
2795
- const [host, port] = url.split(":");
2796
- const portNumber = parseInt(port);
2797
- return {
2798
- host,
2799
- password,
2800
- // assume default port for redis if invalid found
2801
- port: isNaN(portNumber) ? 6379 : portNumber
2802
- };
2773
+ // src/db/couch/utils.ts
2774
+ async function directCouchCall(path2, method = "GET", body2) {
2775
+ let { url, cookie } = getCouchInfo();
2776
+ const couchUrl = `${url}/${path2}`;
2777
+ return await directCouchUrlCall({ url: couchUrl, cookie, method, body: body2 });
2803
2778
  }
2804
- function getRedisOptions() {
2805
- const { host, password, port } = getRedisConnectionDetails();
2806
- let redisOpts = {
2807
- connectTimeout: CONNECT_TIMEOUT_MS,
2808
- port,
2809
- host,
2810
- password
2779
+ async function directCouchUrlCall({
2780
+ url,
2781
+ cookie,
2782
+ method,
2783
+ body: body2
2784
+ }) {
2785
+ const params2 = {
2786
+ method,
2787
+ headers: {
2788
+ Authorization: cookie
2789
+ }
2811
2790
  };
2812
- let opts = redisOpts;
2813
- if (environment_default.REDIS_CLUSTERED) {
2814
- opts = {
2815
- connectTimeout: CONNECT_TIMEOUT_MS,
2816
- redisOptions: {
2817
- ...redisOpts,
2818
- tls: {}
2819
- },
2820
- slotsRefreshTimeout: SLOT_REFRESH_MS,
2821
- dnsLookup: (address, callback) => callback(null, address)
2822
- };
2823
- }
2824
- return opts;
2825
- }
2826
- function addDbPrefix(db, key) {
2827
- if (key.includes(db)) {
2828
- return key;
2791
+ if (body2 && method !== "GET") {
2792
+ params2.body = JSON.stringify(body2);
2793
+ params2.headers["Content-Type"] = "application/json";
2829
2794
  }
2830
- return `${db}${SEPARATOR2}${key}`;
2795
+ return await (0, import_node_fetch.default)(checkSlashesInUrl(encodeURI(url)), params2);
2831
2796
  }
2832
- function removeDbPrefix(key) {
2833
- let parts = key.split(SEPARATOR2);
2834
- if (parts.length >= 2) {
2835
- parts.shift();
2836
- return parts.join(SEPARATOR2);
2797
+ async function directCouchQuery(path2, method = "GET", body2) {
2798
+ const response = await directCouchCall(path2, method, body2);
2799
+ if (response.status < 300) {
2800
+ return await response.json();
2837
2801
  } else {
2838
- return parts[0];
2802
+ throw "Cannot connect to CouchDB instance";
2839
2803
  }
2840
2804
  }
2841
- var SLOT_REFRESH_MS, CONNECT_TIMEOUT_MS, SEPARATOR2, Databases, SelectableDatabase;
2805
+ var import_node_fetch;
2842
2806
  var init_utils2 = __esm({
2843
- "src/redis/utils.ts"() {
2807
+ "src/db/couch/utils.ts"() {
2844
2808
  "use strict";
2845
- init_environment2();
2846
- SLOT_REFRESH_MS = 2e3;
2847
- CONNECT_TIMEOUT_MS = 1e4;
2848
- SEPARATOR2 = "-";
2849
- Databases = /* @__PURE__ */ ((Databases2) => {
2850
- Databases2["PW_RESETS"] = "pwReset";
2851
- Databases2["VERIFICATIONS"] = "verification";
2852
- Databases2["INVITATIONS"] = "invitation";
2853
- Databases2["DEV_LOCKS"] = "devLocks";
2854
- Databases2["DEBOUNCE"] = "debounce";
2855
- Databases2["SESSIONS"] = "session";
2856
- Databases2["USER_CACHE"] = "users";
2857
- Databases2["FLAGS"] = "flags";
2858
- Databases2["APP_METADATA"] = "appMetadata";
2859
- Databases2["QUERY_VARS"] = "queryVars";
2860
- Databases2["LICENSES"] = "license";
2861
- Databases2["GENERIC_CACHE"] = "data_cache";
2862
- Databases2["WRITE_THROUGH"] = "writeThrough";
2863
- Databases2["LOCKS"] = "locks";
2864
- Databases2["SOCKET_IO"] = "socket_io";
2865
- return Databases2;
2866
- })(Databases || {});
2867
- SelectableDatabase = /* @__PURE__ */ ((SelectableDatabase2) => {
2868
- SelectableDatabase2[SelectableDatabase2["DEFAULT"] = 0] = "DEFAULT";
2869
- SelectableDatabase2[SelectableDatabase2["SOCKET_IO"] = 1] = "SOCKET_IO";
2870
- SelectableDatabase2[SelectableDatabase2["RATE_LIMITING"] = 2] = "RATE_LIMITING";
2871
- SelectableDatabase2[SelectableDatabase2["UNUSED_2"] = 3] = "UNUSED_2";
2872
- SelectableDatabase2[SelectableDatabase2["UNUSED_3"] = 4] = "UNUSED_3";
2873
- SelectableDatabase2[SelectableDatabase2["UNUSED_4"] = 5] = "UNUSED_4";
2874
- SelectableDatabase2[SelectableDatabase2["UNUSED_5"] = 6] = "UNUSED_5";
2875
- SelectableDatabase2[SelectableDatabase2["UNUSED_6"] = 7] = "UNUSED_6";
2876
- SelectableDatabase2[SelectableDatabase2["UNUSED_7"] = 8] = "UNUSED_7";
2877
- SelectableDatabase2[SelectableDatabase2["UNUSED_8"] = 9] = "UNUSED_8";
2878
- SelectableDatabase2[SelectableDatabase2["UNUSED_9"] = 10] = "UNUSED_9";
2879
- SelectableDatabase2[SelectableDatabase2["UNUSED_10"] = 11] = "UNUSED_10";
2880
- SelectableDatabase2[SelectableDatabase2["UNUSED_11"] = 12] = "UNUSED_11";
2881
- SelectableDatabase2[SelectableDatabase2["UNUSED_12"] = 13] = "UNUSED_12";
2882
- SelectableDatabase2[SelectableDatabase2["UNUSED_13"] = 14] = "UNUSED_13";
2883
- SelectableDatabase2[SelectableDatabase2["UNUSED_14"] = 15] = "UNUSED_14";
2884
- return SelectableDatabase2;
2885
- })(SelectableDatabase || {});
2809
+ init_connections();
2810
+ import_node_fetch = __toESM(require("node-fetch"));
2811
+ init_helpers3();
2886
2812
  }
2887
2813
  });
2888
2814
 
2889
- // src/timers/timers.ts
2890
- function set(callback, period) {
2891
- const interval = setInterval(callback, period);
2892
- intervals.push(interval);
2893
- return interval;
2815
+ // src/db/couch/pouchDB.ts
2816
+ function init(opts) {
2817
+ Pouch = getPouch(opts);
2818
+ initialised = true;
2894
2819
  }
2895
- function clear(interval) {
2896
- const idx = intervals.indexOf(interval);
2897
- if (idx !== -1) {
2898
- intervals.splice(idx, 1);
2899
- }
2900
- clearInterval(interval);
2820
+ function getPouchDB(dbName, opts) {
2821
+ checkInitialised();
2822
+ const db = new Pouch(dbName, opts);
2823
+ const dbPut = db.put;
2824
+ db.put = async (doc, options2 = {}) => {
2825
+ if (!doc.createdAt) {
2826
+ doc.createdAt = (/* @__PURE__ */ new Date()).toISOString();
2827
+ }
2828
+ doc.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2829
+ return dbPut(doc, options2);
2830
+ };
2831
+ db.exists = async () => {
2832
+ const info = await db.info();
2833
+ return !info.error;
2834
+ };
2835
+ return db;
2901
2836
  }
2902
- function cleanup() {
2903
- for (let interval of intervals) {
2904
- clearInterval(interval);
2837
+ async function closePouchDB(db) {
2838
+ if (!db || environment_default.isTest()) {
2839
+ return;
2840
+ }
2841
+ try {
2842
+ return await db.close();
2843
+ } catch (err) {
2905
2844
  }
2906
- intervals = [];
2907
2845
  }
2908
- var intervals;
2909
- var init_timers = __esm({
2910
- "src/timers/timers.ts"() {
2846
+ var import_pouchdb, Pouch, initialised, getPouch, checkInitialised;
2847
+ var init_pouchDB = __esm({
2848
+ "src/db/couch/pouchDB.ts"() {
2911
2849
  "use strict";
2912
- intervals = [];
2850
+ import_pouchdb = __toESM(require("pouchdb"));
2851
+ init_environment2();
2852
+ init_connections();
2853
+ initialised = false;
2854
+ getPouch = (opts = {}) => {
2855
+ let { url, cookie } = getCouchInfo();
2856
+ let POUCH_DB_DEFAULTS = {
2857
+ prefix: url,
2858
+ fetch: (url2, opts2) => {
2859
+ opts2.headers.set("Authorization", cookie);
2860
+ return import_pouchdb.default.fetch(url2, opts2);
2861
+ }
2862
+ };
2863
+ if (opts.inMemory) {
2864
+ const inMemory = require("pouchdb-adapter-memory");
2865
+ import_pouchdb.default.plugin(inMemory);
2866
+ POUCH_DB_DEFAULTS = {
2867
+ // @ts-ignore
2868
+ adapter: "memory"
2869
+ };
2870
+ }
2871
+ if (opts.onDisk) {
2872
+ POUCH_DB_DEFAULTS = {
2873
+ // @ts-ignore
2874
+ adapter: "leveldb"
2875
+ };
2876
+ }
2877
+ if (opts.replication) {
2878
+ const replicationStream = require("@budibase/pouchdb-replication-stream");
2879
+ import_pouchdb.default.plugin(replicationStream.plugin);
2880
+ import_pouchdb.default.adapter("writableStream", replicationStream.adapters.writableStream);
2881
+ }
2882
+ if (opts.find) {
2883
+ const find2 = require("pouchdb-find");
2884
+ import_pouchdb.default.plugin(find2);
2885
+ }
2886
+ return import_pouchdb.default.defaults(POUCH_DB_DEFAULTS);
2887
+ };
2888
+ checkInitialised = () => {
2889
+ if (!initialised) {
2890
+ throw new Error("init has not been called");
2891
+ }
2892
+ };
2913
2893
  }
2914
2894
  });
2915
2895
 
2916
- // src/timers/index.ts
2917
- var timers_exports = {};
2918
- __export(timers_exports, {
2919
- cleanup: () => cleanup,
2920
- clear: () => clear,
2921
- set: () => set
2922
- });
2923
- var init_timers2 = __esm({
2924
- "src/timers/index.ts"() {
2896
+ // src/docIds/newid.ts
2897
+ function newid() {
2898
+ return (0, import_uuid.v4)().replace(/-/g, "");
2899
+ }
2900
+ var import_uuid;
2901
+ var init_newid = __esm({
2902
+ "src/docIds/newid.ts"() {
2925
2903
  "use strict";
2926
- init_timers();
2904
+ import_uuid = require("uuid");
2927
2905
  }
2928
2906
  });
2929
2907
 
2930
- // src/redis/redis.ts
2931
- function pickClient(selectDb) {
2932
- return CLIENTS[selectDb];
2933
- }
2934
- function connectionError(selectDb, timeout2, err) {
2935
- if (CLOSED) {
2936
- return;
2937
- }
2938
- pickClient(selectDb).disconnect();
2939
- CLOSED = true;
2940
- clearTimeout(timeout2);
2941
- CONNECTED = false;
2942
- console.error("Redis connection failed - " + err);
2943
- setTimeout(() => {
2944
- init2();
2945
- }, RETRY_PERIOD_MS);
2908
+ // src/db/couch/DatabaseImpl.ts
2909
+ function buildNano(couchInfo) {
2910
+ return (0, import_nano.default)({
2911
+ url: couchInfo.url,
2912
+ requestDefaults: {
2913
+ headers: {
2914
+ Authorization: couchInfo.cookie
2915
+ }
2916
+ },
2917
+ parseUrl: false
2918
+ });
2946
2919
  }
2947
- function init2(selectDb = DEFAULT_SELECT_DB) {
2948
- const RedisCore = environment_default.MOCK_REDIS && MockRedis ? MockRedis : import_ioredis.default;
2949
- let timeout2;
2950
- CLOSED = false;
2951
- let client = pickClient(selectDb);
2952
- if (client && CONNECTED) {
2953
- return;
2954
- }
2955
- if (environment_default.MOCK_REDIS) {
2956
- CLIENTS[selectDb] = new RedisCore(getRedisOptions());
2957
- }
2958
- timeout2 = setTimeout(() => {
2959
- if (!CONNECTED) {
2960
- connectionError(
2961
- selectDb,
2962
- timeout2,
2963
- "Did not successfully connect in timeout"
2964
- );
2965
- }
2966
- }, STARTUP_TIMEOUT_MS);
2967
- if (client) {
2968
- client.disconnect();
2969
- }
2970
- const { host, port } = getRedisConnectionDetails();
2971
- const opts = getRedisOptions();
2972
- if (CLUSTERED) {
2973
- client = new RedisCore.Cluster([{ host, port }], opts);
2974
- } else {
2975
- client = new RedisCore(opts);
2920
+ function DatabaseWithConnection(dbName, connection, opts) {
2921
+ if (!connection) {
2922
+ throw new Error("Must provide connection details");
2976
2923
  }
2977
- client.on("end", (err) => {
2978
- if (environment_default.isTest()) {
2979
- return;
2980
- }
2981
- connectionError(selectDb, timeout2, err);
2982
- });
2983
- client.on("error", (err) => {
2984
- connectionError(selectDb, timeout2, err);
2985
- });
2986
- client.on("connect", () => {
2987
- clearTimeout(timeout2);
2988
- CONNECTED = true;
2989
- });
2990
- CLIENTS[selectDb] = client;
2924
+ return new DatabaseImpl(dbName, opts, connection);
2991
2925
  }
2992
- function waitForConnection(selectDb = DEFAULT_SELECT_DB) {
2993
- return new Promise((resolve) => {
2994
- if (pickClient(selectDb) == null) {
2995
- init2();
2996
- } else if (CONNECTED) {
2997
- resolve("");
2998
- return;
2999
- }
3000
- const interval = set(() => {
3001
- if (CONNECTED) {
3002
- clear(interval);
3003
- resolve("");
2926
+ var import_nano, DatabaseImpl;
2927
+ var init_DatabaseImpl = __esm({
2928
+ "src/db/couch/DatabaseImpl.ts"() {
2929
+ "use strict";
2930
+ import_nano = __toESM(require("@budibase/nano"));
2931
+ init_src();
2932
+ init_connections();
2933
+ init_utils2();
2934
+ init_pouchDB();
2935
+ init_newid();
2936
+ DatabaseImpl = class _DatabaseImpl {
2937
+ constructor(dbName, opts, connection) {
2938
+ this.couchInfo = getCouchInfo();
2939
+ this.name = dbName;
2940
+ this.pouchOpts = opts || {};
2941
+ if (connection) {
2942
+ this.couchInfo = getCouchInfo(connection);
2943
+ this.instanceNano = buildNano(this.couchInfo);
2944
+ }
2945
+ if (!_DatabaseImpl.nano) {
2946
+ _DatabaseImpl.init();
2947
+ }
3004
2948
  }
3005
- }, 500);
3006
- });
3007
- }
3008
- function promisifyStream(stream2, client) {
3009
- return new Promise((resolve, reject) => {
3010
- const outputKeys = /* @__PURE__ */ new Set();
3011
- stream2.on("data", (keys2) => {
3012
- keys2.forEach((key) => {
3013
- outputKeys.add(key);
3014
- });
3015
- });
3016
- stream2.on("error", (err) => {
3017
- reject(err);
3018
- });
3019
- stream2.on("end", async () => {
3020
- const keysArray = Array.from(outputKeys);
3021
- try {
3022
- let getPromises = [];
3023
- for (let key of keysArray) {
3024
- getPromises.push(client.get(key));
3025
- }
3026
- const jsonArray = await Promise.all(getPromises);
3027
- resolve(
3028
- keysArray.map((key) => ({
3029
- key: removeDbPrefix(key),
3030
- value: JSON.parse(jsonArray.shift())
3031
- }))
3032
- );
3033
- } catch (err) {
3034
- reject(err);
3035
- }
3036
- });
3037
- });
3038
- }
3039
- var import_ioredis, MockRedis, RETRY_PERIOD_MS, STARTUP_TIMEOUT_MS, CLUSTERED, DEFAULT_SELECT_DB, CLOSED, CLIENTS, CONNECTED, RedisWrapper, redis_default;
3040
- var init_redis = __esm({
3041
- "src/redis/redis.ts"() {
3042
- "use strict";
3043
- init_environment2();
3044
- import_ioredis = __toESM(require("ioredis"));
3045
- init_utils2();
3046
- init_timers2();
3047
- if (environment_default.MOCK_REDIS) {
3048
- try {
3049
- MockRedis = require("ioredis-mock");
3050
- } catch (err) {
3051
- console.log("Mock redis unavailable");
2949
+ static init() {
2950
+ const couchInfo = getCouchInfo();
2951
+ _DatabaseImpl.nano = buildNano(couchInfo);
3052
2952
  }
3053
- }
3054
- RETRY_PERIOD_MS = 2e3;
3055
- STARTUP_TIMEOUT_MS = 5e3;
3056
- CLUSTERED = environment_default.REDIS_CLUSTERED;
3057
- DEFAULT_SELECT_DB = 0 /* DEFAULT */;
3058
- CLOSED = false;
3059
- CLIENTS = {};
3060
- CONNECTED = false;
3061
- if (environment_default.MOCK_REDIS) {
3062
- CONNECTED = true;
3063
- }
3064
- RedisWrapper = class {
3065
- constructor(db, selectDb = null) {
3066
- this._db = db;
3067
- this._select = selectDb || DEFAULT_SELECT_DB;
2953
+ async exists() {
2954
+ const response = await directCouchUrlCall({
2955
+ url: `${this.couchInfo.url}/${this.name}`,
2956
+ method: "HEAD",
2957
+ cookie: this.couchInfo.cookie
2958
+ });
2959
+ return response.status === 200;
3068
2960
  }
3069
- getClient() {
3070
- return pickClient(this._select);
2961
+ nano() {
2962
+ return this.instanceNano || _DatabaseImpl.nano;
3071
2963
  }
3072
- async init() {
3073
- CLOSED = false;
3074
- init2(this._select);
3075
- await waitForConnection(this._select);
3076
- if (this._select && !environment_default.isTest()) {
3077
- this.getClient().select(this._select);
2964
+ async checkSetup() {
2965
+ let shouldCreate = !this.pouchOpts?.skip_setup;
2966
+ let exists2 = await this.exists();
2967
+ if (!shouldCreate && !exists2) {
2968
+ throw new Error("DB does not exist");
3078
2969
  }
3079
- return this;
3080
- }
3081
- async finish() {
3082
- CLOSED = true;
3083
- this.getClient().disconnect();
3084
- }
3085
- async scan(key = "") {
3086
- const db = this._db;
3087
- key = `${db}${SEPARATOR2}${key}`;
3088
- let stream2;
3089
- if (CLUSTERED) {
3090
- let node = this.getClient().nodes("master");
3091
- stream2 = node[0].scanStream({ match: key + "*", count: 100 });
3092
- } else {
3093
- stream2 = this.getClient().scanStream({ match: key + "*", count: 100 });
2970
+ if (!exists2) {
2971
+ try {
2972
+ await this.nano().db.create(this.name);
2973
+ } catch (err) {
2974
+ if (err.statusCode !== 412) {
2975
+ throw err;
2976
+ }
2977
+ }
3094
2978
  }
3095
- return promisifyStream(stream2, this.getClient());
3096
- }
3097
- async keys(pattern) {
3098
- const db = this._db;
3099
- return this.getClient().keys(addDbPrefix(db, pattern));
3100
- }
3101
- async exists(key) {
3102
- const db = this._db;
3103
- return await this.getClient().exists(addDbPrefix(db, key));
2979
+ return this.nano().db.use(this.name);
3104
2980
  }
3105
- async get(key) {
3106
- const db = this._db;
3107
- let response = await this.getClient().get(addDbPrefix(db, key));
3108
- if (response != null && response.key) {
3109
- response.key = key;
3110
- }
2981
+ async updateOutput(fnc) {
3111
2982
  try {
3112
- return JSON.parse(response);
2983
+ return await fnc();
3113
2984
  } catch (err) {
3114
- return response;
2985
+ if (err.statusCode) {
2986
+ err.status = err.statusCode;
2987
+ }
2988
+ throw err;
3115
2989
  }
3116
2990
  }
3117
- async bulkGet(keys2) {
3118
- const db = this._db;
3119
- if (keys2.length === 0) {
3120
- return {};
2991
+ async get(id) {
2992
+ const db = await this.checkSetup();
2993
+ if (!id) {
2994
+ throw new Error("Unable to get doc without a valid _id.");
3121
2995
  }
3122
- const prefixedKeys = keys2.map((key) => addDbPrefix(db, key));
3123
- let response = await this.getClient().mget(prefixedKeys);
3124
- if (Array.isArray(response)) {
3125
- let final = {};
3126
- let count = 0;
3127
- for (let result of response) {
3128
- if (result) {
3129
- let parsed;
3130
- try {
3131
- parsed = JSON.parse(result);
3132
- } catch (err) {
3133
- parsed = result;
3134
- }
3135
- final[keys2[count]] = parsed;
3136
- }
3137
- count++;
2996
+ return this.updateOutput(() => db.get(id));
2997
+ }
2998
+ async getMultiple(ids, opts) {
2999
+ ids = [...new Set(ids)];
3000
+ const response = await this.allDocs({
3001
+ keys: ids,
3002
+ include_docs: true
3003
+ });
3004
+ const rowUnavailable = (row) => {
3005
+ if (row.doc == null || "deleted" in row.value && row.value.deleted) {
3006
+ return true;
3138
3007
  }
3139
- return final;
3140
- } else {
3141
- throw new Error(`Invalid response: ${response}`);
3008
+ return row.error === "not_found";
3009
+ };
3010
+ const rows = response.rows.filter((row) => !rowUnavailable(row));
3011
+ const someMissing = rows.length !== response.rows.length;
3012
+ if (!opts?.allowMissing && someMissing) {
3013
+ const missing = response.rows.filter((row) => rowUnavailable(row));
3014
+ const missingIds = missing.map((row) => row.key).join(", ");
3015
+ throw new Error(`Unable to get documents: ${missingIds}`);
3142
3016
  }
3017
+ return rows.map((row) => row.doc);
3143
3018
  }
3144
- async store(key, value, expirySeconds = null) {
3145
- const db = this._db;
3146
- if (typeof value === "object") {
3147
- value = JSON.stringify(value);
3019
+ async remove(idOrDoc, rev) {
3020
+ const db = await this.checkSetup();
3021
+ let _id;
3022
+ let _rev;
3023
+ if (isDocument(idOrDoc)) {
3024
+ _id = idOrDoc._id;
3025
+ _rev = idOrDoc._rev;
3026
+ } else {
3027
+ _id = idOrDoc;
3028
+ _rev = rev;
3148
3029
  }
3149
- const prefixedKey = addDbPrefix(db, key);
3150
- await this.getClient().set(prefixedKey, value);
3151
- if (expirySeconds) {
3152
- await this.getClient().expire(prefixedKey, expirySeconds);
3030
+ if (!_id || !_rev) {
3031
+ throw new Error("Unable to remove doc without a valid _id and _rev.");
3153
3032
  }
3033
+ return this.updateOutput(() => db.destroy(_id, _rev));
3154
3034
  }
3155
- async getTTL(key) {
3156
- const db = this._db;
3157
- const prefixedKey = addDbPrefix(db, key);
3158
- return this.getClient().ttl(prefixedKey);
3035
+ async post(document, opts) {
3036
+ if (!document._id) {
3037
+ document._id = newid();
3038
+ }
3039
+ return this.put(document, opts);
3159
3040
  }
3160
- async setExpiry(key, expirySeconds) {
3161
- const db = this._db;
3162
- const prefixedKey = addDbPrefix(db, key);
3163
- await this.getClient().expire(prefixedKey, expirySeconds);
3041
+ async put(document, opts) {
3042
+ if (!document._id) {
3043
+ throw new Error("Cannot store document without _id field.");
3044
+ }
3045
+ const db = await this.checkSetup();
3046
+ if (!document.createdAt) {
3047
+ document.createdAt = (/* @__PURE__ */ new Date()).toISOString();
3048
+ }
3049
+ document.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3050
+ if (opts?.force && document._id) {
3051
+ try {
3052
+ const existing = await this.get(document._id);
3053
+ if (existing) {
3054
+ document._rev = existing._rev;
3055
+ }
3056
+ } catch (err) {
3057
+ if (err.status !== 404) {
3058
+ throw err;
3059
+ }
3060
+ }
3061
+ }
3062
+ return this.updateOutput(() => db.insert(document));
3164
3063
  }
3165
- async delete(key) {
3166
- const db = this._db;
3167
- await this.getClient().del(addDbPrefix(db, key));
3064
+ async bulkDocs(documents) {
3065
+ const db = await this.checkSetup();
3066
+ return this.updateOutput(() => db.bulk({ docs: documents }));
3168
3067
  }
3169
- async clear() {
3170
- let items = await this.scan();
3171
- await Promise.all(items.map((obj) => this.delete(obj.key)));
3068
+ async allDocs(params2) {
3069
+ const db = await this.checkSetup();
3070
+ return this.updateOutput(() => db.list(params2));
3172
3071
  }
3173
- };
3174
- redis_default = RedisWrapper;
3175
- }
3176
- });
3177
-
3178
- // src/redis/init.ts
3179
- var init_exports = {};
3180
- __export(init_exports, {
3181
- getAppClient: () => getAppClient,
3182
- getCacheClient: () => getCacheClient,
3183
- getInviteClient: () => getInviteClient,
3184
- getLockClient: () => getLockClient,
3185
- getPasswordResetClient: () => getPasswordResetClient,
3186
- getSessionClient: () => getSessionClient,
3187
- getSocketClient: () => getSocketClient,
3188
- getUserClient: () => getUserClient,
3189
- getWritethroughClient: () => getWritethroughClient,
3190
- init: () => init3,
3191
- shutdown: () => shutdown
3072
+ async query(viewName, params2) {
3073
+ const db = await this.checkSetup();
3074
+ const [database, view] = viewName.split("/");
3075
+ return this.updateOutput(() => db.view(database, view, params2));
3076
+ }
3077
+ async destroy() {
3078
+ try {
3079
+ return await this.nano().db.destroy(this.name);
3080
+ } catch (err) {
3081
+ if (err.statusCode === 404) {
3082
+ return;
3083
+ } else {
3084
+ throw { ...err, status: err.statusCode };
3085
+ }
3086
+ }
3087
+ }
3088
+ async compact() {
3089
+ const db = await this.checkSetup();
3090
+ return this.updateOutput(() => db.compact());
3091
+ }
3092
+ // All below functions are in-frequently called, just utilise PouchDB
3093
+ // for them as it implements them better than we can
3094
+ async dump(stream2, opts) {
3095
+ const pouch = getPouchDB(this.name);
3096
+ return pouch.dump(stream2, opts);
3097
+ }
3098
+ async load(stream2) {
3099
+ const pouch = getPouchDB(this.name);
3100
+ return pouch.load(stream2);
3101
+ }
3102
+ async createIndex(opts) {
3103
+ const pouch = getPouchDB(this.name);
3104
+ return pouch.createIndex(opts);
3105
+ }
3106
+ async deleteIndex(opts) {
3107
+ const pouch = getPouchDB(this.name);
3108
+ return pouch.deleteIndex(opts);
3109
+ }
3110
+ async getIndexes() {
3111
+ const pouch = getPouchDB(this.name);
3112
+ return pouch.getIndexes();
3113
+ }
3114
+ };
3115
+ }
3192
3116
  });
3193
- async function init3() {
3194
- userClient = await new redis_default("users" /* USER_CACHE */).init();
3195
- sessionClient = await new redis_default("session" /* SESSIONS */).init();
3196
- appClient = await new redis_default("appMetadata" /* APP_METADATA */).init();
3197
- cacheClient = await new redis_default("data_cache" /* GENERIC_CACHE */).init();
3198
- lockClient = await new redis_default("locks" /* LOCKS */).init();
3199
- writethroughClient = await new redis_default("writeThrough" /* WRITE_THROUGH */).init();
3200
- inviteClient = await new redis_default("invitation" /* INVITATIONS */).init();
3201
- passwordResetClient = await new redis_default("pwReset" /* PW_RESETS */).init();
3202
- socketClient = await new redis_default(
3203
- "socket_io" /* SOCKET_IO */,
3204
- 1 /* SOCKET_IO */
3205
- ).init();
3206
- }
3207
- async function shutdown() {
3208
- if (userClient)
3209
- await userClient.finish();
3210
- if (sessionClient)
3211
- await sessionClient.finish();
3212
- if (appClient)
3213
- await appClient.finish();
3214
- if (cacheClient)
3215
- await cacheClient.finish();
3216
- if (writethroughClient)
3217
- await writethroughClient.finish();
3218
- if (lockClient)
3219
- await lockClient.finish();
3220
- if (inviteClient)
3221
- await inviteClient.finish();
3222
- if (passwordResetClient)
3223
- await passwordResetClient.finish();
3224
- if (socketClient)
3225
- await socketClient.finish();
3117
+
3118
+ // src/db/constants.ts
3119
+ function isInternalColumnName(name) {
3120
+ return CONSTANT_INTERNAL_ROW_COLS.includes(name);
3226
3121
  }
3227
- async function getUserClient() {
3228
- if (!userClient) {
3229
- await init3();
3122
+ var CONSTANT_INTERNAL_ROW_COLS, CONSTANT_EXTERNAL_ROW_COLS;
3123
+ var init_constants5 = __esm({
3124
+ "src/db/constants.ts"() {
3125
+ "use strict";
3126
+ CONSTANT_INTERNAL_ROW_COLS = [
3127
+ "_id",
3128
+ "_rev",
3129
+ "type",
3130
+ "createdAt",
3131
+ "updatedAt",
3132
+ "tableId"
3133
+ ];
3134
+ CONSTANT_EXTERNAL_ROW_COLS = ["_id", "_rev", "tableId"];
3230
3135
  }
3231
- return userClient;
3232
- }
3233
- async function getSessionClient() {
3234
- if (!sessionClient) {
3235
- await init3();
3136
+ });
3137
+
3138
+ // src/db/couch/index.ts
3139
+ var init_couch = __esm({
3140
+ "src/db/couch/index.ts"() {
3141
+ "use strict";
3142
+ init_connections();
3143
+ init_DatabaseImpl();
3144
+ init_utils2();
3145
+ init_pouchDB();
3146
+ init_constants5();
3236
3147
  }
3237
- return sessionClient;
3148
+ });
3149
+
3150
+ // src/db/db.ts
3151
+ function getDB(dbName, opts) {
3152
+ return new DatabaseImpl(dbName, opts);
3238
3153
  }
3239
- async function getAppClient() {
3240
- if (!appClient) {
3241
- await init3();
3242
- }
3243
- return appClient;
3154
+ async function doWithDB(dbName, cb, opts) {
3155
+ const db = getDB(dbName, opts);
3156
+ return await cb(db);
3244
3157
  }
3245
- async function getCacheClient() {
3246
- if (!cacheClient) {
3247
- await init3();
3158
+ async function directCouchAllDbs(queryString) {
3159
+ let couchPath = "/_all_dbs";
3160
+ if (queryString) {
3161
+ couchPath += `?${queryString}`;
3248
3162
  }
3249
- return cacheClient;
3163
+ return await directCouchQuery(couchPath);
3250
3164
  }
3251
- async function getWritethroughClient() {
3252
- if (!writethroughClient) {
3253
- await init3();
3254
- }
3255
- return writethroughClient;
3165
+ async function directCouchFind(dbName, opts) {
3166
+ const json = await directCouchQuery(`${dbName}/_find`, "POST", opts);
3167
+ return { rows: json.docs, bookmark: json.bookmark };
3256
3168
  }
3257
- async function getLockClient() {
3258
- if (!lockClient) {
3259
- await init3();
3169
+ var init_db3 = __esm({
3170
+ "src/db/db.ts"() {
3171
+ "use strict";
3172
+ init_couch();
3260
3173
  }
3261
- return lockClient;
3174
+ });
3175
+
3176
+ // src/context/mainContext.ts
3177
+ function getGlobalDBName(tenantId) {
3178
+ if (!tenantId) {
3179
+ tenantId = getTenantId();
3180
+ }
3181
+ return baseGlobalDBName(tenantId);
3262
3182
  }
3263
- async function getSocketClient() {
3264
- if (!socketClient) {
3265
- await init3();
3183
+ function getAuditLogDBName(tenantId) {
3184
+ if (!tenantId) {
3185
+ tenantId = getTenantId();
3186
+ }
3187
+ if (tenantId === DEFAULT_TENANT_ID) {
3188
+ return StaticDatabases.AUDIT_LOGS.name;
3189
+ } else {
3190
+ return `${tenantId}${SEPARATOR}${StaticDatabases.AUDIT_LOGS.name}`;
3266
3191
  }
3267
- return socketClient;
3268
3192
  }
3269
- async function getInviteClient() {
3270
- if (!inviteClient) {
3271
- await init3();
3193
+ function baseGlobalDBName(tenantId) {
3194
+ if (!tenantId || tenantId === DEFAULT_TENANT_ID) {
3195
+ return StaticDatabases.GLOBAL.name;
3196
+ } else {
3197
+ return `${tenantId}${SEPARATOR}${StaticDatabases.GLOBAL.name}`;
3272
3198
  }
3273
- return inviteClient;
3274
3199
  }
3275
- async function getPasswordResetClient() {
3276
- if (!passwordResetClient) {
3277
- await init3();
3200
+ function getPlatformURL() {
3201
+ return environment_default.PLATFORM_URL;
3202
+ }
3203
+ function isMultiTenant() {
3204
+ return !!environment_default.MULTI_TENANCY;
3205
+ }
3206
+ function isTenantIdSet() {
3207
+ const context = Context.get();
3208
+ return !!context?.tenantId;
3209
+ }
3210
+ function isTenancyEnabled() {
3211
+ return environment_default.MULTI_TENANCY;
3212
+ }
3213
+ function getTenantIDFromAppID(appId) {
3214
+ if (!appId) {
3215
+ return void 0;
3216
+ }
3217
+ if (!isMultiTenant()) {
3218
+ return DEFAULT_TENANT_ID;
3219
+ }
3220
+ const split = appId.split(SEPARATOR);
3221
+ const hasDev = split[1] === "dev" /* DEV */;
3222
+ if (hasDev && split.length === 3 || !hasDev && split.length === 2) {
3223
+ return void 0;
3224
+ }
3225
+ if (hasDev) {
3226
+ return split[2];
3227
+ } else {
3228
+ return split[1];
3278
3229
  }
3279
- return passwordResetClient;
3280
3230
  }
3281
- var userClient, sessionClient, appClient, cacheClient, writethroughClient, lockClient, socketClient, inviteClient, passwordResetClient;
3282
- var init_init = __esm({
3283
- "src/redis/init.ts"() {
3284
- "use strict";
3285
- init_redis();
3286
- init_utils2();
3287
- process.on("exit", async () => {
3288
- await shutdown();
3289
- });
3231
+ function updateContext(updates) {
3232
+ let context;
3233
+ try {
3234
+ context = Context.get();
3235
+ } catch (err) {
3236
+ context = {};
3290
3237
  }
3291
- });
3292
-
3293
- // ../../node_modules/dayjs/dayjs.min.js
3294
- var require_dayjs_min = __commonJS({
3295
- "../../node_modules/dayjs/dayjs.min.js"(exports, module2) {
3296
- "use strict";
3297
- !function(t, e) {
3298
- "object" == typeof exports && "undefined" != typeof module2 ? module2.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs = e();
3299
- }(exports, function() {
3300
- "use strict";
3301
- var t = 1e3, e = 6e4, n = 36e5, r = "millisecond", i = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t2) {
3302
- var e2 = ["th", "st", "nd", "rd"], n2 = t2 % 100;
3303
- return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
3304
- } }, m = function(t2, e2, n2) {
3305
- var r2 = String(t2);
3306
- return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
3307
- }, v = { s: m, z: function(t2) {
3308
- var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60;
3309
- return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0");
3310
- }, m: function t2(e2, n2) {
3311
- if (e2.date() < n2.date())
3312
- return -t2(n2, e2);
3313
- var r2 = 12 * (n2.year() - e2.year()) + (n2.month() - e2.month()), i2 = e2.clone().add(r2, c), s2 = n2 - i2 < 0, u2 = e2.clone().add(r2 + (s2 ? -1 : 1), c);
3314
- return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0);
3315
- }, a: function(t2) {
3316
- return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
3317
- }, p: function(t2) {
3318
- return { M: c, y: h, w: o, d: a, D: d, h: u, m: s, s: i, ms: r, Q: f }[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
3319
- }, u: function(t2) {
3320
- return void 0 === t2;
3321
- } }, g = "en", D = {};
3322
- D[g] = M;
3323
- var p = "$isDayjsObject", S = function(t2) {
3324
- return t2 instanceof _2 || !(!t2 || !t2[p]);
3325
- }, w = function t2(e2, n2, r2) {
3326
- var i2;
3327
- if (!e2)
3328
- return g;
3329
- if ("string" == typeof e2) {
3330
- var s2 = e2.toLowerCase();
3331
- D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2);
3332
- var u2 = e2.split("-");
3333
- if (!i2 && u2.length > 1)
3334
- return t2(u2[0]);
3335
- } else {
3336
- var a2 = e2.name;
3337
- D[a2] = e2, i2 = a2;
3238
+ context = {
3239
+ ...context,
3240
+ ...updates
3241
+ };
3242
+ return context;
3243
+ }
3244
+ async function newContext(updates, task) {
3245
+ guardMigration();
3246
+ let context = updateContext(updates);
3247
+ return Context.run(context, task);
3248
+ }
3249
+ async function doInAutomationContext(params2) {
3250
+ const tenantId = getTenantIDFromAppID(params2.appId);
3251
+ return newContext(
3252
+ {
3253
+ tenantId,
3254
+ appId: params2.appId,
3255
+ automationId: params2.automationId
3256
+ },
3257
+ params2.task
3258
+ );
3259
+ }
3260
+ async function doInContext(appId, task) {
3261
+ const tenantId = getTenantIDFromAppID(appId);
3262
+ return newContext(
3263
+ {
3264
+ tenantId,
3265
+ appId
3266
+ },
3267
+ task
3268
+ );
3269
+ }
3270
+ async function doInTenant(tenantId, task) {
3271
+ if (!environment_default.MULTI_TENANCY) {
3272
+ tenantId = tenantId || DEFAULT_TENANT_ID;
3273
+ }
3274
+ const updates = tenantId ? { tenantId } : {};
3275
+ return newContext(updates, task);
3276
+ }
3277
+ async function doInAppContext(appId, task) {
3278
+ return _doInAppContext(appId, task);
3279
+ }
3280
+ async function _doInAppContext(appId, task, extraContextSettings) {
3281
+ if (!appId) {
3282
+ throw new Error("appId is required");
3283
+ }
3284
+ const tenantId = getTenantIDFromAppID(appId);
3285
+ const updates = { appId, ...extraContextSettings };
3286
+ if (tenantId) {
3287
+ updates.tenantId = tenantId;
3288
+ }
3289
+ return newContext(updates, task);
3290
+ }
3291
+ async function doInIdentityContext(identity, task) {
3292
+ if (!identity) {
3293
+ throw new Error("identity is required");
3294
+ }
3295
+ const context = {
3296
+ identity
3297
+ };
3298
+ if (identity.tenantId) {
3299
+ context.tenantId = identity.tenantId;
3300
+ }
3301
+ return newContext(context, task);
3302
+ }
3303
+ function guardMigration() {
3304
+ const context = Context.get();
3305
+ if (context?.isMigrating) {
3306
+ throw new Error(
3307
+ "The context cannot be changed, a migration is currently running"
3308
+ );
3309
+ }
3310
+ }
3311
+ async function doInAppMigrationContext(appId, task) {
3312
+ return _doInAppContext(appId, task, {
3313
+ isMigrating: true
3314
+ });
3315
+ }
3316
+ function getIdentity() {
3317
+ try {
3318
+ const context = Context.get();
3319
+ return context?.identity;
3320
+ } catch (e) {
3321
+ }
3322
+ }
3323
+ function getTenantId() {
3324
+ if (!isMultiTenant()) {
3325
+ return DEFAULT_TENANT_ID;
3326
+ }
3327
+ const context = Context.get();
3328
+ const tenantId = context?.tenantId;
3329
+ if (!tenantId) {
3330
+ throw new Error("Tenant id not found");
3331
+ }
3332
+ return tenantId;
3333
+ }
3334
+ function getAutomationId() {
3335
+ const context = Context.get();
3336
+ return context?.automationId;
3337
+ }
3338
+ function getAppId() {
3339
+ const context = Context.get();
3340
+ const foundId = context?.appId;
3341
+ if (!foundId && environment_default.isTest() && TEST_APP_ID) {
3342
+ return TEST_APP_ID;
3343
+ } else {
3344
+ return foundId;
3345
+ }
3346
+ }
3347
+ function doInEnvironmentContext(values2, task) {
3348
+ if (!values2) {
3349
+ throw new Error("Must supply environment variables.");
3350
+ }
3351
+ const updates = {
3352
+ environmentVariables: values2
3353
+ };
3354
+ return newContext(updates, task);
3355
+ }
3356
+ function doInScimContext(task) {
3357
+ const updates = {
3358
+ isScim: true
3359
+ };
3360
+ return newContext(updates, task);
3361
+ }
3362
+ function getEnvironmentVariables() {
3363
+ const context = Context.get();
3364
+ if (!context.environmentVariables) {
3365
+ return null;
3366
+ } else {
3367
+ return context.environmentVariables;
3368
+ }
3369
+ }
3370
+ function getGlobalDB() {
3371
+ const context = Context.get();
3372
+ if (!context || environment_default.MULTI_TENANCY && !context.tenantId) {
3373
+ throw new Error("Global DB not found");
3374
+ }
3375
+ return getDB(baseGlobalDBName(context?.tenantId));
3376
+ }
3377
+ function getAuditLogsDB() {
3378
+ if (!getTenantId()) {
3379
+ throw new Error("No tenant ID found - cannot open audit log DB");
3380
+ }
3381
+ return getDB(getAuditLogDBName());
3382
+ }
3383
+ function getAppDB(opts) {
3384
+ const appId = getAppId();
3385
+ if (!appId) {
3386
+ throw new Error("Unable to retrieve app DB - no app ID.");
3387
+ }
3388
+ return getDB(appId, opts);
3389
+ }
3390
+ function getProdAppDB(opts) {
3391
+ const appId = getAppId();
3392
+ if (!appId) {
3393
+ throw new Error("Unable to retrieve prod DB - no app ID.");
3394
+ }
3395
+ return getDB(getProdAppID2(appId), opts);
3396
+ }
3397
+ function getDevAppDB(opts) {
3398
+ const appId = getAppId();
3399
+ if (!appId) {
3400
+ throw new Error("Unable to retrieve dev DB - no app ID.");
3401
+ }
3402
+ return getDB(getDevelopmentAppID(appId), opts);
3403
+ }
3404
+ function isScim() {
3405
+ const context = Context.get();
3406
+ const scimCall = context?.isScim;
3407
+ return !!scimCall;
3408
+ }
3409
+ var TEST_APP_ID, getProdAppId;
3410
+ var init_mainContext = __esm({
3411
+ "src/context/mainContext.ts"() {
3412
+ "use strict";
3413
+ init_environment2();
3414
+ init_Context();
3415
+ init_conversions();
3416
+ init_db3();
3417
+ init_constants4();
3418
+ TEST_APP_ID = null;
3419
+ getProdAppId = () => {
3420
+ const appId = getAppId();
3421
+ if (!appId) {
3422
+ throw new Error("Could not get appId");
3423
+ }
3424
+ return getProdAppID2(appId);
3425
+ };
3426
+ }
3427
+ });
3428
+
3429
+ // src/context/index.ts
3430
+ var context_exports = {};
3431
+ __export(context_exports, {
3432
+ DEFAULT_TENANT_ID: () => DEFAULT_TENANT_ID,
3433
+ baseGlobalDBName: () => baseGlobalDBName,
3434
+ doInAppContext: () => doInAppContext,
3435
+ doInAppMigrationContext: () => doInAppMigrationContext,
3436
+ doInAutomationContext: () => doInAutomationContext,
3437
+ doInContext: () => doInContext,
3438
+ doInEnvironmentContext: () => doInEnvironmentContext,
3439
+ doInIdentityContext: () => doInIdentityContext,
3440
+ doInScimContext: () => doInScimContext,
3441
+ doInTenant: () => doInTenant,
3442
+ getAppDB: () => getAppDB,
3443
+ getAppId: () => getAppId,
3444
+ getAuditLogDBName: () => getAuditLogDBName,
3445
+ getAuditLogsDB: () => getAuditLogsDB,
3446
+ getAutomationId: () => getAutomationId,
3447
+ getDevAppDB: () => getDevAppDB,
3448
+ getEnvironmentVariables: () => getEnvironmentVariables,
3449
+ getGlobalDB: () => getGlobalDB,
3450
+ getGlobalDBName: () => getGlobalDBName,
3451
+ getIdentity: () => getIdentity,
3452
+ getPlatformURL: () => getPlatformURL,
3453
+ getProdAppDB: () => getProdAppDB,
3454
+ getProdAppId: () => getProdAppId,
3455
+ getTenantIDFromAppID: () => getTenantIDFromAppID,
3456
+ getTenantId: () => getTenantId,
3457
+ identity: () => identity_exports,
3458
+ isMultiTenant: () => isMultiTenant,
3459
+ isScim: () => isScim,
3460
+ isTenancyEnabled: () => isTenancyEnabled,
3461
+ isTenantIdSet: () => isTenantIdSet
3462
+ });
3463
+ var init_context2 = __esm({
3464
+ "src/context/index.ts"() {
3465
+ "use strict";
3466
+ init_constants4();
3467
+ init_identity();
3468
+ init_mainContext();
3469
+ }
3470
+ });
3471
+
3472
+ // src/redis/utils.ts
3473
+ var utils_exports2 = {};
3474
+ __export(utils_exports2, {
3475
+ Databases: () => Databases,
3476
+ SEPARATOR: () => SEPARATOR2,
3477
+ SelectableDatabase: () => SelectableDatabase,
3478
+ addDbPrefix: () => addDbPrefix,
3479
+ getRedisConnectionDetails: () => getRedisConnectionDetails,
3480
+ getRedisOptions: () => getRedisOptions,
3481
+ removeDbPrefix: () => removeDbPrefix
3482
+ });
3483
+ function getRedisConnectionDetails() {
3484
+ let password = environment_default.REDIS_PASSWORD;
3485
+ let url = environment_default.REDIS_URL.split("//");
3486
+ url = url.length > 1 ? url[1] : url[0];
3487
+ url = url.split("@");
3488
+ if (url.length > 1) {
3489
+ password = url[0].split(":")[1];
3490
+ url = url[1];
3491
+ } else {
3492
+ url = url[0];
3493
+ }
3494
+ const [host, port] = url.split(":");
3495
+ const portNumber = parseInt(port);
3496
+ return {
3497
+ host,
3498
+ password,
3499
+ // assume default port for redis if invalid found
3500
+ port: isNaN(portNumber) ? 6379 : portNumber
3501
+ };
3502
+ }
3503
+ function getRedisOptions() {
3504
+ const { host, password, port } = getRedisConnectionDetails();
3505
+ let redisOpts = {
3506
+ connectTimeout: CONNECT_TIMEOUT_MS,
3507
+ port,
3508
+ host,
3509
+ password
3510
+ };
3511
+ let opts = redisOpts;
3512
+ if (environment_default.REDIS_CLUSTERED) {
3513
+ opts = {
3514
+ connectTimeout: CONNECT_TIMEOUT_MS,
3515
+ redisOptions: {
3516
+ ...redisOpts,
3517
+ tls: {}
3518
+ },
3519
+ slotsRefreshTimeout: SLOT_REFRESH_MS,
3520
+ dnsLookup: (address, callback) => callback(null, address)
3521
+ };
3522
+ }
3523
+ return opts;
3524
+ }
3525
+ function addDbPrefix(db, key) {
3526
+ if (key.includes(db)) {
3527
+ return key;
3528
+ }
3529
+ return `${db}${SEPARATOR2}${key}`;
3530
+ }
3531
+ function removeDbPrefix(key) {
3532
+ let parts = key.split(SEPARATOR2);
3533
+ if (parts.length >= 2) {
3534
+ parts.shift();
3535
+ return parts.join(SEPARATOR2);
3536
+ } else {
3537
+ return parts[0];
3538
+ }
3539
+ }
3540
+ var SLOT_REFRESH_MS, CONNECT_TIMEOUT_MS, SEPARATOR2, Databases, SelectableDatabase;
3541
+ var init_utils3 = __esm({
3542
+ "src/redis/utils.ts"() {
3543
+ "use strict";
3544
+ init_environment2();
3545
+ SLOT_REFRESH_MS = 2e3;
3546
+ CONNECT_TIMEOUT_MS = 1e4;
3547
+ SEPARATOR2 = "-";
3548
+ Databases = /* @__PURE__ */ ((Databases2) => {
3549
+ Databases2["PW_RESETS"] = "pwReset";
3550
+ Databases2["VERIFICATIONS"] = "verification";
3551
+ Databases2["INVITATIONS"] = "invitation";
3552
+ Databases2["DEV_LOCKS"] = "devLocks";
3553
+ Databases2["DEBOUNCE"] = "debounce";
3554
+ Databases2["SESSIONS"] = "session";
3555
+ Databases2["USER_CACHE"] = "users";
3556
+ Databases2["FLAGS"] = "flags";
3557
+ Databases2["APP_METADATA"] = "appMetadata";
3558
+ Databases2["QUERY_VARS"] = "queryVars";
3559
+ Databases2["LICENSES"] = "license";
3560
+ Databases2["GENERIC_CACHE"] = "data_cache";
3561
+ Databases2["WRITE_THROUGH"] = "writeThrough";
3562
+ Databases2["LOCKS"] = "locks";
3563
+ Databases2["SOCKET_IO"] = "socket_io";
3564
+ return Databases2;
3565
+ })(Databases || {});
3566
+ SelectableDatabase = /* @__PURE__ */ ((SelectableDatabase2) => {
3567
+ SelectableDatabase2[SelectableDatabase2["DEFAULT"] = 0] = "DEFAULT";
3568
+ SelectableDatabase2[SelectableDatabase2["SOCKET_IO"] = 1] = "SOCKET_IO";
3569
+ SelectableDatabase2[SelectableDatabase2["RATE_LIMITING"] = 2] = "RATE_LIMITING";
3570
+ SelectableDatabase2[SelectableDatabase2["UNUSED_2"] = 3] = "UNUSED_2";
3571
+ SelectableDatabase2[SelectableDatabase2["UNUSED_3"] = 4] = "UNUSED_3";
3572
+ SelectableDatabase2[SelectableDatabase2["UNUSED_4"] = 5] = "UNUSED_4";
3573
+ SelectableDatabase2[SelectableDatabase2["UNUSED_5"] = 6] = "UNUSED_5";
3574
+ SelectableDatabase2[SelectableDatabase2["UNUSED_6"] = 7] = "UNUSED_6";
3575
+ SelectableDatabase2[SelectableDatabase2["UNUSED_7"] = 8] = "UNUSED_7";
3576
+ SelectableDatabase2[SelectableDatabase2["UNUSED_8"] = 9] = "UNUSED_8";
3577
+ SelectableDatabase2[SelectableDatabase2["UNUSED_9"] = 10] = "UNUSED_9";
3578
+ SelectableDatabase2[SelectableDatabase2["UNUSED_10"] = 11] = "UNUSED_10";
3579
+ SelectableDatabase2[SelectableDatabase2["UNUSED_11"] = 12] = "UNUSED_11";
3580
+ SelectableDatabase2[SelectableDatabase2["UNUSED_12"] = 13] = "UNUSED_12";
3581
+ SelectableDatabase2[SelectableDatabase2["UNUSED_13"] = 14] = "UNUSED_13";
3582
+ SelectableDatabase2[SelectableDatabase2["UNUSED_14"] = 15] = "UNUSED_14";
3583
+ return SelectableDatabase2;
3584
+ })(SelectableDatabase || {});
3585
+ }
3586
+ });
3587
+
3588
+ // src/timers/timers.ts
3589
+ function set(callback, period) {
3590
+ const interval = setInterval(callback, period);
3591
+ intervals.push(interval);
3592
+ return interval;
3593
+ }
3594
+ function clear(interval) {
3595
+ const idx = intervals.indexOf(interval);
3596
+ if (idx !== -1) {
3597
+ intervals.splice(idx, 1);
3598
+ }
3599
+ clearInterval(interval);
3600
+ }
3601
+ function cleanup() {
3602
+ for (let interval of intervals) {
3603
+ clearInterval(interval);
3604
+ }
3605
+ intervals = [];
3606
+ }
3607
+ var intervals;
3608
+ var init_timers = __esm({
3609
+ "src/timers/timers.ts"() {
3610
+ "use strict";
3611
+ intervals = [];
3612
+ }
3613
+ });
3614
+
3615
+ // src/timers/index.ts
3616
+ var timers_exports = {};
3617
+ __export(timers_exports, {
3618
+ cleanup: () => cleanup,
3619
+ clear: () => clear,
3620
+ set: () => set
3621
+ });
3622
+ var init_timers2 = __esm({
3623
+ "src/timers/index.ts"() {
3624
+ "use strict";
3625
+ init_timers();
3626
+ }
3627
+ });
3628
+
3629
+ // src/redis/redis.ts
3630
+ function pickClient(selectDb) {
3631
+ return CLIENTS[selectDb];
3632
+ }
3633
+ function connectionError(selectDb, timeout2, err) {
3634
+ if (CLOSED) {
3635
+ return;
3636
+ }
3637
+ pickClient(selectDb).disconnect();
3638
+ CLOSED = true;
3639
+ clearTimeout(timeout2);
3640
+ CONNECTED = false;
3641
+ console.error("Redis connection failed - " + err);
3642
+ setTimeout(() => {
3643
+ init2();
3644
+ }, RETRY_PERIOD_MS);
3645
+ }
3646
+ function init2(selectDb = DEFAULT_SELECT_DB) {
3647
+ const RedisCore = environment_default.MOCK_REDIS && MockRedis ? MockRedis : import_ioredis.default;
3648
+ let timeout2;
3649
+ CLOSED = false;
3650
+ let client = pickClient(selectDb);
3651
+ if (client && CONNECTED) {
3652
+ return;
3653
+ }
3654
+ if (environment_default.MOCK_REDIS) {
3655
+ CLIENTS[selectDb] = new RedisCore(getRedisOptions());
3656
+ }
3657
+ timeout2 = setTimeout(() => {
3658
+ if (!CONNECTED) {
3659
+ connectionError(
3660
+ selectDb,
3661
+ timeout2,
3662
+ "Did not successfully connect in timeout"
3663
+ );
3664
+ }
3665
+ }, STARTUP_TIMEOUT_MS);
3666
+ if (client) {
3667
+ client.disconnect();
3668
+ }
3669
+ const { host, port } = getRedisConnectionDetails();
3670
+ const opts = getRedisOptions();
3671
+ if (CLUSTERED) {
3672
+ client = new RedisCore.Cluster([{ host, port }], opts);
3673
+ } else {
3674
+ client = new RedisCore(opts);
3675
+ }
3676
+ client.on("end", (err) => {
3677
+ if (environment_default.isTest()) {
3678
+ return;
3679
+ }
3680
+ connectionError(selectDb, timeout2, err);
3681
+ });
3682
+ client.on("error", (err) => {
3683
+ connectionError(selectDb, timeout2, err);
3684
+ });
3685
+ client.on("connect", () => {
3686
+ clearTimeout(timeout2);
3687
+ CONNECTED = true;
3688
+ });
3689
+ CLIENTS[selectDb] = client;
3690
+ }
3691
+ function waitForConnection(selectDb = DEFAULT_SELECT_DB) {
3692
+ return new Promise((resolve) => {
3693
+ if (pickClient(selectDb) == null) {
3694
+ init2();
3695
+ } else if (CONNECTED) {
3696
+ resolve("");
3697
+ return;
3698
+ }
3699
+ const interval = set(() => {
3700
+ if (CONNECTED) {
3701
+ clear(interval);
3702
+ resolve("");
3703
+ }
3704
+ }, 500);
3705
+ });
3706
+ }
3707
+ function promisifyStream(stream2, client) {
3708
+ return new Promise((resolve, reject) => {
3709
+ const outputKeys = /* @__PURE__ */ new Set();
3710
+ stream2.on("data", (keys2) => {
3711
+ keys2.forEach((key) => {
3712
+ outputKeys.add(key);
3713
+ });
3714
+ });
3715
+ stream2.on("error", (err) => {
3716
+ reject(err);
3717
+ });
3718
+ stream2.on("end", async () => {
3719
+ const keysArray = Array.from(outputKeys);
3720
+ try {
3721
+ let getPromises = [];
3722
+ for (let key of keysArray) {
3723
+ getPromises.push(client.get(key));
3338
3724
  }
3339
- return !r2 && i2 && (g = i2), i2 || !r2 && g;
3340
- }, O = function(t2, e2) {
3341
- if (S(t2))
3342
- return t2.clone();
3343
- var n2 = "object" == typeof e2 ? e2 : {};
3344
- return n2.date = t2, n2.args = arguments, new _2(n2);
3345
- }, b = v;
3346
- b.l = w, b.i = S, b.w = function(t2, e2) {
3347
- return O(t2, { locale: e2.$L, utc: e2.$u, x: e2.$x, $offset: e2.$offset });
3348
- };
3349
- var _2 = function() {
3350
- function M2(t2) {
3351
- this.$L = w(t2.locale, null, true), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = true;
3725
+ const jsonArray = await Promise.all(getPromises);
3726
+ resolve(
3727
+ keysArray.map((key) => ({
3728
+ key: removeDbPrefix(key),
3729
+ value: JSON.parse(jsonArray.shift())
3730
+ }))
3731
+ );
3732
+ } catch (err) {
3733
+ reject(err);
3734
+ }
3735
+ });
3736
+ });
3737
+ }
3738
+ var import_ioredis, MockRedis, RETRY_PERIOD_MS, STARTUP_TIMEOUT_MS, CLUSTERED, DEFAULT_SELECT_DB, CLOSED, CLIENTS, CONNECTED, RedisWrapper, redis_default;
3739
+ var init_redis = __esm({
3740
+ "src/redis/redis.ts"() {
3741
+ "use strict";
3742
+ init_environment2();
3743
+ import_ioredis = __toESM(require("ioredis"));
3744
+ init_utils3();
3745
+ init_timers2();
3746
+ if (environment_default.MOCK_REDIS) {
3747
+ try {
3748
+ MockRedis = require("ioredis-mock");
3749
+ } catch (err) {
3750
+ console.log("Mock redis unavailable");
3751
+ }
3752
+ }
3753
+ RETRY_PERIOD_MS = 2e3;
3754
+ STARTUP_TIMEOUT_MS = 5e3;
3755
+ CLUSTERED = environment_default.REDIS_CLUSTERED;
3756
+ DEFAULT_SELECT_DB = 0 /* DEFAULT */;
3757
+ CLOSED = false;
3758
+ CLIENTS = {};
3759
+ CONNECTED = false;
3760
+ if (environment_default.MOCK_REDIS) {
3761
+ CONNECTED = true;
3762
+ }
3763
+ RedisWrapper = class {
3764
+ constructor(db, selectDb = null) {
3765
+ this._db = db;
3766
+ this._select = selectDb || DEFAULT_SELECT_DB;
3767
+ }
3768
+ getClient() {
3769
+ return pickClient(this._select);
3770
+ }
3771
+ async init() {
3772
+ CLOSED = false;
3773
+ init2(this._select);
3774
+ await waitForConnection(this._select);
3775
+ if (this._select && !environment_default.isTest()) {
3776
+ this.getClient().select(this._select);
3352
3777
  }
3353
- var m2 = M2.prototype;
3354
- return m2.parse = function(t2) {
3355
- this.$d = function(t3) {
3356
- var e2 = t3.date, n2 = t3.utc;
3357
- if (null === e2)
3358
- return /* @__PURE__ */ new Date(NaN);
3359
- if (b.u(e2))
3360
- return /* @__PURE__ */ new Date();
3361
- if (e2 instanceof Date)
3362
- return new Date(e2);
3363
- if ("string" == typeof e2 && !/Z$/i.test(e2)) {
3364
- var r2 = e2.match($);
3365
- if (r2) {
3366
- var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
3367
- return n2 ? new Date(Date.UTC(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2)) : new Date(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2);
3368
- }
3369
- }
3370
- return new Date(e2);
3371
- }(t2), this.init();
3372
- }, m2.init = function() {
3373
- var t2 = this.$d;
3374
- this.$y = t2.getFullYear(), this.$M = t2.getMonth(), this.$D = t2.getDate(), this.$W = t2.getDay(), this.$H = t2.getHours(), this.$m = t2.getMinutes(), this.$s = t2.getSeconds(), this.$ms = t2.getMilliseconds();
3375
- }, m2.$utils = function() {
3376
- return b;
3377
- }, m2.isValid = function() {
3378
- return !(this.$d.toString() === l);
3379
- }, m2.isSame = function(t2, e2) {
3380
- var n2 = O(t2);
3381
- return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
3382
- }, m2.isAfter = function(t2, e2) {
3383
- return O(t2) < this.startOf(e2);
3384
- }, m2.isBefore = function(t2, e2) {
3385
- return this.endOf(e2) < O(t2);
3386
- }, m2.$g = function(t2, e2, n2) {
3387
- return b.u(t2) ? this[e2] : this.set(n2, t2);
3388
- }, m2.unix = function() {
3389
- return Math.floor(this.valueOf() / 1e3);
3390
- }, m2.valueOf = function() {
3391
- return this.$d.getTime();
3392
- }, m2.startOf = function(t2, e2) {
3393
- var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
3394
- var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
3395
- return r2 ? i2 : i2.endOf(a);
3396
- }, $2 = function(t3, e3) {
3397
- return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e3)), n2);
3398
- }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
3399
- switch (f2) {
3400
- case h:
3401
- return r2 ? l2(1, 0) : l2(31, 11);
3402
- case c:
3403
- return r2 ? l2(1, M3) : l2(0, M3 + 1);
3404
- case o:
3405
- var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
3406
- return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
3407
- case a:
3408
- case d:
3409
- return $2(v2 + "Hours", 0);
3410
- case u:
3411
- return $2(v2 + "Minutes", 1);
3412
- case s:
3413
- return $2(v2 + "Seconds", 2);
3414
- case i:
3415
- return $2(v2 + "Milliseconds", 3);
3416
- default:
3417
- return this.clone();
3418
- }
3419
- }, m2.endOf = function(t2) {
3420
- return this.startOf(t2, false);
3421
- }, m2.$set = function(t2, e2) {
3422
- var n2, o2 = b.p(t2), f2 = "set" + (this.$u ? "UTC" : ""), l2 = (n2 = {}, n2[a] = f2 + "Date", n2[d] = f2 + "Date", n2[c] = f2 + "Month", n2[h] = f2 + "FullYear", n2[u] = f2 + "Hours", n2[s] = f2 + "Minutes", n2[i] = f2 + "Seconds", n2[r] = f2 + "Milliseconds", n2)[o2], $2 = o2 === a ? this.$D + (e2 - this.$W) : e2;
3423
- if (o2 === c || o2 === h) {
3424
- var y2 = this.clone().set(d, 1);
3425
- y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
3426
- } else
3427
- l2 && this.$d[l2]($2);
3428
- return this.init(), this;
3429
- }, m2.set = function(t2, e2) {
3430
- return this.clone().$set(t2, e2);
3431
- }, m2.get = function(t2) {
3432
- return this[b.p(t2)]();
3433
- }, m2.add = function(r2, f2) {
3434
- var d2, l2 = this;
3435
- r2 = Number(r2);
3436
- var $2 = b.p(f2), y2 = function(t2) {
3437
- var e2 = O(l2);
3438
- return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
3439
- };
3440
- if ($2 === c)
3441
- return this.set(c, this.$M + r2);
3442
- if ($2 === h)
3443
- return this.set(h, this.$y + r2);
3444
- if ($2 === a)
3445
- return y2(1);
3446
- if ($2 === o)
3447
- return y2(7);
3448
- var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
3449
- return b.w(m3, this);
3450
- }, m2.subtract = function(t2, e2) {
3451
- return this.add(-1 * t2, e2);
3452
- }, m2.format = function(t2) {
3453
- var e2 = this, n2 = this.$locale();
3454
- if (!this.isValid())
3455
- return n2.invalidDate || l;
3456
- var r2 = t2 || "YYYY-MM-DDTHH:mm:ssZ", i2 = b.z(this), s2 = this.$H, u2 = this.$m, a2 = this.$M, o2 = n2.weekdays, c2 = n2.months, f2 = n2.meridiem, h2 = function(t3, n3, i3, s3) {
3457
- return t3 && (t3[n3] || t3(e2, r2)) || i3[n3].slice(0, s3);
3458
- }, d2 = function(t3) {
3459
- return b.s(s2 % 12 || 12, t3, "0");
3460
- }, $2 = f2 || function(t3, e3, n3) {
3461
- var r3 = t3 < 12 ? "AM" : "PM";
3462
- return n3 ? r3.toLowerCase() : r3;
3463
- };
3464
- return r2.replace(y, function(t3, r3) {
3465
- return r3 || function(t4) {
3466
- switch (t4) {
3467
- case "YY":
3468
- return String(e2.$y).slice(-2);
3469
- case "YYYY":
3470
- return b.s(e2.$y, 4, "0");
3471
- case "M":
3472
- return a2 + 1;
3473
- case "MM":
3474
- return b.s(a2 + 1, 2, "0");
3475
- case "MMM":
3476
- return h2(n2.monthsShort, a2, c2, 3);
3477
- case "MMMM":
3478
- return h2(c2, a2);
3479
- case "D":
3480
- return e2.$D;
3481
- case "DD":
3482
- return b.s(e2.$D, 2, "0");
3483
- case "d":
3484
- return String(e2.$W);
3485
- case "dd":
3486
- return h2(n2.weekdaysMin, e2.$W, o2, 2);
3487
- case "ddd":
3488
- return h2(n2.weekdaysShort, e2.$W, o2, 3);
3489
- case "dddd":
3490
- return o2[e2.$W];
3491
- case "H":
3492
- return String(s2);
3493
- case "HH":
3494
- return b.s(s2, 2, "0");
3495
- case "h":
3496
- return d2(1);
3497
- case "hh":
3498
- return d2(2);
3499
- case "a":
3500
- return $2(s2, u2, true);
3501
- case "A":
3502
- return $2(s2, u2, false);
3503
- case "m":
3504
- return String(u2);
3505
- case "mm":
3506
- return b.s(u2, 2, "0");
3507
- case "s":
3508
- return String(e2.$s);
3509
- case "ss":
3510
- return b.s(e2.$s, 2, "0");
3511
- case "SSS":
3512
- return b.s(e2.$ms, 3, "0");
3513
- case "Z":
3514
- return i2;
3778
+ return this;
3779
+ }
3780
+ async finish() {
3781
+ CLOSED = true;
3782
+ this.getClient().disconnect();
3783
+ }
3784
+ async scan(key = "") {
3785
+ const db = this._db;
3786
+ key = `${db}${SEPARATOR2}${key}`;
3787
+ let stream2;
3788
+ if (CLUSTERED) {
3789
+ let node = this.getClient().nodes("master");
3790
+ stream2 = node[0].scanStream({ match: key + "*", count: 100 });
3791
+ } else {
3792
+ stream2 = this.getClient().scanStream({ match: key + "*", count: 100 });
3793
+ }
3794
+ return promisifyStream(stream2, this.getClient());
3795
+ }
3796
+ async keys(pattern) {
3797
+ const db = this._db;
3798
+ return this.getClient().keys(addDbPrefix(db, pattern));
3799
+ }
3800
+ async exists(key) {
3801
+ const db = this._db;
3802
+ return await this.getClient().exists(addDbPrefix(db, key));
3803
+ }
3804
+ async get(key) {
3805
+ const db = this._db;
3806
+ let response = await this.getClient().get(addDbPrefix(db, key));
3807
+ if (response != null && response.key) {
3808
+ response.key = key;
3809
+ }
3810
+ try {
3811
+ return JSON.parse(response);
3812
+ } catch (err) {
3813
+ return response;
3814
+ }
3815
+ }
3816
+ async bulkGet(keys2) {
3817
+ const db = this._db;
3818
+ if (keys2.length === 0) {
3819
+ return {};
3820
+ }
3821
+ const prefixedKeys = keys2.map((key) => addDbPrefix(db, key));
3822
+ let response = await this.getClient().mget(prefixedKeys);
3823
+ if (Array.isArray(response)) {
3824
+ let final = {};
3825
+ let count = 0;
3826
+ for (let result of response) {
3827
+ if (result) {
3828
+ let parsed;
3829
+ try {
3830
+ parsed = JSON.parse(result);
3831
+ } catch (err) {
3832
+ parsed = result;
3515
3833
  }
3516
- return null;
3517
- }(t3) || i2.replace(":", "");
3518
- });
3519
- }, m2.utcOffset = function() {
3520
- return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
3521
- }, m2.diff = function(r2, d2, l2) {
3522
- var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
3523
- return b.m(y2, m3);
3524
- };
3525
- switch (M3) {
3526
- case h:
3527
- $2 = D2() / 12;
3528
- break;
3529
- case c:
3530
- $2 = D2();
3531
- break;
3532
- case f:
3533
- $2 = D2() / 3;
3534
- break;
3535
- case o:
3536
- $2 = (g2 - v2) / 6048e5;
3537
- break;
3538
- case a:
3539
- $2 = (g2 - v2) / 864e5;
3540
- break;
3541
- case u:
3542
- $2 = g2 / n;
3543
- break;
3544
- case s:
3545
- $2 = g2 / e;
3546
- break;
3547
- case i:
3548
- $2 = g2 / t;
3549
- break;
3550
- default:
3551
- $2 = g2;
3834
+ final[keys2[count]] = parsed;
3835
+ }
3836
+ count++;
3552
3837
  }
3553
- return l2 ? $2 : b.a($2);
3554
- }, m2.daysInMonth = function() {
3555
- return this.endOf(c).$D;
3556
- }, m2.$locale = function() {
3557
- return D[this.$L];
3558
- }, m2.locale = function(t2, e2) {
3559
- if (!t2)
3560
- return this.$L;
3561
- var n2 = this.clone(), r2 = w(t2, e2, true);
3562
- return r2 && (n2.$L = r2), n2;
3563
- }, m2.clone = function() {
3564
- return b.w(this.$d, this);
3565
- }, m2.toDate = function() {
3566
- return new Date(this.valueOf());
3567
- }, m2.toJSON = function() {
3568
- return this.isValid() ? this.toISOString() : null;
3569
- }, m2.toISOString = function() {
3570
- return this.$d.toISOString();
3571
- }, m2.toString = function() {
3572
- return this.$d.toUTCString();
3573
- }, M2;
3574
- }(), k = _2.prototype;
3575
- return O.prototype = k, [["$ms", r], ["$s", i], ["$m", s], ["$H", u], ["$W", a], ["$M", c], ["$y", h], ["$D", d]].forEach(function(t2) {
3576
- k[t2[1]] = function(e2) {
3577
- return this.$g(e2, t2[0], t2[1]);
3578
- };
3579
- }), O.extend = function(t2, e2) {
3580
- return t2.$i || (t2(e2, _2, O), t2.$i = true), O;
3581
- }, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
3582
- return O(1e3 * t2);
3583
- }, O.en = D[g], O.Ls = D, O.p = {}, O;
3838
+ return final;
3839
+ } else {
3840
+ throw new Error(`Invalid response: ${response}`);
3841
+ }
3842
+ }
3843
+ async store(key, value, expirySeconds = null) {
3844
+ const db = this._db;
3845
+ if (typeof value === "object") {
3846
+ value = JSON.stringify(value);
3847
+ }
3848
+ const prefixedKey = addDbPrefix(db, key);
3849
+ await this.getClient().set(prefixedKey, value);
3850
+ if (expirySeconds) {
3851
+ await this.getClient().expire(prefixedKey, expirySeconds);
3852
+ }
3853
+ }
3854
+ async getTTL(key) {
3855
+ const db = this._db;
3856
+ const prefixedKey = addDbPrefix(db, key);
3857
+ return this.getClient().ttl(prefixedKey);
3858
+ }
3859
+ async setExpiry(key, expirySeconds) {
3860
+ const db = this._db;
3861
+ const prefixedKey = addDbPrefix(db, key);
3862
+ await this.getClient().expire(prefixedKey, expirySeconds);
3863
+ }
3864
+ async delete(key) {
3865
+ const db = this._db;
3866
+ await this.getClient().del(addDbPrefix(db, key));
3867
+ }
3868
+ async clear() {
3869
+ let items = await this.scan();
3870
+ await Promise.all(items.map((obj) => this.delete(obj.key)));
3871
+ }
3872
+ };
3873
+ redis_default = RedisWrapper;
3874
+ }
3875
+ });
3876
+
3877
+ // src/redis/init.ts
3878
+ var init_exports = {};
3879
+ __export(init_exports, {
3880
+ getAppClient: () => getAppClient,
3881
+ getCacheClient: () => getCacheClient,
3882
+ getInviteClient: () => getInviteClient,
3883
+ getLockClient: () => getLockClient,
3884
+ getPasswordResetClient: () => getPasswordResetClient,
3885
+ getSessionClient: () => getSessionClient,
3886
+ getSocketClient: () => getSocketClient,
3887
+ getUserClient: () => getUserClient,
3888
+ getWritethroughClient: () => getWritethroughClient,
3889
+ init: () => init3,
3890
+ shutdown: () => shutdown
3891
+ });
3892
+ async function init3() {
3893
+ userClient = await new redis_default("users" /* USER_CACHE */).init();
3894
+ sessionClient = await new redis_default("session" /* SESSIONS */).init();
3895
+ appClient = await new redis_default("appMetadata" /* APP_METADATA */).init();
3896
+ cacheClient = await new redis_default("data_cache" /* GENERIC_CACHE */).init();
3897
+ lockClient = await new redis_default("locks" /* LOCKS */).init();
3898
+ writethroughClient = await new redis_default("writeThrough" /* WRITE_THROUGH */).init();
3899
+ inviteClient = await new redis_default("invitation" /* INVITATIONS */).init();
3900
+ passwordResetClient = await new redis_default("pwReset" /* PW_RESETS */).init();
3901
+ socketClient = await new redis_default(
3902
+ "socket_io" /* SOCKET_IO */,
3903
+ 1 /* SOCKET_IO */
3904
+ ).init();
3905
+ }
3906
+ async function shutdown() {
3907
+ if (userClient)
3908
+ await userClient.finish();
3909
+ if (sessionClient)
3910
+ await sessionClient.finish();
3911
+ if (appClient)
3912
+ await appClient.finish();
3913
+ if (cacheClient)
3914
+ await cacheClient.finish();
3915
+ if (writethroughClient)
3916
+ await writethroughClient.finish();
3917
+ if (lockClient)
3918
+ await lockClient.finish();
3919
+ if (inviteClient)
3920
+ await inviteClient.finish();
3921
+ if (passwordResetClient)
3922
+ await passwordResetClient.finish();
3923
+ if (socketClient)
3924
+ await socketClient.finish();
3925
+ }
3926
+ async function getUserClient() {
3927
+ if (!userClient) {
3928
+ await init3();
3929
+ }
3930
+ return userClient;
3931
+ }
3932
+ async function getSessionClient() {
3933
+ if (!sessionClient) {
3934
+ await init3();
3935
+ }
3936
+ return sessionClient;
3937
+ }
3938
+ async function getAppClient() {
3939
+ if (!appClient) {
3940
+ await init3();
3941
+ }
3942
+ return appClient;
3943
+ }
3944
+ async function getCacheClient() {
3945
+ if (!cacheClient) {
3946
+ await init3();
3947
+ }
3948
+ return cacheClient;
3949
+ }
3950
+ async function getWritethroughClient() {
3951
+ if (!writethroughClient) {
3952
+ await init3();
3953
+ }
3954
+ return writethroughClient;
3955
+ }
3956
+ async function getLockClient() {
3957
+ if (!lockClient) {
3958
+ await init3();
3959
+ }
3960
+ return lockClient;
3961
+ }
3962
+ async function getSocketClient() {
3963
+ if (!socketClient) {
3964
+ await init3();
3965
+ }
3966
+ return socketClient;
3967
+ }
3968
+ async function getInviteClient() {
3969
+ if (!inviteClient) {
3970
+ await init3();
3971
+ }
3972
+ return inviteClient;
3973
+ }
3974
+ async function getPasswordResetClient() {
3975
+ if (!passwordResetClient) {
3976
+ await init3();
3977
+ }
3978
+ return passwordResetClient;
3979
+ }
3980
+ var userClient, sessionClient, appClient, cacheClient, writethroughClient, lockClient, socketClient, inviteClient, passwordResetClient;
3981
+ var init_init = __esm({
3982
+ "src/redis/init.ts"() {
3983
+ "use strict";
3984
+ init_redis();
3985
+ init_utils3();
3986
+ process.on("exit", async () => {
3987
+ await shutdown();
3584
3988
  });
3585
3989
  }
3586
3990
  });
@@ -3697,7 +4101,7 @@ var generateAppID, isGlobalUserIDRegex, generateDevInfoID, generatePluginID;
3697
4101
  var init_ids = __esm({
3698
4102
  "src/docIds/ids.ts"() {
3699
4103
  "use strict";
3700
- init_constants3();
4104
+ init_constants4();
3701
4105
  init_newid();
3702
4106
  generateAppID = (tenantId) => {
3703
4107
  let id = APP_PREFIX;
@@ -3760,7 +4164,7 @@ function getUserMetadataParams(userId, otherProps = {}) {
3760
4164
  return getRowParams("ta_users" /* USER_METADATA */, userId, otherProps);
3761
4165
  }
3762
4166
  function getUsersByAppParams(appId, otherProps = {}) {
3763
- const prodAppId = getProdAppID(appId);
4167
+ const prodAppId = getProdAppID2(appId);
3764
4168
  return {
3765
4169
  ...otherProps,
3766
4170
  startkey: prodAppId,
@@ -3794,7 +4198,7 @@ var isTableId, isDatasourceId, getPluginParams;
3794
4198
  var init_params = __esm({
3795
4199
  "src/docIds/params.ts"() {
3796
4200
  "use strict";
3797
- init_constants3();
4201
+ init_constants4();
3798
4202
  init_conversions();
3799
4203
  isTableId = (id) => {
3800
4204
  return id && (id.startsWith(`${"ta" /* TABLE */}${SEPARATOR}`) || id.startsWith(`${"datasource_plus" /* DATASOURCE_PLUS */}${SEPARATOR}`));
@@ -3947,7 +4351,7 @@ function isSameAppID(appId1, appId2) {
3947
4351
  if (appId1 == void 0 || appId2 == void 0) {
3948
4352
  return false;
3949
4353
  }
3950
- return getProdAppID(appId1) === getProdAppID(appId2);
4354
+ return getProdAppID2(appId1) === getProdAppID2(appId2);
3951
4355
  }
3952
4356
  async function dbExists(dbName) {
3953
4357
  return doWithDB(
@@ -3983,11 +4387,11 @@ function pagination(data, pageSize, {
3983
4387
  nextPage
3984
4388
  };
3985
4389
  }
3986
- var init_utils3 = __esm({
4390
+ var init_utils4 = __esm({
3987
4391
  "src/db/utils.ts"() {
3988
4392
  "use strict";
3989
4393
  init_environment2();
3990
- init_constants3();
4394
+ init_constants4();
3991
4395
  init_context2();
3992
4396
  init_db3();
3993
4397
  init_appMetadata();
@@ -4082,7 +4486,7 @@ var DESIGN_DB, createNewUserEmailView, createUserAppView, createApiKeyView, quer
4082
4486
  var init_views = __esm({
4083
4487
  "src/db/views.ts"() {
4084
4488
  "use strict";
4085
- init_constants3();
4489
+ init_constants4();
4086
4490
  init_context2();
4087
4491
  init_db4();
4088
4492
  init_environment2();
@@ -4178,7 +4582,7 @@ var init_Replication = __esm({
4178
4582
  "src/db/Replication.ts"() {
4179
4583
  "use strict";
4180
4584
  init_couch();
4181
- init_constants3();
4585
+ init_constants4();
4182
4586
  Replication = class {
4183
4587
  /**
4184
4588
  *
@@ -4951,7 +5355,7 @@ __export(db_exports, {
4951
5355
  getAppsByIDs: () => getAppsByIDs,
4952
5356
  getCouchInfo: () => getCouchInfo,
4953
5357
  getDB: () => getDB,
4954
- getDevAppID: () => getDevAppID,
5358
+ getDevAppID: () => getDevAppID2,
4955
5359
  getDevAppIDs: () => getDevAppIDs,
4956
5360
  getDevelopmentAppID: () => getDevelopmentAppID,
4957
5361
  getDocParams: () => getDocParams,
@@ -4961,7 +5365,7 @@ __export(db_exports, {
4961
5365
  getPluginParams: () => getPluginParams,
4962
5366
  getPouch: () => getPouch,
4963
5367
  getPouchDB: () => getPouchDB,
4964
- getProdAppID: () => getProdAppID,
5368
+ getProdAppID: () => getProdAppID2,
4965
5369
  getProdAppIDs: () => getProdAppIDs,
4966
5370
  getQueryIndex: () => getQueryIndex,
4967
5371
  getRoleParams: () => getRoleParams,
@@ -4998,7 +5402,7 @@ var init_db4 = __esm({
4998
5402
  "use strict";
4999
5403
  init_couch();
5000
5404
  init_db3();
5001
- init_utils3();
5405
+ init_utils4();
5002
5406
  init_views();
5003
5407
  init_conversions();
5004
5408
  init_Replication();
@@ -5023,7 +5427,7 @@ var correlator, setHeader;
5023
5427
  var init_correlation = __esm({
5024
5428
  "src/logging/correlation/correlation.ts"() {
5025
5429
  "use strict";
5026
- init_constants3();
5430
+ init_constants4();
5027
5431
  correlator = require("correlation-id");
5028
5432
  setHeader = (headers) => {
5029
5433
  const correlationId = correlator.getId();
@@ -5047,7 +5451,7 @@ function budibaseTempDir() {
5047
5451
  return bbTmp;
5048
5452
  }
5049
5453
  var import_path, import_os, import_fs2, ObjectStoreBuckets, bbTmp;
5050
- var init_utils4 = __esm({
5454
+ var init_utils5 = __esm({
5051
5455
  "src/objectStore/utils.ts"() {
5052
5456
  "use strict";
5053
5457
  import_path = require("path");
@@ -5380,7 +5784,7 @@ var init_objectStore = __esm({
5380
5784
  import_path2 = require("path");
5381
5785
  import_fs3 = __toESM(require("fs"));
5382
5786
  init_environment2();
5383
- init_utils4();
5787
+ init_utils5();
5384
5788
  import_uuid2 = require("uuid");
5385
5789
  init_db4();
5386
5790
  sanitize = require("sanitize-s3-objectkey");
@@ -5638,7 +6042,7 @@ var init_objectStore2 = __esm({
5638
6042
  "src/objectStore/index.ts"() {
5639
6043
  "use strict";
5640
6044
  init_objectStore();
5641
- init_utils4();
6045
+ init_utils5();
5642
6046
  init_buckets();
5643
6047
  }
5644
6048
  });
@@ -5976,7 +6380,7 @@ __export(src_exports, {
5976
6380
  blacklist: () => blacklist_exports,
5977
6381
  cache: () => cache_exports,
5978
6382
  configs: () => configs_exports,
5979
- constants: () => constants_exports,
6383
+ constants: () => constants_exports2,
5980
6384
  context: () => context_exports,
5981
6385
  db: () => db_exports,
5982
6386
  docIds: () => docIds_exports,
@@ -6032,7 +6436,7 @@ __export(configs_exports, {
6032
6436
 
6033
6437
  // src/configs/configs.ts
6034
6438
  init_src();
6035
- init_constants3();
6439
+ init_constants4();
6036
6440
 
6037
6441
  // src/cache/index.ts
6038
6442
  var cache_exports = {};
@@ -6043,7 +6447,7 @@ __export(cache_exports, {
6043
6447
  bustCache: () => bustCache,
6044
6448
  destroy: () => destroy,
6045
6449
  generic: () => generic_exports,
6046
- get: () => get,
6450
+ get: () => get2,
6047
6451
  invite: () => invite_exports,
6048
6452
  keys: () => keys,
6049
6453
  passwordReset: () => passwordReset_exports,
@@ -6060,7 +6464,7 @@ __export(generic_exports, {
6060
6464
  TTL: () => TTL,
6061
6465
  bustCache: () => bustCache,
6062
6466
  destroy: () => destroy,
6063
- get: () => get,
6467
+ get: () => get2,
6064
6468
  keys: () => keys,
6065
6469
  store: () => store,
6066
6470
  withCache: () => withCache
@@ -6158,7 +6562,7 @@ function performExport(funcName) {
6158
6562
  return (...args) => GENERIC[funcName](...args);
6159
6563
  }
6160
6564
  var keys = performExport("keys");
6161
- var get = performExport("get");
6565
+ var get2 = performExport("get");
6162
6566
  var store = performExport("store");
6163
6567
  var destroy = performExport("delete");
6164
6568
  var withCache = performExport("withCache");
@@ -6192,7 +6596,7 @@ function getTenantDB(tenantId) {
6192
6596
  // src/tenancy/tenancy.ts
6193
6597
  init_context2();
6194
6598
  init_src();
6195
- init_constants3();
6599
+ init_constants4();
6196
6600
  function addTenantToUrl(url) {
6197
6601
  const tenantId = getTenantId();
6198
6602
  if (isMultiTenant()) {
@@ -6303,26 +6707,26 @@ var platform_exports = {};
6303
6707
  __export(platform_exports, {
6304
6708
  getPlatformDB: () => getPlatformDB,
6305
6709
  tenants: () => tenants_exports,
6306
- users: () => users_exports
6710
+ users: () => users_exports2
6307
6711
  });
6308
6712
 
6309
6713
  // src/platform/users.ts
6310
- var users_exports = {};
6311
- __export(users_exports, {
6714
+ var users_exports2 = {};
6715
+ __export(users_exports2, {
6312
6716
  addUser: () => addUser,
6313
6717
  lookupTenantId: () => lookupTenantId,
6314
6718
  removeUser: () => removeUser
6315
6719
  });
6316
6720
 
6317
6721
  // src/platform/platformDb.ts
6318
- init_constants3();
6722
+ init_constants4();
6319
6723
  init_db3();
6320
6724
  function getPlatformDB() {
6321
6725
  return getDB(StaticDatabases.PLATFORM_INFO.name);
6322
6726
  }
6323
6727
 
6324
6728
  // src/platform/users.ts
6325
- init_constants3();
6729
+ init_constants4();
6326
6730
  init_environment2();
6327
6731
  async function lookupTenantId(userId) {
6328
6732
  if (!environment_default.MULTI_TENANCY) {
@@ -6407,7 +6811,7 @@ __export(tenants_exports, {
6407
6811
  removeTenant: () => removeTenant,
6408
6812
  tenacyLockOptions: () => tenacyLockOptions
6409
6813
  });
6410
- init_constants3();
6814
+ init_constants4();
6411
6815
  init_src();
6412
6816
 
6413
6817
  // src/redis/redlockImpl.ts
@@ -6421,313 +6825,7 @@ var import_redlock = __toESM(require("redlock"));
6421
6825
  init_init();
6422
6826
  init_src();
6423
6827
  init_context2();
6424
-
6425
- // ../shared-core/src/constants.ts
6426
- var OperatorOptions = {
6427
- Equals: {
6428
- value: "equal",
6429
- label: "Equals"
6430
- },
6431
- NotEquals: {
6432
- value: "notEqual",
6433
- label: "Not equals"
6434
- },
6435
- Empty: {
6436
- value: "empty",
6437
- label: "Is empty"
6438
- },
6439
- NotEmpty: {
6440
- value: "notEmpty",
6441
- label: "Is not empty"
6442
- },
6443
- StartsWith: {
6444
- value: "string",
6445
- label: "Starts with"
6446
- },
6447
- Like: {
6448
- value: "fuzzy",
6449
- label: "Like"
6450
- },
6451
- MoreThan: {
6452
- value: "rangeLow",
6453
- label: "More than or equal to"
6454
- },
6455
- LessThan: {
6456
- value: "rangeHigh",
6457
- label: "Less than or equal to"
6458
- },
6459
- Contains: {
6460
- value: "contains",
6461
- label: "Contains"
6462
- },
6463
- NotContains: {
6464
- value: "notContains",
6465
- label: "Does not contain"
6466
- },
6467
- In: {
6468
- value: "oneOf",
6469
- label: "Is in"
6470
- },
6471
- ContainsAny: {
6472
- value: "containsAny",
6473
- label: "Has any"
6474
- }
6475
- };
6476
-
6477
- // ../shared-core/src/filters.ts
6478
- init_src();
6479
- var import_dayjs = __toESM(require_dayjs_min());
6480
-
6481
- // ../shared-core/src/helpers/integrations.ts
6482
- init_src();
6483
-
6484
- // ../shared-core/src/filters.ts
6485
- var NoEmptyFilterStrings = [
6486
- OperatorOptions.StartsWith.value,
6487
- OperatorOptions.Like.value,
6488
- OperatorOptions.Equals.value,
6489
- OperatorOptions.NotEquals.value,
6490
- OperatorOptions.Contains.value,
6491
- OperatorOptions.NotContains.value
6492
- ];
6493
-
6494
- // ../shared-core/src/utils.ts
6495
- var utils_exports2 = {};
6496
- __export(utils_exports2, {
6497
- filterValueToLabel: () => filterValueToLabel,
6498
- parallelForeach: () => parallelForeach,
6499
- unreachable: () => unreachable
6500
- });
6501
- function unreachable(value, message = `No such case in exhaustive switch: ${value}`) {
6502
- throw new Error(message);
6503
- }
6504
- async function parallelForeach(items, task, maxConcurrency) {
6505
- const promises = [];
6506
- let index2 = 0;
6507
- const processItem = async (item) => {
6508
- try {
6509
- await task(item);
6510
- } finally {
6511
- processNext();
6512
- }
6513
- };
6514
- const processNext = () => {
6515
- if (index2 >= items.length) {
6516
- return;
6517
- }
6518
- const item = items[index2];
6519
- index2++;
6520
- const promise = processItem(item);
6521
- promises.push(promise);
6522
- if (promises.length >= maxConcurrency) {
6523
- Promise.race(promises).then(processNext);
6524
- } else {
6525
- processNext();
6526
- }
6527
- };
6528
- processNext();
6529
- await Promise.all(promises);
6530
- }
6531
- function filterValueToLabel() {
6532
- return Object.keys(OperatorOptions).reduce(
6533
- (acc, key) => {
6534
- const ops = OperatorOptions;
6535
- const op = ops[key];
6536
- acc[op["value"]] = op.label;
6537
- return acc;
6538
- },
6539
- {}
6540
- );
6541
- }
6542
-
6543
- // ../shared-core/src/sdk/index.ts
6544
- var sdk_exports = {};
6545
- __export(sdk_exports, {
6546
- applications: () => applications_exports,
6547
- users: () => users_exports2
6548
- });
6549
-
6550
- // ../shared-core/src/sdk/documents/applications.ts
6551
- var applications_exports = {};
6552
- __export(applications_exports, {
6553
- getDevAppID: () => getDevAppID2,
6554
- getProdAppID: () => getProdAppID2
6555
- });
6556
- init_src();
6557
- var APP_PREFIX2 = prefixed("app" /* APP */);
6558
- var APP_DEV_PREFIX2 = prefixed("app_dev" /* APP_DEV */);
6559
- function getDevAppID2(appId) {
6560
- if (!appId) {
6561
- throw new Error("No app ID provided");
6562
- }
6563
- if (appId.startsWith(APP_DEV_PREFIX2)) {
6564
- return appId;
6565
- }
6566
- const split = appId.split(APP_PREFIX2);
6567
- split.shift();
6568
- const rest = split.join(APP_PREFIX2);
6569
- return `${APP_DEV_PREFIX2}${rest}`;
6570
- }
6571
- function getProdAppID2(appId) {
6572
- if (!appId) {
6573
- throw new Error("No app ID provided");
6574
- }
6575
- if (!appId.startsWith(APP_DEV_PREFIX2)) {
6576
- return appId;
6577
- }
6578
- const split = appId.split(APP_DEV_PREFIX2);
6579
- split.shift();
6580
- const rest = split.join(APP_DEV_PREFIX2);
6581
- return `${APP_PREFIX2}${rest}`;
6582
- }
6583
-
6584
- // ../shared-core/src/sdk/documents/users.ts
6585
- var users_exports2 = {};
6586
- __export(users_exports2, {
6587
- canCreateApps: () => canCreateApps,
6588
- containsUserID: () => containsUserID,
6589
- getGlobalUserID: () => getGlobalUserID,
6590
- hasAdminPermissions: () => hasAdminPermissions,
6591
- hasAppBuilderPermissions: () => hasAppBuilderPermissions,
6592
- hasAppCreatorPermissions: () => hasAppCreatorPermissions,
6593
- hasBuilderPermissions: () => hasBuilderPermissions,
6594
- hasCreatorPermissions: () => hasCreatorPermissions,
6595
- isAdmin: () => isAdmin,
6596
- isAdminOrBuilder: () => isAdminOrBuilder,
6597
- isAdminOrGlobalBuilder: () => isAdminOrGlobalBuilder,
6598
- isBuilder: () => isBuilder,
6599
- isCreator: () => isCreator,
6600
- isGlobalBuilder: () => isGlobalBuilder
6601
- });
6602
- init_src();
6603
- var _ = __toESM(require("lodash/fp"));
6604
- function isBuilder(user, appId) {
6605
- if (!user) {
6606
- return false;
6607
- }
6608
- if (user.builder?.global) {
6609
- return true;
6610
- } else if (appId && user.builder?.apps?.includes(getProdAppID2(appId))) {
6611
- return true;
6612
- }
6613
- return false;
6614
- }
6615
- function isGlobalBuilder(user) {
6616
- return isBuilder(user) && !hasAppBuilderPermissions(user) || isAdmin(user);
6617
- }
6618
- function canCreateApps(user) {
6619
- return isGlobalBuilder(user) || hasCreatorPermissions(user);
6620
- }
6621
- function isAdmin(user) {
6622
- if (!user) {
6623
- return false;
6624
- }
6625
- return hasAdminPermissions(user);
6626
- }
6627
- function isAdminOrBuilder(user, appId) {
6628
- return isBuilder(user, appId) || isAdmin(user);
6629
- }
6630
- function isAdminOrGlobalBuilder(user, appId) {
6631
- return isGlobalBuilder(user) || isAdmin(user);
6632
- }
6633
- function hasAppBuilderPermissions(user) {
6634
- if (!user) {
6635
- return false;
6636
- }
6637
- const appLength = user.builder?.apps?.length;
6638
- const isGlobalBuilder3 = !!user.builder?.global;
6639
- return !isGlobalBuilder3 && appLength != null && appLength > 0;
6640
- }
6641
- function hasAppCreatorPermissions(user) {
6642
- if (!user) {
6643
- return false;
6644
- }
6645
- return _.flow(
6646
- _.get("roles"),
6647
- _.values,
6648
- _.find((x) => x === "CREATOR"),
6649
- (x) => !!x
6650
- )(user);
6651
- }
6652
- function hasBuilderPermissions(user) {
6653
- if (!user) {
6654
- return false;
6655
- }
6656
- return user.builder?.global || hasAppBuilderPermissions(user) || hasCreatorPermissions(user);
6657
- }
6658
- function hasAdminPermissions(user) {
6659
- if (!user) {
6660
- return false;
6661
- }
6662
- return !!user.admin?.global;
6663
- }
6664
- function hasCreatorPermissions(user) {
6665
- if (!user) {
6666
- return false;
6667
- }
6668
- return !!user.builder?.creator;
6669
- }
6670
- function isCreator(user) {
6671
- if (!user) {
6672
- return false;
6673
- }
6674
- return isGlobalBuilder(user) || hasAdminPermissions(user) || hasCreatorPermissions(user) || hasAppBuilderPermissions(user) || hasAppCreatorPermissions(user);
6675
- }
6676
- function getGlobalUserID(userId) {
6677
- if (typeof userId !== "string") {
6678
- return userId;
6679
- }
6680
- const prefix = `${"ro" /* ROW */}${SEPARATOR}${"ta_users" /* USER_METADATA */}${SEPARATOR}`;
6681
- if (!userId.startsWith(prefix)) {
6682
- return userId;
6683
- }
6684
- return userId.split(prefix)[1];
6685
- }
6686
- function containsUserID(value) {
6687
- if (typeof value !== "string") {
6688
- return false;
6689
- }
6690
- return value.includes(`${"us" /* USER */}${SEPARATOR}`);
6691
- }
6692
-
6693
- // ../shared-core/src/table.ts
6694
- init_src();
6695
- var allowDisplayColumnByType = {
6696
- ["string" /* STRING */]: true,
6697
- ["longform" /* LONGFORM */]: true,
6698
- ["options" /* OPTIONS */]: true,
6699
- ["number" /* NUMBER */]: true,
6700
- ["datetime" /* DATETIME */]: true,
6701
- ["formula" /* FORMULA */]: true,
6702
- ["auto" /* AUTO */]: true,
6703
- ["internal" /* INTERNAL */]: true,
6704
- ["barcodeqr" /* BARCODEQR */]: true,
6705
- ["bigint" /* BIGINT */]: true,
6706
- ["boolean" /* BOOLEAN */]: false,
6707
- ["array" /* ARRAY */]: false,
6708
- ["attachment" /* ATTACHMENT */]: false,
6709
- ["link" /* LINK */]: false,
6710
- ["json" /* JSON */]: false,
6711
- ["bb_reference" /* BB_REFERENCE */]: false
6712
- };
6713
- var allowSortColumnByType = {
6714
- ["string" /* STRING */]: true,
6715
- ["longform" /* LONGFORM */]: true,
6716
- ["options" /* OPTIONS */]: true,
6717
- ["number" /* NUMBER */]: true,
6718
- ["datetime" /* DATETIME */]: true,
6719
- ["auto" /* AUTO */]: true,
6720
- ["internal" /* INTERNAL */]: true,
6721
- ["barcodeqr" /* BARCODEQR */]: true,
6722
- ["bigint" /* BIGINT */]: true,
6723
- ["boolean" /* BOOLEAN */]: true,
6724
- ["json" /* JSON */]: true,
6725
- ["formula" /* FORMULA */]: false,
6726
- ["attachment" /* ATTACHMENT */]: false,
6727
- ["array" /* ARRAY */]: false,
6728
- ["link" /* LINK */]: false,
6729
- ["bb_reference" /* BB_REFERENCE */]: false
6730
- };
6828
+ init_src2();
6731
6829
 
6732
6830
  // src/utils/index.ts
6733
6831
  var utils_exports3 = {};
@@ -6770,7 +6868,7 @@ async function compare(data, encrypted) {
6770
6868
 
6771
6869
  // src/utils/utils.ts
6772
6870
  init_db4();
6773
- init_constants3();
6871
+ init_constants4();
6774
6872
  init_environment2();
6775
6873
  init_context2();
6776
6874
  init_src();
@@ -6829,7 +6927,7 @@ async function getAppIdFromCtx(ctx) {
6829
6927
  if (!appId && ctx.request.body && ctx.request.body.appId) {
6830
6928
  appId = confirmAppId(ctx.request.body.appId);
6831
6929
  }
6832
- const pathId = parseAppIdFromUrl(ctx.path);
6930
+ const pathId = parseAppIdFromUrlPath(ctx.path);
6833
6931
  if (!appId && pathId) {
6834
6932
  appId = confirmAppId(pathId);
6835
6933
  }
@@ -6840,16 +6938,16 @@ async function getAppIdFromCtx(ctx) {
6840
6938
  }
6841
6939
  const referer = ctx.request.headers.referer;
6842
6940
  if (!appId && referer?.includes(BUILDER_APP_PREFIX)) {
6843
- const refererId = parseAppIdFromUrl(ctx.request.headers.referer);
6941
+ const refererId = parseAppIdFromUrlPath(ctx.request.headers.referer);
6844
6942
  appId = confirmAppId(refererId);
6845
6943
  }
6846
6944
  return appId;
6847
6945
  }
6848
- function parseAppIdFromUrl(url) {
6946
+ function parseAppIdFromUrlPath(url) {
6849
6947
  if (!url) {
6850
6948
  return;
6851
6949
  }
6852
- return url.split("/").find((subPath) => subPath.startsWith(APP_PREFIX3));
6950
+ return url.split("?")[0].split("/").find((subPath) => subPath.startsWith(APP_PREFIX3));
6853
6951
  }
6854
6952
  function openJwt(token) {
6855
6953
  if (!token) {
@@ -6996,7 +7094,7 @@ async function getClient(type, opts) {
6996
7094
  return newRedlock(OPTIONS.AUTO_EXTEND);
6997
7095
  }
6998
7096
  default: {
6999
- throw utils_exports2.unreachable(type);
7097
+ throw utils_exports.unreachable(type);
7000
7098
  }
7001
7099
  }
7002
7100
  }
@@ -7217,7 +7315,7 @@ var API = class {
7217
7315
 
7218
7316
  // src/accounts/accounts.ts
7219
7317
  init_environment2();
7220
- init_constants3();
7318
+ init_constants4();
7221
7319
  var api = new API(environment_default.ACCOUNT_PORTAL_URL);
7222
7320
  var EXIT_EARLY = environment_default.SELF_HOSTED || environment_default.DISABLE_ACCOUNT_PORTAL;
7223
7321
  var getAccount = async (email) => {
@@ -7324,7 +7422,7 @@ init_environment2();
7324
7422
 
7325
7423
  // src/users/lookup.ts
7326
7424
  init_db4();
7327
- init_constants3();
7425
+ init_constants4();
7328
7426
 
7329
7427
  // src/cache/invite.ts
7330
7428
  var invite_exports = {};
@@ -7548,6 +7646,7 @@ var EmailUnavailableError = class extends Error {
7548
7646
 
7549
7647
  // src/users/utils.ts
7550
7648
  init_context2();
7649
+ init_src2();
7551
7650
  var isBuilder2 = sdk_exports.users.isBuilder;
7552
7651
  var isAdmin2 = sdk_exports.users.isAdmin;
7553
7652
  var isCreator2 = sdk_exports.users.isCreator;
@@ -7700,7 +7799,7 @@ var eventKey = (event) => {
7700
7799
  };
7701
7800
  var readEvent = async (event) => {
7702
7801
  const key = eventKey(event);
7703
- const result = await get(key);
7802
+ const result = await get2(key);
7704
7803
  return result;
7705
7804
  };
7706
7805
  var recordEvent = async (event, properties) => {
@@ -7887,7 +7986,7 @@ __export(queue_exports, {
7887
7986
 
7888
7987
  // src/queue/queue.ts
7889
7988
  init_environment2();
7890
- init_utils2();
7989
+ init_utils3();
7891
7990
 
7892
7991
  // src/queue/inMemoryQueue.ts
7893
7992
  var import_events2 = __toESM(require("events"));
@@ -8651,7 +8750,7 @@ var end = async () => {
8651
8750
  await clearEvents();
8652
8751
  };
8653
8752
  var getBackfillMetadata = async () => {
8654
- return get("backfillMetadata" /* BACKFILL_METADATA */);
8753
+ return get2("backfillMetadata" /* BACKFILL_METADATA */);
8655
8754
  };
8656
8755
  var saveBackfillMetadata = async (backfill) => {
8657
8756
  return store("backfillMetadata" /* BACKFILL_METADATA */, backfill);
@@ -8677,7 +8776,7 @@ var isBackfillingEvent = async (event) => {
8677
8776
  };
8678
8777
  var isAlreadySent = async (event, properties) => {
8679
8778
  const eventKey2 = getEventKey(event, properties);
8680
- const cachedEvent = await get(eventKey2, {
8779
+ const cachedEvent = await get2(eventKey2, {
8681
8780
  useTenancy: false
8682
8781
  });
8683
8782
  return !!cachedEvent;
@@ -10246,7 +10345,7 @@ async function getSession(userId, sessionId) {
10246
10345
  init_src();
10247
10346
  var bulkDeleteProcessing = async (dbUser) => {
10248
10347
  const userId = dbUser._id;
10249
- await users_exports.removeUser(dbUser);
10348
+ await users_exports2.removeUser(dbUser);
10250
10349
  await handleDeleteEvents(dbUser);
10251
10350
  await user_exports.invalidateUser(userId);
10252
10351
  await invalidateSessions(userId, { reason: "bulk-deletion" });
@@ -10409,7 +10508,7 @@ var UserDB = class _UserDB {
10409
10508
  let response = await db.put(builtUser);
10410
10509
  builtUser._rev = response.rev;
10411
10510
  await handleSaveEvents(builtUser, dbUser);
10412
- await users_exports.addUser(
10511
+ await users_exports2.addUser(
10413
10512
  tenantId,
10414
10513
  builtUser._id,
10415
10514
  builtUser.email,
@@ -10474,7 +10573,7 @@ var UserDB = class _UserDB {
10474
10573
  const usersToBulkSave = await Promise.all(usersToSave);
10475
10574
  await bulkUpdateGlobalUsers(usersToBulkSave);
10476
10575
  for (const user of usersToBulkSave) {
10477
- await users_exports.addUser(tenantId, user._id, user.email);
10576
+ await users_exports2.addUser(tenantId, user._id, user.email);
10478
10577
  await handleSaveEvents(user, void 0);
10479
10578
  }
10480
10579
  const saved = usersToBulkSave.map((user) => {
@@ -10564,7 +10663,7 @@ var UserDB = class _UserDB {
10564
10663
  }
10565
10664
  }
10566
10665
  }
10567
- await users_exports.removeUser(dbUser);
10666
+ await users_exports2.removeUser(dbUser);
10568
10667
  await db.remove(userId, dbUser._rev);
10569
10668
  const creatorsToDelete = isCreator2(dbUser) ? 1 : 0;
10570
10669
  await _UserDB.quotas.removeUsers(1, creatorsToDelete);
@@ -10752,7 +10851,7 @@ function getGlobalUserByAppPage(appId, user) {
10752
10851
  if (!user) {
10753
10852
  return;
10754
10853
  }
10755
- return generateAppUserID(getProdAppID(appId), user._id);
10854
+ return generateAppUserID(getProdAppID2(appId), user._id);
10756
10855
  }
10757
10856
  async function searchGlobalUsersByEmail(email, opts, getOpts) {
10758
10857
  if (typeof email !== "string") {
@@ -10847,7 +10946,7 @@ function cleanseUserObject(user, base) {
10847
10946
  return user;
10848
10947
  }
10849
10948
  async function addAppBuilder(user, appId) {
10850
- const prodAppId = getProdAppID(appId);
10949
+ const prodAppId = getProdAppID2(appId);
10851
10950
  user.builder ??= {};
10852
10951
  user.builder.creator = true;
10853
10952
  user.builder.apps ??= [];
@@ -10855,7 +10954,7 @@ async function addAppBuilder(user, appId) {
10855
10954
  await UserDB.save(user, { hashPassword: false });
10856
10955
  }
10857
10956
  async function removeAppBuilder(user, appId) {
10858
- const prodAppId = getProdAppID(appId);
10957
+ const prodAppId = getProdAppID2(appId);
10859
10958
  if (user.builder && user.builder.apps?.includes(prodAppId)) {
10860
10959
  user.builder.apps = user.builder.apps.filter((id) => id !== prodAppId);
10861
10960
  }
@@ -10863,6 +10962,7 @@ async function removeAppBuilder(user, appId) {
10863
10962
  }
10864
10963
 
10865
10964
  // src/cache/user.ts
10965
+ init_src2();
10866
10966
  var EXPIRY_SECONDS3 = 3600;
10867
10967
  async function populateFromDB2(userId, tenantId) {
10868
10968
  const db = getTenantDB(tenantId);
@@ -10906,7 +11006,7 @@ async function getUser(userId, tenantId, populateUser) {
10906
11006
  try {
10907
11007
  tenantId = getTenantId();
10908
11008
  } catch (err) {
10909
- tenantId = await users_exports.lookupTenantId(userId);
11009
+ tenantId = await users_exports2.lookupTenantId(userId);
10910
11010
  }
10911
11011
  }
10912
11012
  const client = await getUserClient();
@@ -11257,7 +11357,7 @@ __export(migrations_exports, {
11257
11357
  });
11258
11358
 
11259
11359
  // src/migrations/migrations.ts
11260
- init_constants3();
11360
+ init_constants4();
11261
11361
  init_db4();
11262
11362
  init_environment2();
11263
11363
  init_context2();
@@ -11989,7 +12089,7 @@ __export(auth_exports, {
11989
12089
 
11990
12090
  // src/auth/auth.ts
11991
12091
  init_context2();
11992
- init_constants3();
12092
+ init_constants4();
11993
12093
 
11994
12094
  // src/middleware/index.ts
11995
12095
  var middleware_exports = {};
@@ -12021,7 +12121,7 @@ __export(local_exports, {
12021
12121
  authenticate: () => authenticate,
12022
12122
  options: () => options
12023
12123
  });
12024
- init_constants3();
12124
+ init_constants4();
12025
12125
 
12026
12126
  // src/middleware/passport/utils.ts
12027
12127
  init_context2();
@@ -12348,7 +12448,7 @@ __export(google_exports2, {
12348
12448
  postAuth: () => postAuth,
12349
12449
  preAuth: () => preAuth
12350
12450
  });
12351
- init_constants3();
12451
+ init_constants4();
12352
12452
  var GoogleStrategy2 = require("passport-google-oauth").OAuth2Strategy;
12353
12453
  async function fetchGoogleCreds() {
12354
12454
  let config = await getGoogleDatasourceConfig();
@@ -12414,7 +12514,7 @@ async function postAuth(passport2, ctx, next) {
12414
12514
  }
12415
12515
 
12416
12516
  // src/middleware/authenticated.ts
12417
- init_constants3();
12517
+ init_constants4();
12418
12518
 
12419
12519
  // src/middleware/matchers.ts
12420
12520
  var PARAM_REGEX = /\/:(.*?)(\/.*)?$/g;
@@ -12751,7 +12851,7 @@ var auditLog_default2 = async (ctx, next) => {
12751
12851
 
12752
12852
  // src/middleware/tenancy.ts
12753
12853
  init_context2();
12754
- init_constants3();
12854
+ init_constants4();
12755
12855
  init_src();
12756
12856
  function tenancy_default(allowQueryStringPatterns, noTenancyPatterns, opts = { noTenancyRequired: false }) {
12757
12857
  const allowQsOptions = buildMatcherRegex(allowQueryStringPatterns);
@@ -12772,7 +12872,7 @@ function tenancy_default(allowQueryStringPatterns, noTenancyPatterns, opts = { n
12772
12872
  }
12773
12873
 
12774
12874
  // src/middleware/internalApi.ts
12775
- init_constants3();
12875
+ init_constants4();
12776
12876
  var internalApi_default = async (ctx, next) => {
12777
12877
  const apiKey = ctx.request.headers["x-budibase-api-key" /* API_KEY */];
12778
12878
  if (!apiKey) {
@@ -12788,7 +12888,7 @@ var internalApi_default = async (ctx, next) => {
12788
12888
  };
12789
12889
 
12790
12890
  // src/middleware/csrf.ts
12791
- init_constants3();
12891
+ init_constants4();
12792
12892
  var EXCLUDED_METHODS = ["GET", "HEAD", "OPTIONS"];
12793
12893
  var INCLUDED_CONTENT_TYPES = [
12794
12894
  "application/x-www-form-urlencoded",
@@ -12903,7 +13003,7 @@ var pinoMiddleware = getMiddleware();
12903
13003
  var middleware_default = pinoMiddleware;
12904
13004
 
12905
13005
  // src/logging/correlation/middleware.ts
12906
- init_constants3();
13006
+ init_constants4();
12907
13007
  var import_uuid3 = require("uuid");
12908
13008
  var correlator3 = require("correlation-id");
12909
13009
  var correlation = (ctx, next) => {
@@ -13136,7 +13236,7 @@ async function platformLogout(opts) {
13136
13236
  }
13137
13237
 
13138
13238
  // src/index.ts
13139
- init_constants3();
13239
+ init_constants4();
13140
13240
  init_logging();
13141
13241
 
13142
13242
  // src/plugin/index.ts
@@ -13287,10 +13387,10 @@ __export(redis_exports, {
13287
13387
  Client: () => redis_default,
13288
13388
  clients: () => init_exports,
13289
13389
  locks: () => redlockImpl_exports,
13290
- utils: () => utils_exports
13390
+ utils: () => utils_exports2
13291
13391
  });
13292
13392
  init_redis();
13293
- init_utils2();
13393
+ init_utils3();
13294
13394
  init_init();
13295
13395
 
13296
13396
  // src/index.ts
@@ -13443,7 +13543,7 @@ function init7(processors2) {
13443
13543
  init_db4();
13444
13544
  init_docIds();
13445
13545
  init_context2();
13446
- init_constants3();
13546
+ init_constants4();
13447
13547
  init_db4();
13448
13548
  var tenancy = {
13449
13549
  ...tenancy_exports,