"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LightdashInstallType = exports.isLightdashMode = exports.CompleteUserSchema = exports.hasSpecialCharacters = exports.snakeCaseName = exports.findFieldByIdInExplore = exports.getVisibleFields = exports.SEED_GROUP_2 = exports.SEED_GROUP = exports.SEED_SPACE = exports.SEED_PROJECT = exports.SEED_PAT = exports.SEED_EMBED_SECRET = exports.SEED_ORG_2_ADMIN_ROLE = exports.SEED_ORG_2_ADMIN_PASSWORD = exports.SEED_ORG_2_ADMIN_EMAIL = exports.SEED_ORG_2_ADMIN = exports.SEED_ORG_2 = exports.SEED_ORG_1_VIEWER_ROLE = exports.SEED_ORG_1_VIEWER_PASSWORD = exports.SEED_ORG_1_VIEWER_EMAIL = exports.SEED_ORG_1_VIEWER = exports.SEED_ORG_1_EDITOR_ROLE = exports.SEED_ORG_1_EDITOR_PASSWORD = exports.SEED_ORG_1_EDITOR_EMAIL = exports.SEED_ORG_1_EDITOR = exports.SEED_ORG_1_ADMIN_ROLE = exports.SEED_ORG_1_ADMIN_PASSWORD = exports.SEED_ORG_1_ADMIN_EMAIL = exports.SEED_ORG_1_ADMIN = exports.SEED_ORG_1 = exports.replaceStringInArray = exports.toggleArrayValue = exports.hasIntersection = exports.validatePassword = exports.getPasswordSchema = exports.getEmailSchema = exports.validateEmail = exports.vizThemeColors = exports.assertUnreachable = exports.modelAsCodeSchema = exports.lightdashProjectConfigSchema = exports.lightdashDbtYamlSchema = exports.dashboardAsCodeSchema = exports.chartAsCodeSchema = exports.DbtSchemaEditor = exports.projectMemberAbilities = exports.JWT_HEADER_NAME = exports.getUserAbilityBuilder = exports.defineUserAbility = void 0;
exports.SPACE_TREE_2 = exports.SPACE_TREE_1 = exports.getProjectDirectory = exports.deepEqual = exports.removeEmptyProperties = exports.getTableCalculationsFromItemsMap = exports.getMetricsFromItemsMap = exports.getFilterableDimensionsFromItemsMap = exports.getDimensionsFromItemsMap = exports.getFieldsFromMetricQuery = exports.getAxisName = exports.getDateGroupLabel = exports.getResultValueArray = void 0;
exports.hexToRGB = hexToRGB;
exports.getFieldMap = getFieldMap;
exports.getItemMap = getItemMap;
exports.itemsInMetricQuery = itemsInMetricQuery;
exports.formatRawValue = formatRawValue;
exports.formatRawRows = formatRawRows;
exports.formatRow = formatRow;
exports.formatRows = formatRows;
exports.isNotNull = isNotNull;
const tslib_1 = require("tslib");
const dayjs_1 = tslib_1.__importDefault(require("dayjs"));
const utc_1 = tslib_1.__importDefault(require("dayjs/plugin/utc"));
const zod_1 = require("zod");
const api_1 = require("./types/api");
const field_1 = require("./types/field");
const organizationMemberProfile_1 = require("./types/organizationMemberProfile");
const projects_1 = require("./types/projects");
const space_1 = require("./types/space");
const timeFrames_1 = require("./types/timeFrames");
const additionalMetrics_1 = require("./utils/additionalMetrics");
const fields_1 = require("./utils/fields");
const formatting_1 = require("./utils/formatting");
const item_1 = require("./utils/item");
const organization_1 = require("./utils/organization");
dayjs_1.default.extend(utc_1.default);
tslib_1.__exportStar(require("./authorization/buildAccountHelpers"), exports);
var index_1 = require("./authorization/index");
Object.defineProperty(exports, "defineUserAbility", { enumerable: true, get: function () { return index_1.defineUserAbility; } });
Object.defineProperty(exports, "getUserAbilityBuilder", { enumerable: true, get: function () { return index_1.getUserAbilityBuilder; } });
Object.defineProperty(exports, "JWT_HEADER_NAME", { enumerable: true, get: function () { return index_1.JWT_HEADER_NAME; } });
tslib_1.__exportStar(require("./authorization/jwtAbility"), exports);
var projectMemberAbility_1 = require("./authorization/projectMemberAbility");
Object.defineProperty(exports, "projectMemberAbilities", { enumerable: true, get: function () { return projectMemberAbility_1.projectMemberAbilities; } });
tslib_1.__exportStar(require("./authorization/parseAccount"), exports);
tslib_1.__exportStar(require("./authorization/roleToScopeMapping"), exports);
tslib_1.__exportStar(require("./authorization/scopeAbilityBuilder"), exports);
tslib_1.__exportStar(require("./authorization/scopes"), exports);
tslib_1.__exportStar(require("./authorization/serviceAccountAbility"), exports);
tslib_1.__exportStar(require("./authorization/space/spaceAccessResolver"), exports);
tslib_1.__exportStar(require("./authorization/types"), exports);
tslib_1.__exportStar(require("./compiler/compilationReport"), exports);
tslib_1.__exportStar(require("./compiler/exploreCompiler"), exports);
tslib_1.__exportStar(require("./compiler/filtersCompiler"), exports);
tslib_1.__exportStar(require("./compiler/lightdashModelConverter"), exports);
tslib_1.__exportStar(require("./compiler/parameters"), exports);
tslib_1.__exportStar(require("./compiler/translator"), exports);
tslib_1.__exportStar(require("./constants/screenshot"), exports);
tslib_1.__exportStar(require("./constants/sessionStorageKeys"), exports);
tslib_1.__exportStar(require("./constants/spaces"), exports);
tslib_1.__exportStar(require("./constants/sqlRunner"), exports);
var DbtSchemaEditor_1 = require("./dbt/DbtSchemaEditor/DbtSchemaEditor");
Object.defineProperty(exports, "DbtSchemaEditor", { enumerable: true, get: function () { return tslib_1.__importDefault(DbtSchemaEditor_1).default; } });
tslib_1.__exportStar(require("./dbt/validation"), exports);
tslib_1.__exportStar(require("./ee"), exports);
tslib_1.__exportStar(require("./preAggregates"), exports);
tslib_1.__exportStar(require("./pivot/derivePivotConfigFromChart"), exports);
tslib_1.__exportStar(require("./pivot/pivotConfig"), exports);
tslib_1.__exportStar(require("./pivot/pivotQueryResults"), exports);
tslib_1.__exportStar(require("./pivot/utils"), exports);
var chart_as_code_1_0_json_1 = require("./schemas/json/chart-as-code-1.0.json");
Object.defineProperty(exports, "chartAsCodeSchema", { enumerable: true, get: function () { return tslib_1.__importDefault(chart_as_code_1_0_json_1).default; } });
var dashboard_as_code_1_0_json_1 = require("./schemas/json/dashboard-as-code-1.0.json");
Object.defineProperty(exports, "dashboardAsCodeSchema", { enumerable: true, get: function () { return tslib_1.__importDefault(dashboard_as_code_1_0_json_1).default; } });
var lightdash_dbt_2_0_json_1 = require("./schemas/json/lightdash-dbt-2.0.json");
Object.defineProperty(exports, "lightdashDbtYamlSchema", { enumerable: true, get: function () { return tslib_1.__importDefault(lightdash_dbt_2_0_json_1).default; } });
var lightdash_project_config_1_0_json_1 = require("./schemas/json/lightdash-project-config-1.0.json");
Object.defineProperty(exports, "lightdashProjectConfigSchema", { enumerable: true, get: function () { return tslib_1.__importDefault(lightdash_project_config_1_0_json_1).default; } });
var model_as_code_1_0_json_1 = require("./schemas/json/model-as-code-1.0.json");
Object.defineProperty(exports, "modelAsCodeSchema", { enumerable: true, get: function () { return tslib_1.__importDefault(model_as_code_1_0_json_1).default; } });
tslib_1.__exportStar(require("./templating/liquidSql"), exports);
tslib_1.__exportStar(require("./templating/template"), exports);
tslib_1.__exportStar(require("./types/account"), exports);
tslib_1.__exportStar(require("./types/adminNotifications"), exports);
tslib_1.__exportStar(require("./types/analytics"), exports);
tslib_1.__exportStar(require("./types/any"), exports);
tslib_1.__exportStar(require("./types/api"), exports);
tslib_1.__exportStar(require("./types/api/comments"), exports);
tslib_1.__exportStar(require("./types/api/errors"), exports);
tslib_1.__exportStar(require("./types/api/notifications"), exports);
tslib_1.__exportStar(require("./types/api/paginatedQuery"), exports);
tslib_1.__exportStar(require("./types/api/parameters"), exports);
tslib_1.__exportStar(require("./types/api/share"), exports);
tslib_1.__exportStar(require("./types/api/sort"), exports);
tslib_1.__exportStar(require("./types/api/spotlight"), exports);
tslib_1.__exportStar(require("./types/api/success"), exports);
tslib_1.__exportStar(require("./types/api/uuid"), exports);
tslib_1.__exportStar(require("./types/auth"), exports);
tslib_1.__exportStar(require("./types/bigQuerySSO"), exports);
tslib_1.__exportStar(require("./types/catalog"), exports);
tslib_1.__exportStar(require("./types/changeset"), exports);
tslib_1.__exportStar(require("./types/coder"), exports);
tslib_1.__exportStar(require("./types/comments"), exports);
tslib_1.__exportStar(require("./types/conditionalFormatting"), exports);
tslib_1.__exportStar(require("./types/content"), exports);
tslib_1.__exportStar(require("./types/contentVerification"), exports);
tslib_1.__exportStar(require("./types/dashboard"), exports);
tslib_1.__exportStar(require("./types/dbt"), exports);
tslib_1.__exportStar(require("./types/downloadFile"), exports);
tslib_1.__exportStar(require("./types/email"), exports);
tslib_1.__exportStar(require("./types/errors"), exports);
tslib_1.__exportStar(require("./types/explore"), exports);
tslib_1.__exportStar(require("./types/favorites"), exports);
tslib_1.__exportStar(require("./types/featureFlags"), exports);
tslib_1.__exportStar(require("./types/impersonationOrganizationSettings"), exports);
tslib_1.__exportStar(require("./types/field"), exports);
tslib_1.__exportStar(require("./types/fieldMatch"), exports);
tslib_1.__exportStar(require("./types/filter"), exports);
tslib_1.__exportStar(require("./types/funnel"), exports);
tslib_1.__exportStar(require("./types/gdrive"), exports);
tslib_1.__exportStar(require("./types/gitIntegration"), exports);
tslib_1.__exportStar(require("./types/groups"), exports);
tslib_1.__exportStar(require("./types/job"), exports);
tslib_1.__exportStar(require("./types/knex-paginate"), exports);
tslib_1.__exportStar(require("./types/lightdashModel"), exports);
tslib_1.__exportStar(require("./types/lightdashProjectConfig"), exports);
tslib_1.__exportStar(require("./types/metricQuery"), exports);
tslib_1.__exportStar(require("./types/metricsExplorer"), exports);
tslib_1.__exportStar(require("./types/notifications"), exports);
tslib_1.__exportStar(require("./types/oauth"), exports);
tslib_1.__exportStar(require("./types/openIdIdentity"), exports);
tslib_1.__exportStar(require("./types/organization"), exports);
tslib_1.__exportStar(require("./types/organizationMemberProfile"), exports);
tslib_1.__exportStar(require("./types/organizationSso"), exports);
tslib_1.__exportStar(require("./types/organizationWarehouseCredentials"), exports);
tslib_1.__exportStar(require("./types/paginateResults"), exports);
tslib_1.__exportStar(require("./types/parameters"), exports);
tslib_1.__exportStar(require("./types/periodOverPeriodComparison"), exports);
tslib_1.__exportStar(require("./types/personalAccessToken"), exports);
tslib_1.__exportStar(require("./types/pinning"), exports);
tslib_1.__exportStar(require("./types/pivot"), exports);
tslib_1.__exportStar(require("./types/preAggregate"), exports);
tslib_1.__exportStar(require("./types/projectCompileLogs"), exports);
tslib_1.__exportStar(require("./types/projectGroupAccess"), exports);
tslib_1.__exportStar(require("./types/projectMemberProfile"), exports);
tslib_1.__exportStar(require("./types/projectMemberRole"), exports);
tslib_1.__exportStar(require("./types/projects"), exports);
tslib_1.__exportStar(require("./types/promotion"), exports);
tslib_1.__exportStar(require("./types/queryHistory"), exports);
tslib_1.__exportStar(require("./types/rename"), exports);
tslib_1.__exportStar(require("./types/resourceViewItem"), exports);
tslib_1.__exportStar(require("./types/results"), exports);
tslib_1.__exportStar(require("./types/roles"), exports);
tslib_1.__exportStar(require("./types/savedCharts"), exports);
tslib_1.__exportStar(require("./types/scheduler"), exports);
tslib_1.__exportStar(require("./types/schedulerLog"), exports);
tslib_1.__exportStar(require("./types/schedulerTaskList"), exports);
tslib_1.__exportStar(require("./types/scopes"), exports);
tslib_1.__exportStar(require("./types/search"), exports);
tslib_1.__exportStar(require("./types/share"), exports);
tslib_1.__exportStar(require("./types/slack"), exports);
tslib_1.__exportStar(require("./types/slackSettings"), exports);
tslib_1.__exportStar(require("./types/softDelete"), exports);
tslib_1.__exportStar(require("./types/space"), exports);
tslib_1.__exportStar(require("./types/spotlightTableConfig"), exports);
tslib_1.__exportStar(require("./types/sqlRunner"), exports);
tslib_1.__exportStar(require("./types/SshKeyPair"), exports);
tslib_1.__exportStar(require("./types/table"), exports);
tslib_1.__exportStar(require("./types/tags"), exports);
tslib_1.__exportStar(require("./types/timeFrames"), exports);
tslib_1.__exportStar(require("./types/timezone"), exports);
tslib_1.__exportStar(require("./types/user"), exports);
tslib_1.__exportStar(require("./types/userAttributes"), exports);
tslib_1.__exportStar(require("./types/userWarehouseCredentials"), exports);
tslib_1.__exportStar(require("./types/validation"), exports);
tslib_1.__exportStar(require("./types/warehouse"), exports);
tslib_1.__exportStar(require("./types/yamlSchema"), exports);
tslib_1.__exportStar(require("./utils/accessors"), exports);
tslib_1.__exportStar(require("./utils/additionalMetrics"), exports);
tslib_1.__exportStar(require("./utils/api"), exports);
var assertUnreachable_1 = require("./utils/assertUnreachable");
Object.defineProperty(exports, "assertUnreachable", { enumerable: true, get: function () { return tslib_1.__importDefault(assertUnreachable_1).default; } });
tslib_1.__exportStar(require("./utils/bigNumber"), exports);
tslib_1.__exportStar(require("./utils/changeset"), exports);
tslib_1.__exportStar(require("./utils/charts"), exports);
tslib_1.__exportStar(require("./utils/chartValidation"), exports);
tslib_1.__exportStar(require("./utils/colors"), exports);
tslib_1.__exportStar(require("./utils/conditionalFormatExpressions"), exports);
tslib_1.__exportStar(require("./utils/conditionalFormatting"), exports);
tslib_1.__exportStar(require("./utils/connectionChanges"), exports);
tslib_1.__exportStar(require("./utils/convertCustomDimensionsToYaml"), exports);
tslib_1.__exportStar(require("./utils/convertCustomMetricsToYaml"), exports);
tslib_1.__exportStar(require("./utils/customDimensions"), exports);
tslib_1.__exportStar(require("./utils/dashboard"), exports);
tslib_1.__exportStar(require("./utils/dbt"), exports);
tslib_1.__exportStar(require("./utils/dependencyGraph"), exports);
tslib_1.__exportStar(require("./utils/email"), exports);
tslib_1.__exportStar(require("./utils/fields"), exports);
tslib_1.__exportStar(require("./utils/filters"), exports);
tslib_1.__exportStar(require("./utils/formatting"), exports);
tslib_1.__exportStar(require("./utils/github"), exports);
tslib_1.__exportStar(require("./utils/i18n/chartAsCode"), exports);
tslib_1.__exportStar(require("./utils/i18n/dashboardAsCode"), exports);
tslib_1.__exportStar(require("./utils/i18n/merge"), exports);
tslib_1.__exportStar(require("./utils/i18n/types"), exports);
tslib_1.__exportStar(require("./utils/item"), exports);
tslib_1.__exportStar(require("./utils/loadLightdashProjectConfig"), exports);
tslib_1.__exportStar(require("./utils/lightdashSqlVariables"), exports);
tslib_1.__exportStar(require("./utils/metricsExplorer"), exports);
tslib_1.__exportStar(require("./utils/normalizeCellRawForFilter"), exports);
tslib_1.__exportStar(require("./utils/oauth"), exports);
tslib_1.__exportStar(require("./utils/organization"), exports);
tslib_1.__exportStar(require("./utils/projectMemberRole"), exports);
tslib_1.__exportStar(require("./utils/promises"), exports);
tslib_1.__exportStar(require("./utils/sanitizeHtml"), exports);
tslib_1.__exportStar(require("./utils/scheduler"), exports);
tslib_1.__exportStar(require("./utils/searchParams"), exports);
tslib_1.__exportStar(require("./utils/slack"), exports);
tslib_1.__exportStar(require("./utils/sleep"), exports);
tslib_1.__exportStar(require("./utils/slugs"), exports);
tslib_1.__exportStar(require("./utils/sqlDialect"), exports);
tslib_1.__exportStar(require("./utils/subtotals"), exports);
tslib_1.__exportStar(require("./utils/dateZoom"), exports);
tslib_1.__exportStar(require("./utils/tableCalculationFunctions"), exports);
tslib_1.__exportStar(require("./utils/time"), exports);
tslib_1.__exportStar(require("./utils/timeFrames"), exports);
tslib_1.__exportStar(require("./utils/resolveQueryTimezone"), exports);
tslib_1.__exportStar(require("./utils/virtualView"), exports);
tslib_1.__exportStar(require("./utils/warehouse"), exports);
tslib_1.__exportStar(require("./visualizations/CartesianChartDataModel"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/getCartesianAxisFormatterConfig"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/styles/axisStyles"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/styles/barChartStyles"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/styles/gridStyles"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/styles/legendStyles"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/styles/pieChartStyles"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/styles/referenceLineStyles"), exports);
exports.vizThemeColors = tslib_1.__importStar(require("./visualizations/helpers/styles/themeColors"));
tslib_1.__exportStar(require("./visualizations/helpers/styles/tooltipStyles"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/styles/valueLabelStyles"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/tooltipFormatter"), exports);
tslib_1.__exportStar(require("./visualizations/helpers/valueFormatter"), exports);
tslib_1.__exportStar(require("./visualizations/PieChartDataModel"), exports);
tslib_1.__exportStar(require("./visualizations/TableDataModel"), exports);
tslib_1.__exportStar(require("./visualizations/types"), exports);
tslib_1.__exportStar(require("./visualizations/types/IResultsRunner"), exports);
const validateEmail = (email) => {
    if (/\s/.test(email)) {
        return false;
    }
    const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
};
exports.validateEmail = validateEmail;
const getEmailSchema = () => zod_1.z
    .string()
    .refine((email) => (0, exports.validateEmail)(email), {
    message: 'Email address is not valid',
})
    .refine((email) => !/\s/.test(email), {
    message: 'Email address must not contain whitespaces',
});
exports.getEmailSchema = getEmailSchema;
const getPasswordSchema = () => zod_1.z
    .string()
    .min(8, { message: 'must be at least 8 characters long' })
    .regex(/[a-zA-Z]/, { message: 'must contain a letter' })
    .regex(/[\d\W_]/, { message: 'must contain a number or symbol' });
exports.getPasswordSchema = getPasswordSchema;
const validatePassword = (password) => (0, exports.getPasswordSchema)().safeParse(password).success;
exports.validatePassword = validatePassword;
const hasIntersection = (tags, tags2) => {
    const intersection = tags.filter((value) => tags2.includes(value));
    return intersection.length > 0;
};
exports.hasIntersection = hasIntersection;
const toggleArrayValue = (initialArray, value) => {
    const array = [...initialArray];
    const index = array.indexOf(value);
    if (index === -1) {
        array.push(value);
    }
    else {
        array.splice(index, 1);
    }
    return array;
};
exports.toggleArrayValue = toggleArrayValue;
const replaceStringInArray = (arrayToUpdate, valueToReplace, newValue) => arrayToUpdate.map((value) => (value === valueToReplace ? newValue : value));
exports.replaceStringInArray = replaceStringInArray;
function hexToRGB(hex, alpha) {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    if (alpha !== undefined) {
        return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    }
    return `rgb(${r}, ${g}, ${b})`;
}
// Seeds
exports.SEED_ORG_1 = {
    organization_uuid: '172a2270-000f-42be-9c68-c4752c23ae51',
    organization_name: 'Jaffle Shop',
};
exports.SEED_ORG_1_ADMIN = {
    user_uuid: 'b264d83a-9000-426a-85ec-3f9c20f368ce',
    first_name: 'David',
    last_name: 'Attenborough',
    is_marketing_opted_in: true,
    is_tracking_anonymized: false,
    is_setup_complete: true,
    is_active: true,
};
exports.SEED_ORG_1_ADMIN_EMAIL = {
    email: 'demo@lightdash.com',
    is_primary: true,
};
exports.SEED_ORG_1_ADMIN_PASSWORD = {
    password: 'demo_password!',
};
exports.SEED_ORG_1_ADMIN_ROLE = organizationMemberProfile_1.OrganizationMemberRole.ADMIN;
exports.SEED_ORG_1_EDITOR = {
    user_uuid: '80fb8b59-d6b7-4ed6-b969-9849310f3e53',
    first_name: 'Editor',
    last_name: 'User',
    is_marketing_opted_in: true,
    is_tracking_anonymized: false,
    is_setup_complete: true,
    is_active: true,
};
exports.SEED_ORG_1_EDITOR_EMAIL = {
    email: 'demo2@lightdash.com',
    is_primary: true,
};
exports.SEED_ORG_1_EDITOR_PASSWORD = {
    password: 'demo_password!',
};
exports.SEED_ORG_1_EDITOR_ROLE = organizationMemberProfile_1.OrganizationMemberRole.EDITOR;
exports.SEED_ORG_1_VIEWER = {
    user_uuid: 'e0dd2003-c291-4e14-b977-7a03b7edc842',
    first_name: 'Viewer',
    last_name: 'User',
    is_marketing_opted_in: true,
    is_tracking_anonymized: false,
    is_setup_complete: true,
    is_active: true,
};
exports.SEED_ORG_1_VIEWER_EMAIL = {
    email: 'demo3@lightdash.com',
    is_primary: true,
};
exports.SEED_ORG_1_VIEWER_PASSWORD = {
    password: 'demo_password!',
};
exports.SEED_ORG_1_VIEWER_ROLE = organizationMemberProfile_1.OrganizationMemberRole.VIEWER;
// Another user
exports.SEED_ORG_2 = {
    organization_uuid: '42339eef-359e-4ec4-b810-54ef0b4e3446',
    organization_name: 'Another Shop',
};
exports.SEED_ORG_2_ADMIN = {
    user_uuid: '57cd4548-cbe3-42b3-aa13-97821713e307',
    first_name: 'Another',
    last_name: 'User',
    is_marketing_opted_in: true,
    is_tracking_anonymized: false,
    is_setup_complete: true,
    is_active: true,
};
exports.SEED_ORG_2_ADMIN_EMAIL = {
    email: 'another@lightdash.com',
    is_primary: true,
};
exports.SEED_ORG_2_ADMIN_PASSWORD = {
    password: 'demo_password!',
};
exports.SEED_ORG_2_ADMIN_ROLE = organizationMemberProfile_1.OrganizationMemberRole.ADMIN;
exports.SEED_EMBED_SECRET = 'zU3h50saDOO20czNFNRok';
// Deterministic PAT for dev environment
// Use with: Authorization: ApiKey ldpat_deadbeefdeadbeefdeadbeefdeadbeef
exports.SEED_PAT = {
    token: 'ldpat_deadbeefdeadbeefdeadbeefdeadbeef',
    description: 'Dev seed PAT',
};
exports.SEED_PROJECT = {
    project_uuid: '3675b69e-8324-4110-bdca-059031aa8da3',
    name: 'Jaffle shop',
    project_type: projects_1.ProjectType.DEFAULT,
    dbt_connection_type: projects_1.DbtProjectType.DBT,
    dbt_connection: null,
    copied_from_project_uuid: null,
    organization_warehouse_credentials_uuid: null,
};
exports.SEED_SPACE = {
    name: exports.SEED_PROJECT.name,
};
exports.SEED_GROUP = {
    groupUuid: '9d615ede-5758-4954-9fb9-2a07fc415ba5',
    name: 'Org 1 Group',
};
exports.SEED_GROUP_2 = {
    groupUuid: '1456c265-f375-4d64-bd33-105c84ad9b5d',
    name: 'Org 1 Editor Group',
};
const getVisibleFields = (explore) => (0, fields_1.getFields)(explore).filter(({ hidden }) => !hidden);
exports.getVisibleFields = getVisibleFields;
const findFieldByIdInExplore = (explore, id) => (0, fields_1.getFields)(explore).find((field) => (0, item_1.getItemId)(field) === id);
exports.findFieldByIdInExplore = findFieldByIdInExplore;
const snakeCaseName = (text) => text
    .replace(/\W+/g, ' ')
    .split(/ |\B(?=[A-Z])/)
    .map((word) => word.toLowerCase())
    .join('_');
exports.snakeCaseName = snakeCaseName;
const hasSpecialCharacters = (text) => /[^a-zA-Z ]/g.test(text);
exports.hasSpecialCharacters = hasSpecialCharacters;
exports.CompleteUserSchema = zod_1.z.object({
    organizationName: (0, organization_1.getOrganizationNameSchema)().optional(),
    jobTitle: zod_1.z.string().min(0),
    enableEmailDomainAccess: zod_1.z.boolean().default(false),
    isMarketingOptedIn: zod_1.z.boolean().default(true),
    isTrackingAnonymized: zod_1.z.boolean().default(false),
});
const isLightdashMode = (x) => Object.values(api_1.LightdashMode).includes(x);
exports.isLightdashMode = isLightdashMode;
var LightdashInstallType;
(function (LightdashInstallType) {
    LightdashInstallType["DOCKER_IMAGE"] = "docker_image";
    LightdashInstallType["BASH_INSTALL"] = "bash_install";
    LightdashInstallType["HEROKU"] = "heroku";
    LightdashInstallType["UNKNOWN"] = "unknown";
})(LightdashInstallType || (exports.LightdashInstallType = LightdashInstallType = {}));
const getResultValueArray = (rows, preferRaw = false, calculateMinAndMax = false, excludeNulls = false) => {
    const minMax = {};
    const results = rows.map((row) => Object.keys(row).reduce((acc, key) => {
        if (excludeNulls && row[key]?.value.raw === null) {
            return acc;
        }
        const rawWithFallback = row[key]?.value.raw ?? row[key]?.value.formatted; // using nullish coalescing operator to handle null and undefined only
        const formattedWithFallback = row[key]?.value.formatted || row[key]?.value.raw;
        const value = preferRaw ? rawWithFallback : formattedWithFallback;
        acc[key] = value;
        if (calculateMinAndMax) {
            const numericValue = Number(value);
            if (!Number.isNaN(numericValue)) {
                if (!minMax[key]) {
                    minMax[key] = { min: numericValue, max: numericValue };
                }
                else {
                    minMax[key].min = Math.min(minMax[key].min, numericValue);
                    minMax[key].max = Math.max(minMax[key].max, numericValue);
                }
            }
        }
        return acc;
    }, {}));
    return calculateMinAndMax ? { results, minsAndMaxes: minMax } : { results };
};
exports.getResultValueArray = getResultValueArray;
const getDateGroupLabel = (axisItem) => {
    if ((0, field_1.isDimension)(axisItem) &&
        [field_1.DimensionType.DATE, field_1.DimensionType.TIMESTAMP].includes(axisItem.type) &&
        (axisItem.group || (axisItem.groups && axisItem.groups.length > 0)) &&
        axisItem.label &&
        axisItem.timeInterval) {
        const timeFrame = timeFrames_1.TimeFrames[axisItem.timeInterval]?.toLowerCase() || '';
        if (timeFrame && axisItem.label.endsWith(` ${timeFrame}`)) {
            // Remove the time frame from the end of the label - e.g. from 'Order created day' to 'Order created'.
            return (0, item_1.getItemLabelWithoutTableName)(axisItem).replace(new RegExp(`\\s+${timeFrame}$`), '');
        }
        return (0, field_1.friendlyName)(axisItem.label);
    }
    return undefined;
};
exports.getDateGroupLabel = getDateGroupLabel;
const getAxisName = ({ isAxisTheSameForAllSeries, selectedAxisIndex, axisReference, axisIndex, axisName, series, itemsMap, }) => {
    const itemIndex = (series || [])[0]?.encode[axisReference].field;
    const defaultItem = itemsMap && itemIndex ? itemsMap[itemIndex] : undefined;
    const dateGroupName = defaultItem
        ? (0, exports.getDateGroupLabel)(defaultItem)
        : undefined;
    const fallbackSeriesName = series && series.length === 1
        ? series[0]?.name ||
            (defaultItem && (0, item_1.getItemLabelWithoutTableName)(defaultItem))
        : undefined;
    return !isAxisTheSameForAllSeries || selectedAxisIndex === axisIndex
        ? axisName || dateGroupName || fallbackSeriesName
        : undefined;
};
exports.getAxisName = getAxisName;
function getFieldMap(explore, additionalMetrics = []) {
    return [...(0, fields_1.getFields)(explore), ...additionalMetrics].reduce((sum, field) => ({
        ...sum,
        [(0, item_1.getItemId)(field)]: field,
    }), {});
}
function getItemMap(explore, additionalMetrics = [], tableCalculations = [], customDimensions = []) {
    const convertedAdditionalMetrics = (additionalMetrics || []).reduce((acc, additionalMetric) => {
        const table = explore.tables[additionalMetric.table];
        if (table) {
            const metric = (0, additionalMetrics_1.convertAdditionalMetric)({
                additionalMetric,
                table,
            });
            acc.push(metric);
        }
        return acc;
    }, []);
    return [
        ...(0, fields_1.getFields)(explore),
        ...convertedAdditionalMetrics,
        ...tableCalculations,
        ...customDimensions,
    ].reduce((acc, item) => {
        acc[(0, item_1.getItemId)(item)] = item;
        return acc;
    }, {});
}
const getFieldsFromMetricQuery = (metricQuery, explore) => {
    const itemsMap = getItemMap(explore, metricQuery.additionalMetrics, metricQuery.tableCalculations, metricQuery.customDimensions);
    const itemIdsInMetricQuery = [
        ...metricQuery.dimensions,
        ...metricQuery.metrics,
        ...(metricQuery.tableCalculations || []).map(item_1.getItemId),
    ];
    return itemIdsInMetricQuery.reduce((acc, id) => {
        const item = itemsMap[id];
        if (item)
            acc[id] = item;
        return acc;
    }, {});
};
exports.getFieldsFromMetricQuery = getFieldsFromMetricQuery;
const getDimensionsFromItemsMap = (itemsMap) => Object.entries(itemsMap).reduce((acc, [key, value]) => {
    if ((0, field_1.isDimension)(value) || (0, field_1.isCustomDimension)(value)) {
        return { ...acc, [key]: value };
    }
    return acc;
}, {});
exports.getDimensionsFromItemsMap = getDimensionsFromItemsMap;
const getFilterableDimensionsFromItemsMap = (itemsMap) => Object.entries(itemsMap).reduce((acc, [key, value]) => {
    if ((0, field_1.isDimension)(value) && (0, field_1.isFilterableDimension)(value)) {
        return { ...acc, [key]: value };
    }
    return acc;
}, {});
exports.getFilterableDimensionsFromItemsMap = getFilterableDimensionsFromItemsMap;
const getMetricsFromItemsMap = (itemsMap, filter = () => true) => Object.entries(itemsMap).reduce((acc, [key, value]) => {
    if ((0, field_1.isField)(value) && (0, field_1.isMetric)(value) && filter(value)) {
        return { ...acc, [key]: value };
    }
    return acc;
}, {});
exports.getMetricsFromItemsMap = getMetricsFromItemsMap;
const getTableCalculationsFromItemsMap = (itemsMap) => Object.entries(itemsMap ?? {}).reduce((acc, [key, value]) => {
    if ((0, field_1.isTableCalculation)(value)) {
        return { ...acc, [key]: value };
    }
    return acc;
}, {});
exports.getTableCalculationsFromItemsMap = getTableCalculationsFromItemsMap;
function itemsInMetricQuery(metricQuery) {
    return metricQuery === undefined
        ? []
        : [
            ...metricQuery.metrics,
            ...metricQuery.dimensions,
            ...(metricQuery.tableCalculations || []).map((tc) => tc.name),
        ];
}
function formatRawValue(field, value) {
    const isTimestamp = (0, field_1.isField)(field) &&
        (field.type === field_1.DimensionType.DATE ||
            field.type === field_1.DimensionType.TIMESTAMP);
    if (isTimestamp && value !== null) {
        // We want to return the datetime in UTC to avoid timezone issues in the frontend like in chart tooltips
        return (0, dayjs_1.default)(value).utc(true).format();
    }
    return value;
}
// ! We format raw values so we can't use the values directly from the warehouse to compare with subtotals of date dimensions
function formatRawRows(rows, itemsMap) {
    return rows.map((row) => {
        const resultRow = {};
        const columnNames = Object.keys(row || {});
        for (const columnName of columnNames) {
            const value = row[columnName];
            const item = itemsMap[columnName];
            resultRow[columnName] = formatRawValue(item, value);
        }
        return resultRow;
    });
}
function formatRow(row, itemsMap, pivotValuesColumns, parameters, timezone) {
    const resultRow = {};
    const columnNames = Object.keys(row || {});
    for (const columnName of columnNames) {
        const value = row[columnName];
        const pivotValuesColumn = pivotValuesColumns?.[columnName];
        const item = itemsMap[pivotValuesColumn?.referenceField ?? columnName];
        resultRow[columnName] = {
            value: {
                raw: formatRawValue(item, value),
                formatted: (0, formatting_1.formatItemValue)(item, value, false, parameters, timezone),
            },
        };
    }
    return resultRow;
}
function formatRows(rows, itemsMap, pivotValuesColumns, parameters, timezone) {
    return rows.map((row) => formatRow(row, itemsMap, pivotValuesColumns, parameters, timezone));
}
const isObject = (object) => object != null && typeof object === 'object';
const removeEmptyProperties = (object) => {
    const newObj = {};
    Object.keys(object).forEach((key) => {
        if (object[key] === Object(object[key]))
            newObj[key] = (0, exports.removeEmptyProperties)(object[key]);
        else if (object[key] !== undefined && object[key] !== null)
            newObj[key] = object[key];
    });
    return newObj;
};
exports.removeEmptyProperties = removeEmptyProperties;
const deepEqual = (object1, object2) => {
    const keys1 = Object.keys(object1);
    const keys2 = Object.keys(object2);
    if (keys1.length !== keys2.length) {
        return false;
    }
    return keys1.every((key) => {
        const val1 = object1[key];
        const val2 = object2[key];
        const areObjects = isObject(val1) && isObject(val2);
        return !((areObjects && !(0, exports.deepEqual)(val1, val2)) ||
            (!areObjects && val1 !== val2));
    });
};
exports.deepEqual = deepEqual;
const getProjectDirectory = (dbtConnection) => {
    if (!dbtConnection)
        return undefined;
    switch (dbtConnection.type) {
        case projects_1.DbtProjectType.DBT:
            return dbtConnection.project_dir;
        case projects_1.DbtProjectType.GITHUB:
        case projects_1.DbtProjectType.GITLAB:
        case projects_1.DbtProjectType.BITBUCKET:
        case projects_1.DbtProjectType.AZURE_DEVOPS:
            return dbtConnection.project_sub_path;
        case projects_1.DbtProjectType.DBT_CLOUD_IDE:
        case projects_1.DbtProjectType.NONE:
            return undefined;
        default:
            return undefined;
    }
};
exports.getProjectDirectory = getProjectDirectory;
function isNotNull(arg) {
    return arg !== null;
}
exports.SPACE_TREE_1 = [
    {
        name: 'Parent Space 1',
        children: [
            {
                name: 'Child Space 1.1',
                children: [
                    {
                        name: 'Grandchild Space 1.1.1',
                    },
                    {
                        name: 'Grandchild Space 1.1.2',
                    },
                ],
            },
            {
                name: 'Child Space 1.2',
                children: [
                    {
                        name: 'Grandchild Space 1.2.1',
                    },
                    {
                        name: 'Grandchild Space 1.2.2',
                        children: [
                            {
                                name: 'Great Grandchild Space 1.2.2.1',
                            },
                        ],
                    },
                ],
            },
            {
                name: 'Child Space 1.3',
                children: [
                    {
                        name: 'Grandchild Space 1.3.1',
                        children: [
                            {
                                name: 'Great Grandchild Space 1.3.1.1',
                            },
                        ],
                    },
                ],
            },
        ],
    },
    {
        name: 'Parent Space 2',
        inheritParentPermissions: false,
        children: [
            {
                name: 'Child Space 2.1',
                children: [
                    {
                        name: 'Grandchild Space 2.1.1',
                    },
                ],
            },
        ],
    },
    {
        name: 'Parent Space 3',
        inheritParentPermissions: false,
        access: [
            // Admin will automatically be added, we only seed editor
            {
                userUuid: exports.SEED_ORG_1_EDITOR.user_uuid,
                role: space_1.SpaceMemberRole.EDITOR,
            },
        ],
        children: [
            {
                name: 'Child Space 3.1',
            },
        ],
    },
    // Created by admin and added group access
    {
        name: 'Parent Space 5',
        inheritParentPermissions: false,
        access: [],
        groupAccess: [
            {
                groupUuid: exports.SEED_GROUP_2.groupUuid,
                role: space_1.SpaceMemberRole.EDITOR,
            },
        ],
        children: [
            {
                name: 'Child Space 5.1',
            },
        ],
    },
];
exports.SPACE_TREE_2 = [
    {
        name: 'Parent Space 4',
        inheritParentPermissions: false,
        access: [],
        children: [
            {
                name: 'Child Space 4.1',
            },
        ],
    },
];
//# sourceMappingURL=index.js.map