var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/auth/server.ts
var server_exports = {};
__export(server_exports, {
  createAutoRefreshFetch: () => createAutoRefreshFetch,
  isAuthenticationError: () => isAuthenticationError,
  isTokenExpiringSoon: () => isTokenExpiringSoon,
  proxyMiddleware: () => proxyMiddleware,
  proxyMiddlewareConfig: () => proxyMiddlewareConfig,
  refreshAccessToken: () => refreshAccessToken,
  refreshIfExpiringSoon: () => refreshIfExpiringSoon
});
module.exports = __toCommonJS(server_exports);

// src/auth/middlewares/proxy.ts
var import_server = require("next/server");
function proxyMiddleware(request) {
  const { pathname, search } = request.nextUrl;
  const apiUrl2 = process.env.NEXT_PUBLIC_API_URL;
  if (pathname.startsWith("/media/")) {
    const targetUrl = `${apiUrl2}${pathname}${search}`;
    return import_server.NextResponse.rewrite(targetUrl, { request: { headers: request.headers } });
  }
  if (pathname.startsWith("/api/")) {
    const targetUrl = `${apiUrl2}${pathname}${search}`;
    return import_server.NextResponse.rewrite(targetUrl, { request: { headers: request.headers } });
  }
  return import_server.NextResponse.next();
}
__name(proxyMiddleware, "proxyMiddleware");
var proxyMiddlewareConfig = {
  matcher: ["/media/:path*", "/api/:path*"]
};

// src/generated/cfg_accounts/accounts__auth/client.ts
var Auth = class {
  static {
    __name(this, "Auth");
  }
  constructor(client) {
    this.client = client;
  }
  /**
   * Refresh JWT token.
   */
  async accountsTokenRefreshCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/token/refresh/", { body: data });
    return response;
  }
};

// src/generated/cfg_accounts/accounts__oauth/client.ts
var Oauth = class {
  static {
    __name(this, "Oauth");
  }
  constructor(client) {
    this.client = client;
  }
  /**
   * List OAuth connections
   * 
   * Get all OAuth connections for the current user.
   */
  async accountsOauthConnectionsList() {
    const response = await this.client.request("GET", "/cfg/accounts/oauth/connections/");
    return response.results || response;
  }
  /**
   * Disconnect OAuth provider
   * 
   * Remove OAuth connection for the specified provider.
   */
  async accountsOauthDisconnectCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/oauth/disconnect/", { body: data });
    return response;
  }
  /**
   * Start GitHub OAuth
   * 
   * Generate GitHub OAuth authorization URL. Redirect user to this URL to
   * start authentication.
   */
  async accountsOauthGithubAuthorizeCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/oauth/github/authorize/", { body: data });
    return response;
  }
  /**
   * Complete GitHub OAuth
   * 
   * Exchange authorization code for JWT tokens. Call this after GitHub
   * redirects back with code.
   */
  async accountsOauthGithubCallbackCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/oauth/github/callback/", { body: data });
    return response;
  }
  /**
   * List OAuth providers
   * 
   * Get list of available OAuth providers for authentication.
   */
  async accountsOauthProvidersRetrieve() {
    const response = await this.client.request("GET", "/cfg/accounts/oauth/providers/");
    return response;
  }
};

// src/generated/cfg_accounts/accounts__user_profile/client.ts
var UserProfile = class {
  static {
    __name(this, "UserProfile");
  }
  constructor(client) {
    this.client = client;
  }
  /**
   * Get current user profile
   * 
   * Retrieve the current authenticated user's profile information.
   */
  async accountsProfileRetrieve() {
    const response = await this.client.request("GET", "/cfg/accounts/profile/");
    return response;
  }
  /**
   * Upload user avatar
   * 
   * Upload avatar image for the current authenticated user. Accepts
   * multipart/form-data with 'avatar' field.
   */
  async accountsProfileAvatarCreate(data) {
    const formData = new FormData();
    formData.append("avatar", data.avatar);
    const response = await this.client.request("POST", "/cfg/accounts/profile/avatar/", { formData });
    return response;
  }
  /**
   * Delete user account
   * 
   * Permanently delete the current user's account. This operation: -
   * Deactivates the account (user cannot log in) - Anonymizes personal data
   * (GDPR compliance) - Frees up the email address for re-registration -
   * Preserves audit trail The account can be restored by an administrator if
   * needed.
   */
  async accountsProfileDeleteCreate() {
    const response = await this.client.request("POST", "/cfg/accounts/profile/delete/");
    return response;
  }
  /**
   * Partial update user profile
   * 
   * Partially update the current authenticated user's profile information.
   * Supports avatar upload.
   */
  async accountsProfilePartialUpdate(data) {
    const response = await this.client.request("PUT", "/cfg/accounts/profile/partial/", { body: data });
    return response;
  }
  /**
   * Partial update user profile
   * 
   * Partially update the current authenticated user's profile information.
   * Supports avatar upload.
   */
  async accountsProfilePartialPartialUpdate(data) {
    const response = await this.client.request("PATCH", "/cfg/accounts/profile/partial/", { body: data });
    return response;
  }
  /**
   * Update user profile
   * 
   * Update the current authenticated user's profile information.
   */
  async accountsProfileUpdateUpdate(data) {
    const response = await this.client.request("PUT", "/cfg/accounts/profile/update/", { body: data });
    return response;
  }
  /**
   * Update user profile
   * 
   * Update the current authenticated user's profile information.
   */
  async accountsProfileUpdatePartialUpdate(data) {
    const response = await this.client.request("PATCH", "/cfg/accounts/profile/update/", { body: data });
    return response;
  }
};

// src/generated/cfg_accounts/accounts/client.ts
var Accounts = class {
  static {
    __name(this, "Accounts");
  }
  constructor(client) {
    this.client = client;
  }
  /**
   * Request OTP code to email or phone.
   */
  async otpRequestCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/otp/request/", { body: data });
    return response;
  }
  /**
   * Verify OTP code and return JWT tokens or 2FA session. If user has 2FA
   * enabled: - Returns requires_2fa=True with session_id - Client must
   * complete 2FA verification at /cfg/totp/verify/ If user has no 2FA: -
   * Returns JWT tokens and user data directly
   */
  async otpVerifyCreate(data) {
    const response = await this.client.request("POST", "/cfg/accounts/otp/verify/", { body: data });
    return response;
  }
};

// src/generated/cfg_accounts/http.ts
var FetchAdapter = class {
  static {
    __name(this, "FetchAdapter");
  }
  async request(request) {
    const { method, url, headers, body, params, formData, binaryBody } = request;
    let finalUrl = url;
    if (params) {
      const searchParams = new URLSearchParams();
      Object.entries(params).forEach(([key, value]) => {
        if (value !== null && value !== void 0) {
          searchParams.append(key, String(value));
        }
      });
      const queryString = searchParams.toString();
      if (queryString) {
        finalUrl = url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
      }
    }
    const finalHeaders = { ...headers };
    let requestBody;
    if (formData) {
      requestBody = formData;
    } else if (binaryBody) {
      finalHeaders["Content-Type"] = "application/octet-stream";
      requestBody = binaryBody;
    } else if (body) {
      finalHeaders["Content-Type"] = "application/json";
      requestBody = JSON.stringify(body);
    }
    const response = await fetch(finalUrl, {
      method,
      headers: finalHeaders,
      body: requestBody,
      credentials: "include"
      // Include Django session cookies
    });
    let data = null;
    const contentType = response.headers.get("content-type");
    if (response.status !== 204 && contentType?.includes("application/json")) {
      data = await response.json();
    } else if (response.status !== 204) {
      data = await response.text();
    }
    const responseHeaders = {};
    response.headers.forEach((value, key) => {
      responseHeaders[key] = value;
    });
    return {
      data,
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders
    };
  }
};

// src/generated/cfg_accounts/errors.ts
var APIError = class extends Error {
  constructor(statusCode, statusText, response, url, message) {
    super(message || `HTTP ${statusCode}: ${statusText}`);
    this.statusCode = statusCode;
    this.statusText = statusText;
    this.response = response;
    this.url = url;
    this.name = "APIError";
  }
  static {
    __name(this, "APIError");
  }
  /**
   * Get error details from response.
   * DRF typically returns: { "detail": "Error message" } or { "field": ["error1", "error2"] }
   */
  get details() {
    if (typeof this.response === "object" && this.response !== null) {
      return this.response;
    }
    return null;
  }
  /**
   * Get field-specific validation errors from DRF.
   * Returns: { "field_name": ["error1", "error2"], ... }
   */
  get fieldErrors() {
    const details = this.details;
    if (!details) return null;
    const fieldErrors = {};
    for (const [key, value] of Object.entries(details)) {
      if (Array.isArray(value)) {
        fieldErrors[key] = value;
      }
    }
    return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
  }
  /**
   * Get single error message from DRF.
   * Checks for "detail", "message", or first field error.
   */
  get errorMessage() {
    const details = this.details;
    if (!details) return this.message;
    if (details.detail) {
      return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
    }
    if (details.message) {
      return String(details.message);
    }
    const fieldErrors = this.fieldErrors;
    if (fieldErrors) {
      const firstField = Object.keys(fieldErrors)[0];
      if (firstField) {
        return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
      }
    }
    return this.message;
  }
  // Helper methods for common HTTP status codes
  get isValidationError() {
    return this.statusCode === 400;
  }
  get isAuthError() {
    return this.statusCode === 401;
  }
  get isPermissionError() {
    return this.statusCode === 403;
  }
  get isNotFoundError() {
    return this.statusCode === 404;
  }
  get isServerError() {
    return this.statusCode >= 500 && this.statusCode < 600;
  }
};
var NetworkError = class extends Error {
  constructor(message, url, originalError) {
    super(message);
    this.url = url;
    this.originalError = originalError;
    this.name = "NetworkError";
  }
  static {
    __name(this, "NetworkError");
  }
};

// src/generated/cfg_accounts/logger.ts
var import_consola = require("consola");
var DEFAULT_CONFIG = {
  enabled: process.env.NODE_ENV !== "production",
  logRequests: true,
  logResponses: true,
  logErrors: true,
  logBodies: true,
  logHeaders: false
};
var SENSITIVE_HEADERS = [
  "authorization",
  "cookie",
  "set-cookie",
  "x-api-key",
  "x-csrf-token"
];
var APILogger = class {
  static {
    __name(this, "APILogger");
  }
  constructor(config = {}) {
    this.config = { ...DEFAULT_CONFIG, ...config };
    this.consola = config.consola || (0, import_consola.createConsola)({
      level: this.config.enabled ? 4 : 0
    });
  }
  /**
   * Enable logging
   */
  enable() {
    this.config.enabled = true;
  }
  /**
   * Disable logging
   */
  disable() {
    this.config.enabled = false;
  }
  /**
   * Update configuration
   */
  setConfig(config) {
    this.config = { ...this.config, ...config };
  }
  /**
   * Filter sensitive headers
   */
  filterHeaders(headers) {
    if (!headers) return {};
    const filtered = {};
    Object.keys(headers).forEach((key) => {
      const lowerKey = key.toLowerCase();
      if (SENSITIVE_HEADERS.includes(lowerKey)) {
        filtered[key] = "***";
      } else {
        filtered[key] = headers[key] || "";
      }
    });
    return filtered;
  }
  /**
   * Log request
   */
  logRequest(request) {
    if (!this.config.enabled || !this.config.logRequests) return;
    const { method, url, headers, body } = request;
    this.consola.start(`${method} ${url}`);
    if (this.config.logHeaders && headers) {
      this.consola.debug("Headers:", this.filterHeaders(headers));
    }
    if (this.config.logBodies && body) {
      this.consola.debug("Body:", body);
    }
  }
  /**
   * Log response
   */
  logResponse(request, response) {
    if (!this.config.enabled || !this.config.logResponses) return;
    const { method, url } = request;
    const { status, statusText, data, duration } = response;
    const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
    this.consola.success(
      `${method} ${url} ${status} ${statusText} (${duration}ms)`
    );
    if (this.config.logBodies && data) {
      this.consola.debug("Response:", data);
    }
  }
  /**
   * Log error
   */
  logError(request, error) {
    if (!this.config.enabled || !this.config.logErrors) return;
    const { method, url } = request;
    const { message, statusCode, fieldErrors, duration } = error;
    this.consola.error(
      `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
    );
    this.consola.error("Message:", message);
    if (fieldErrors && Object.keys(fieldErrors).length > 0) {
      this.consola.error("Field Errors:");
      Object.entries(fieldErrors).forEach(([field, errors]) => {
        errors.forEach((err) => {
          this.consola.error(`  \u2022 ${field}: ${err}`);
        });
      });
    }
  }
  /**
   * Log general info
   */
  info(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.info(message, ...args);
  }
  /**
   * Log warning
   */
  warn(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.warn(message, ...args);
  }
  /**
   * Log error
   */
  error(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.error(message, ...args);
  }
  /**
   * Log debug
   */
  debug(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.debug(message, ...args);
  }
  /**
   * Log success
   */
  success(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.success(message, ...args);
  }
  /**
   * Create a sub-logger with prefix
   */
  withTag(tag) {
    return this.consola.withTag(tag);
  }
};
var defaultLogger = new APILogger();

// src/generated/cfg_accounts/retry.ts
var import_p_retry = __toESM(require("p-retry"), 1);
var DEFAULT_RETRY_CONFIG = {
  retries: 3,
  factor: 2,
  minTimeout: 1e3,
  maxTimeout: 6e4,
  randomize: true,
  onFailedAttempt: /* @__PURE__ */ __name(() => {
  }, "onFailedAttempt")
};
function shouldRetry(error) {
  if (error instanceof NetworkError) {
    return true;
  }
  if (error instanceof APIError) {
    const status = error.statusCode;
    if (status >= 500 && status < 600) {
      return true;
    }
    if (status === 429) {
      return true;
    }
    return false;
  }
  return true;
}
__name(shouldRetry, "shouldRetry");
async function withRetry(fn, config) {
  const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
  return (0, import_p_retry.default)(
    async () => {
      try {
        return await fn();
      } catch (error) {
        if (!shouldRetry(error)) {
          throw new import_p_retry.AbortError(error);
        }
        throw error;
      }
    },
    {
      retries: finalConfig.retries,
      factor: finalConfig.factor,
      minTimeout: finalConfig.minTimeout,
      maxTimeout: finalConfig.maxTimeout,
      randomize: finalConfig.randomize,
      onFailedAttempt: finalConfig.onFailedAttempt ? (error) => {
        const pRetryError = error;
        finalConfig.onFailedAttempt({
          error: pRetryError,
          attemptNumber: pRetryError.attemptNumber,
          retriesLeft: pRetryError.retriesLeft
        });
      } : void 0
    }
  );
}
__name(withRetry, "withRetry");

// src/generated/cfg_accounts/client.ts
var APIClient = class {
  constructor(baseUrl, options) {
    this.logger = null;
    this.retryConfig = null;
    this.tokenGetter = null;
    this.baseUrl = baseUrl.replace(/\/$/, "");
    this.httpClient = options?.httpClient || new FetchAdapter();
    this.tokenGetter = options?.tokenGetter || null;
    if (options?.loggerConfig !== void 0) {
      this.logger = new APILogger(options.loggerConfig);
    }
    if (options?.retryConfig !== void 0) {
      this.retryConfig = options.retryConfig;
    }
    this.auth = new Auth(this);
    this.oauth = new Oauth(this);
    this.user_profile = new UserProfile(this);
    this.accounts = new Accounts(this);
  }
  static {
    __name(this, "APIClient");
  }
  /**
   * Get CSRF token from cookies (for SessionAuthentication).
   *
   * Returns null if cookie doesn't exist (JWT-only auth).
   */
  getCsrfToken() {
    const name = "csrftoken";
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) {
      return parts.pop()?.split(";").shift() || null;
    }
    return null;
  }
  /**
   * Get the base URL for building streaming/download URLs.
   */
  getBaseUrl() {
    return this.baseUrl;
  }
  /**
   * Get JWT token for URL authentication (used in streaming endpoints).
   * Returns null if no token getter is configured or no token is available.
   */
  getToken() {
    return this.tokenGetter ? this.tokenGetter() : null;
  }
  /**
   * Make HTTP request with Django CSRF and session handling.
   * Automatically retries on network errors and 5xx server errors.
   */
  async request(method, path, options) {
    if (this.retryConfig) {
      return withRetry(() => this._makeRequest(method, path, options), {
        ...this.retryConfig,
        onFailedAttempt: /* @__PURE__ */ __name((info) => {
          if (this.logger) {
            this.logger.warn(
              `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} for ${method} ${path}: ${info.error.message}`
            );
          }
          this.retryConfig?.onFailedAttempt?.(info);
        }, "onFailedAttempt")
      });
    }
    return this._makeRequest(method, path, options);
  }
  /**
   * Internal request method (without retry wrapper).
   * Used by request() method with optional retry logic.
   */
  async _makeRequest(method, path, options) {
    const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
    const startTime = Date.now();
    const headers = {
      ...options?.headers || {}
    };
    if (!options?.formData && !options?.binaryBody && !headers["Content-Type"]) {
      headers["Content-Type"] = "application/json";
    }
    if (this.logger) {
      this.logger.logRequest({
        method,
        url,
        headers,
        body: options?.formData || options?.body,
        timestamp: startTime
      });
    }
    try {
      const response = await this.httpClient.request({
        method,
        url,
        headers,
        params: options?.params,
        body: options?.body,
        formData: options?.formData,
        binaryBody: options?.binaryBody
      });
      const duration = Date.now() - startTime;
      if (response.status >= 400) {
        const error = new APIError(
          response.status,
          response.statusText,
          response.data,
          url
        );
        if (this.logger) {
          this.logger.logError(
            {
              method,
              url,
              headers,
              body: options?.formData || options?.body,
              timestamp: startTime
            },
            {
              message: error.message,
              statusCode: response.status,
              duration,
              timestamp: Date.now()
            }
          );
        }
        throw error;
      }
      if (this.logger) {
        this.logger.logResponse(
          {
            method,
            url,
            headers,
            body: options?.formData || options?.body,
            timestamp: startTime
          },
          {
            status: response.status,
            statusText: response.statusText,
            data: response.data,
            duration,
            timestamp: Date.now()
          }
        );
      }
      return response.data;
    } catch (error) {
      const duration = Date.now() - startTime;
      if (error instanceof APIError) {
        throw error;
      }
      const isCORSError = error instanceof TypeError && (error.message.toLowerCase().includes("cors") || error.message.toLowerCase().includes("failed to fetch") || error.message.toLowerCase().includes("network request failed"));
      if (this.logger) {
        if (isCORSError) {
          this.logger.error(`\u{1F6AB} CORS Error: ${method} ${url}`);
          this.logger.error(`  \u2192 ${error instanceof Error ? error.message : String(error)}`);
          this.logger.error(`  \u2192 Configure security_domains parameter on the server`);
        } else {
          this.logger.error(`\u26A0\uFE0F  Network Error: ${method} ${url}`);
          this.logger.error(`  \u2192 ${error instanceof Error ? error.message : String(error)}`);
        }
      }
      if (typeof window !== "undefined") {
        try {
          if (isCORSError) {
            window.dispatchEvent(new CustomEvent("cors-error", {
              detail: {
                url,
                method,
                error: error instanceof Error ? error.message : String(error),
                timestamp: /* @__PURE__ */ new Date()
              },
              bubbles: true,
              cancelable: false
            }));
          } else {
            window.dispatchEvent(new CustomEvent("network-error", {
              detail: {
                url,
                method,
                error: error instanceof Error ? error.message : String(error),
                timestamp: /* @__PURE__ */ new Date()
              },
              bubbles: true,
              cancelable: false
            }));
          }
        } catch (eventError) {
        }
      }
      const networkError = error instanceof Error ? new NetworkError(error.message, url, error) : new NetworkError("Unknown error", url);
      if (this.logger) {
        this.logger.logError(
          {
            method,
            url,
            headers,
            body: options?.formData || options?.body,
            timestamp: startTime
          },
          {
            message: networkError.message,
            duration,
            timestamp: Date.now()
          }
        );
      }
      throw networkError;
    }
  }
};

// src/generated/cfg_accounts/storage.ts
var LocalStorageAdapter = class {
  static {
    __name(this, "LocalStorageAdapter");
  }
  constructor(logger2) {
    this.logger = logger2;
  }
  getItem(key) {
    try {
      if (typeof window !== "undefined" && window.localStorage) {
        const value = localStorage.getItem(key);
        this.logger?.debug(`LocalStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
        return value;
      }
      this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
    } catch (error) {
      this.logger?.error("LocalStorage.getItem failed:", error);
    }
    return null;
  }
  setItem(key, value) {
    try {
      if (typeof window !== "undefined" && window.localStorage) {
        localStorage.setItem(key, value);
        this.logger?.debug(`LocalStorage.setItem("${key}"): success`);
      } else {
        this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
      }
    } catch (error) {
      this.logger?.error("LocalStorage.setItem failed:", error);
    }
  }
  removeItem(key) {
    try {
      if (typeof window !== "undefined" && window.localStorage) {
        localStorage.removeItem(key);
        this.logger?.debug(`LocalStorage.removeItem("${key}"): success`);
      } else {
        this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
      }
    } catch (error) {
      this.logger?.error("LocalStorage.removeItem failed:", error);
    }
  }
};

// src/generated/cfg_accounts/enums.ts
var OAuthConnectionProvider = /* @__PURE__ */ ((OAuthConnectionProvider2) => {
  OAuthConnectionProvider2["GITHUB"] = "github";
  return OAuthConnectionProvider2;
})(OAuthConnectionProvider || {});
var OTPRequestRequestChannel = /* @__PURE__ */ ((OTPRequestRequestChannel2) => {
  OTPRequestRequestChannel2["EMAIL"] = "email";
  OTPRequestRequestChannel2["PHONE"] = "phone";
  return OTPRequestRequestChannel2;
})(OTPRequestRequestChannel || {});

// src/generated/cfg_accounts/_utils/schemas/AccountDeleteResponse.schema.ts
var import_zod = require("zod");
var AccountDeleteResponseSchema = import_zod.z.object({
  success: import_zod.z.boolean(),
  message: import_zod.z.string()
});

// src/generated/cfg_accounts/_utils/schemas/CentrifugoToken.schema.ts
var import_zod2 = require("zod");
var CentrifugoTokenSchema = import_zod2.z.object({
  token: import_zod2.z.string(),
  centrifugo_url: import_zod2.z.union([import_zod2.z.url(), import_zod2.z.literal("")]),
  expires_at: import_zod2.z.string().datetime({ offset: true }),
  channels: import_zod2.z.array(import_zod2.z.string())
});

// src/generated/cfg_accounts/_utils/schemas/CfgAccountsProfileAvatarCreateRequest.schema.ts
var import_zod3 = require("zod");
var CfgAccountsProfileAvatarCreateRequestSchema = import_zod3.z.object({
  avatar: import_zod3.z.union([import_zod3.z.instanceof(File), import_zod3.z.instanceof(Blob)])
});

// src/generated/cfg_accounts/_utils/schemas/OAuthAuthorizeRequestRequest.schema.ts
var import_zod4 = require("zod");
var OAuthAuthorizeRequestRequestSchema = import_zod4.z.object({
  redirect_uri: import_zod4.z.union([import_zod4.z.url(), import_zod4.z.literal("")]).optional(),
  source_url: import_zod4.z.union([import_zod4.z.url(), import_zod4.z.literal("")]).optional()
});

// src/generated/cfg_accounts/_utils/schemas/OAuthAuthorizeResponse.schema.ts
var import_zod5 = require("zod");
var OAuthAuthorizeResponseSchema = import_zod5.z.object({
  authorization_url: import_zod5.z.union([import_zod5.z.url(), import_zod5.z.literal("")]),
  state: import_zod5.z.string()
});

// src/generated/cfg_accounts/_utils/schemas/OAuthCallbackRequestRequest.schema.ts
var import_zod6 = require("zod");
var OAuthCallbackRequestRequestSchema = import_zod6.z.object({
  code: import_zod6.z.string().min(10).max(500),
  state: import_zod6.z.string().min(20).max(100),
  redirect_uri: import_zod6.z.union([import_zod6.z.url(), import_zod6.z.literal("")]).optional()
});

// src/generated/cfg_accounts/_utils/schemas/OAuthConnection.schema.ts
var import_zod7 = require("zod");
var OAuthConnectionSchema = import_zod7.z.object({
  id: import_zod7.z.int(),
  provider: import_zod7.z.nativeEnum(OAuthConnectionProvider),
  provider_display: import_zod7.z.string(),
  provider_username: import_zod7.z.string(),
  provider_email: import_zod7.z.email(),
  provider_avatar_url: import_zod7.z.union([import_zod7.z.url(), import_zod7.z.literal("")]),
  connected_at: import_zod7.z.string().datetime({ offset: true }),
  last_login_at: import_zod7.z.string().datetime({ offset: true })
});

// src/generated/cfg_accounts/_utils/schemas/OAuthDisconnectRequestRequest.schema.ts
var import_zod8 = require("zod");
var OAuthDisconnectRequestRequestSchema = import_zod8.z.object({
  provider: import_zod8.z.nativeEnum(OAuthConnectionProvider)
});

// src/generated/cfg_accounts/_utils/schemas/OAuthError.schema.ts
var import_zod9 = require("zod");
var OAuthErrorSchema = import_zod9.z.object({
  error: import_zod9.z.string(),
  error_description: import_zod9.z.string().optional()
});

// src/generated/cfg_accounts/_utils/schemas/OAuthProvidersResponse.schema.ts
var import_zod10 = require("zod");
var OAuthProvidersResponseSchema = import_zod10.z.object({
  providers: import_zod10.z.array(import_zod10.z.record(import_zod10.z.string(), import_zod10.z.any()))
});

// src/generated/cfg_accounts/_utils/schemas/OAuthTokenResponse.schema.ts
var import_zod11 = require("zod");
var OAuthTokenResponseSchema = import_zod11.z.object({
  requires_2fa: import_zod11.z.boolean().optional(),
  session_id: import_zod11.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
  access: import_zod11.z.string().nullable().optional(),
  refresh: import_zod11.z.string().nullable().optional(),
  user: import_zod11.z.record(import_zod11.z.string(), import_zod11.z.any()).nullable().optional(),
  is_new_user: import_zod11.z.boolean(),
  is_new_connection: import_zod11.z.boolean(),
  should_prompt_2fa: import_zod11.z.boolean().optional()
});

// src/generated/cfg_accounts/_utils/schemas/OTPErrorResponse.schema.ts
var import_zod12 = require("zod");
var OTPErrorResponseSchema = import_zod12.z.object({
  error: import_zod12.z.string()
});

// src/generated/cfg_accounts/_utils/schemas/OTPRequestRequest.schema.ts
var import_zod13 = require("zod");
var OTPRequestRequestSchema = import_zod13.z.object({
  identifier: import_zod13.z.string().min(1),
  channel: import_zod13.z.nativeEnum(OTPRequestRequestChannel).optional(),
  source_url: import_zod13.z.union([import_zod13.z.url(), import_zod13.z.literal("")]).optional()
});

// src/generated/cfg_accounts/_utils/schemas/OTPRequestResponse.schema.ts
var import_zod14 = require("zod");
var OTPRequestResponseSchema = import_zod14.z.object({
  message: import_zod14.z.string()
});

// src/generated/cfg_accounts/_utils/schemas/OTPVerifyRequest.schema.ts
var import_zod15 = require("zod");
var OTPVerifyRequestSchema = import_zod15.z.object({
  identifier: import_zod15.z.string().min(1),
  otp: import_zod15.z.string().min(6).max(6),
  channel: import_zod15.z.nativeEnum(OTPRequestRequestChannel).optional(),
  source_url: import_zod15.z.union([import_zod15.z.url(), import_zod15.z.literal("")]).optional()
});

// src/generated/cfg_accounts/_utils/schemas/OTPVerifyResponse.schema.ts
var import_zod17 = require("zod");

// src/generated/cfg_accounts/_utils/schemas/User.schema.ts
var import_zod16 = require("zod");
var UserSchema = import_zod16.z.object({
  id: import_zod16.z.int(),
  email: import_zod16.z.email(),
  first_name: import_zod16.z.string().max(50).optional(),
  last_name: import_zod16.z.string().max(50).optional(),
  full_name: import_zod16.z.string(),
  initials: import_zod16.z.string(),
  display_username: import_zod16.z.string(),
  company: import_zod16.z.string().max(100).optional(),
  phone: import_zod16.z.string().max(20).optional(),
  position: import_zod16.z.string().max(100).optional(),
  avatar: import_zod16.z.union([import_zod16.z.url(), import_zod16.z.literal("")]).nullable(),
  is_staff: import_zod16.z.boolean(),
  is_superuser: import_zod16.z.boolean(),
  date_joined: import_zod16.z.string().datetime({ offset: true }),
  last_login: import_zod16.z.string().datetime({ offset: true }).nullable(),
  unanswered_messages_count: import_zod16.z.int(),
  centrifugo: CentrifugoTokenSchema.nullable()
});

// src/generated/cfg_accounts/_utils/schemas/OTPVerifyResponse.schema.ts
var OTPVerifyResponseSchema = import_zod17.z.object({
  requires_2fa: import_zod17.z.boolean().optional(),
  session_id: import_zod17.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
  refresh: import_zod17.z.string().nullable().optional(),
  access: import_zod17.z.string().nullable().optional(),
  user: UserSchema.nullable().optional(),
  should_prompt_2fa: import_zod17.z.boolean().optional()
});

// src/generated/cfg_accounts/_utils/schemas/PatchedUserProfileUpdateRequest.schema.ts
var import_zod18 = require("zod");
var PatchedUserProfileUpdateRequestSchema = import_zod18.z.object({
  first_name: import_zod18.z.string().max(50).optional(),
  last_name: import_zod18.z.string().max(50).optional(),
  company: import_zod18.z.string().max(100).optional(),
  phone: import_zod18.z.string().max(20).optional(),
  position: import_zod18.z.string().max(100).optional()
});

// src/generated/cfg_accounts/_utils/schemas/TokenRefresh.schema.ts
var import_zod19 = require("zod");
var TokenRefreshSchema = import_zod19.z.object({
  access: import_zod19.z.string(),
  refresh: import_zod19.z.string()
});

// src/generated/cfg_accounts/_utils/schemas/TokenRefreshRequest.schema.ts
var import_zod20 = require("zod");
var TokenRefreshRequestSchema = import_zod20.z.object({
  refresh: import_zod20.z.string().min(1)
});

// src/generated/cfg_accounts/_utils/schemas/UserProfileUpdateRequest.schema.ts
var import_zod21 = require("zod");
var UserProfileUpdateRequestSchema = import_zod21.z.object({
  first_name: import_zod21.z.string().max(50).optional(),
  last_name: import_zod21.z.string().max(50).optional(),
  company: import_zod21.z.string().max(100).optional(),
  phone: import_zod21.z.string().max(20).optional(),
  position: import_zod21.z.string().max(100).optional()
});

// src/generated/cfg_accounts/_utils/fetchers/accounts.ts
var import_consola2 = require("consola");

// src/generated/cfg_accounts/_utils/fetchers/accounts__auth.ts
var import_consola3 = require("consola");

// src/generated/cfg_accounts/_utils/fetchers/accounts__oauth.ts
var import_consola4 = require("consola");

// src/generated/cfg_accounts/_utils/fetchers/accounts__user_profile.ts
var import_consola5 = require("consola");

// src/generated/cfg_accounts/index.ts
var TOKEN_KEY = "auth_token";
var REFRESH_TOKEN_KEY = "refresh_token";
var API = class {
  constructor(baseUrl, options) {
    this._token = null;
    this._refreshToken = null;
    this.baseUrl = baseUrl;
    this.options = options;
    const logger2 = options?.loggerConfig ? new APILogger(options.loggerConfig) : void 0;
    this.storage = options?.storage || new LocalStorageAdapter(logger2);
    this._loadTokensFromStorage();
    this._client = new APIClient(this.baseUrl, {
      retryConfig: this.options?.retryConfig,
      loggerConfig: this.options?.loggerConfig,
      tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
    });
    this._injectAuthHeader();
    this.auth = this._client.auth;
    this.oauth = this._client.oauth;
    this.user_profile = this._client.user_profile;
    this.accounts = this._client.accounts;
  }
  static {
    __name(this, "API");
  }
  _loadTokensFromStorage() {
    this._token = this.storage.getItem(TOKEN_KEY);
    this._refreshToken = this.storage.getItem(REFRESH_TOKEN_KEY);
  }
  _reinitClients() {
    this._client = new APIClient(this.baseUrl, {
      retryConfig: this.options?.retryConfig,
      loggerConfig: this.options?.loggerConfig,
      tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
    });
    this._injectAuthHeader();
    this.auth = this._client.auth;
    this.oauth = this._client.oauth;
    this.user_profile = this._client.user_profile;
    this.accounts = this._client.accounts;
  }
  _injectAuthHeader() {
    const originalRequest = this._client.request.bind(this._client);
    this._client.request = async (method, path, options) => {
      const token = this.getToken();
      const mergedOptions = {
        ...options,
        headers: {
          ...options?.headers || {},
          ...token ? { "Authorization": `Bearer ${token}` } : {}
        }
      };
      return originalRequest(method, path, mergedOptions);
    };
  }
  /**
   * Get current JWT token
   */
  getToken() {
    return this.storage.getItem(TOKEN_KEY);
  }
  /**
   * Get current refresh token
   */
  getRefreshToken() {
    return this.storage.getItem(REFRESH_TOKEN_KEY);
  }
  /**
   * Set JWT token and refresh token
   * @param token - JWT access token
   * @param refreshToken - JWT refresh token (optional)
   */
  setToken(token, refreshToken) {
    this._token = token;
    this.storage.setItem(TOKEN_KEY, token);
    if (refreshToken) {
      this._refreshToken = refreshToken;
      this.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
    }
    this._reinitClients();
  }
  /**
   * Clear all tokens
   */
  clearTokens() {
    this._token = null;
    this._refreshToken = null;
    this.storage.removeItem(TOKEN_KEY);
    this.storage.removeItem(REFRESH_TOKEN_KEY);
    this._reinitClients();
  }
  /**
   * Check if user is authenticated
   */
  isAuthenticated() {
    return !!this.getToken();
  }
  /**
   * Update base URL and reinitialize clients
   * @param url - New base URL
   */
  setBaseUrl(url) {
    this.baseUrl = url;
    this._reinitClients();
  }
  /**
   * Get current base URL
   */
  getBaseUrl() {
    return this.baseUrl;
  }
  /**
   * Get OpenAPI schema path
   * @returns Path to the OpenAPI schema JSON file
   *
   * Note: The OpenAPI schema is available in the schema.json file.
   * You can load it dynamically using:
   * ```typescript
   * const schema = await fetch('./schema.json').then(r => r.json());
   * // or using fs in Node.js:
   * // const schema = JSON.parse(fs.readFileSync('./schema.json', 'utf-8'));
   * ```
   */
  getSchemaPath() {
    return "./schema.json";
  }
};

// src/generated/cfg_centrifugo/logger.ts
var import_consola6 = require("consola");
var DEFAULT_CONFIG2 = {
  enabled: process.env.NODE_ENV !== "production",
  logRequests: true,
  logResponses: true,
  logErrors: true,
  logBodies: true,
  logHeaders: false
};
var SENSITIVE_HEADERS2 = [
  "authorization",
  "cookie",
  "set-cookie",
  "x-api-key",
  "x-csrf-token"
];
var APILogger2 = class {
  static {
    __name(this, "APILogger");
  }
  constructor(config = {}) {
    this.config = { ...DEFAULT_CONFIG2, ...config };
    this.consola = config.consola || (0, import_consola6.createConsola)({
      level: this.config.enabled ? 4 : 0
    });
  }
  /**
   * Enable logging
   */
  enable() {
    this.config.enabled = true;
  }
  /**
   * Disable logging
   */
  disable() {
    this.config.enabled = false;
  }
  /**
   * Update configuration
   */
  setConfig(config) {
    this.config = { ...this.config, ...config };
  }
  /**
   * Filter sensitive headers
   */
  filterHeaders(headers) {
    if (!headers) return {};
    const filtered = {};
    Object.keys(headers).forEach((key) => {
      const lowerKey = key.toLowerCase();
      if (SENSITIVE_HEADERS2.includes(lowerKey)) {
        filtered[key] = "***";
      } else {
        filtered[key] = headers[key] || "";
      }
    });
    return filtered;
  }
  /**
   * Log request
   */
  logRequest(request) {
    if (!this.config.enabled || !this.config.logRequests) return;
    const { method, url, headers, body } = request;
    this.consola.start(`${method} ${url}`);
    if (this.config.logHeaders && headers) {
      this.consola.debug("Headers:", this.filterHeaders(headers));
    }
    if (this.config.logBodies && body) {
      this.consola.debug("Body:", body);
    }
  }
  /**
   * Log response
   */
  logResponse(request, response) {
    if (!this.config.enabled || !this.config.logResponses) return;
    const { method, url } = request;
    const { status, statusText, data, duration } = response;
    const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
    this.consola.success(
      `${method} ${url} ${status} ${statusText} (${duration}ms)`
    );
    if (this.config.logBodies && data) {
      this.consola.debug("Response:", data);
    }
  }
  /**
   * Log error
   */
  logError(request, error) {
    if (!this.config.enabled || !this.config.logErrors) return;
    const { method, url } = request;
    const { message, statusCode, fieldErrors, duration } = error;
    this.consola.error(
      `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
    );
    this.consola.error("Message:", message);
    if (fieldErrors && Object.keys(fieldErrors).length > 0) {
      this.consola.error("Field Errors:");
      Object.entries(fieldErrors).forEach(([field, errors]) => {
        errors.forEach((err) => {
          this.consola.error(`  \u2022 ${field}: ${err}`);
        });
      });
    }
  }
  /**
   * Log general info
   */
  info(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.info(message, ...args);
  }
  /**
   * Log warning
   */
  warn(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.warn(message, ...args);
  }
  /**
   * Log error
   */
  error(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.error(message, ...args);
  }
  /**
   * Log debug
   */
  debug(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.debug(message, ...args);
  }
  /**
   * Log success
   */
  success(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.success(message, ...args);
  }
  /**
   * Create a sub-logger with prefix
   */
  withTag(tag) {
    return this.consola.withTag(tag);
  }
};
var defaultLogger2 = new APILogger2();

// src/generated/cfg_centrifugo/retry.ts
var import_p_retry2 = __toESM(require("p-retry"), 1);

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelInfo.schema.ts
var import_zod22 = require("zod");
var CentrifugoChannelInfoSchema = import_zod22.z.object({
  num_clients: import_zod22.z.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsRequestRequest.schema.ts
var import_zod23 = require("zod");
var CentrifugoChannelsRequestRequestSchema = import_zod23.z.object({
  pattern: import_zod23.z.string().nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResponse.schema.ts
var import_zod26 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResult.schema.ts
var import_zod24 = require("zod");
var CentrifugoChannelsResultSchema = import_zod24.z.object({
  channels: import_zod24.z.record(import_zod24.z.string(), CentrifugoChannelInfoSchema)
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoError.schema.ts
var import_zod25 = require("zod");
var CentrifugoErrorSchema = import_zod25.z.object({
  code: import_zod25.z.int().optional(),
  message: import_zod25.z.string().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResponse.schema.ts
var CentrifugoChannelsResponseSchema = import_zod26.z.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoChannelsResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoClientInfo.schema.ts
var import_zod27 = require("zod");
var CentrifugoClientInfoSchema = import_zod27.z.object({
  user: import_zod27.z.string(),
  client: import_zod27.z.string(),
  conn_info: import_zod27.z.record(import_zod27.z.string(), import_zod27.z.any()).nullable().optional(),
  chan_info: import_zod27.z.record(import_zod27.z.string(), import_zod27.z.any()).nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHealthCheck.schema.ts
var import_zod28 = require("zod");
var CentrifugoHealthCheckSchema = import_zod28.z.object({
  status: import_zod28.z.string(),
  wrapper_url: import_zod28.z.string(),
  has_api_key: import_zod28.z.boolean(),
  timestamp: import_zod28.z.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryRequestRequest.schema.ts
var import_zod30 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoStreamPosition.schema.ts
var import_zod29 = require("zod");
var CentrifugoStreamPositionSchema = import_zod29.z.object({
  offset: import_zod29.z.int(),
  epoch: import_zod29.z.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryRequestRequest.schema.ts
var CentrifugoHistoryRequestRequestSchema = import_zod30.z.object({
  channel: import_zod30.z.string(),
  limit: import_zod30.z.int().nullable().optional(),
  since: CentrifugoStreamPositionSchema.optional(),
  reverse: import_zod30.z.boolean().nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResponse.schema.ts
var import_zod33 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResult.schema.ts
var import_zod32 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPublication.schema.ts
var import_zod31 = require("zod");
var CentrifugoPublicationSchema = import_zod31.z.object({
  data: import_zod31.z.record(import_zod31.z.string(), import_zod31.z.any()),
  info: CentrifugoClientInfoSchema.optional(),
  offset: import_zod31.z.int(),
  tags: import_zod31.z.record(import_zod31.z.string(), import_zod31.z.any()).nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResult.schema.ts
var CentrifugoHistoryResultSchema = import_zod32.z.object({
  publications: import_zod32.z.array(CentrifugoPublicationSchema),
  epoch: import_zod32.z.string(),
  offset: import_zod32.z.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResponse.schema.ts
var CentrifugoHistoryResponseSchema = import_zod33.z.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoHistoryResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResponse.schema.ts
var import_zod38 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResult.schema.ts
var import_zod37 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoNodeInfo.schema.ts
var import_zod36 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoMetrics.schema.ts
var import_zod34 = require("zod");
var CentrifugoMetricsSchema = import_zod34.z.object({
  interval: import_zod34.z.number(),
  items: import_zod34.z.record(import_zod34.z.string(), import_zod34.z.number())
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoProcess.schema.ts
var import_zod35 = require("zod");
var CentrifugoProcessSchema = import_zod35.z.object({
  cpu: import_zod35.z.number(),
  rss: import_zod35.z.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoNodeInfo.schema.ts
var CentrifugoNodeInfoSchema = import_zod36.z.object({
  uid: import_zod36.z.string(),
  name: import_zod36.z.string(),
  version: import_zod36.z.string(),
  num_clients: import_zod36.z.int(),
  num_users: import_zod36.z.int(),
  num_channels: import_zod36.z.int(),
  uptime: import_zod36.z.int(),
  num_subs: import_zod36.z.int(),
  metrics: CentrifugoMetricsSchema.optional(),
  process: CentrifugoProcessSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResult.schema.ts
var CentrifugoInfoResultSchema = import_zod37.z.object({
  nodes: import_zod37.z.array(CentrifugoNodeInfoSchema)
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResponse.schema.ts
var CentrifugoInfoResponseSchema = import_zod38.z.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoInfoResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoOverviewStats.schema.ts
var import_zod39 = require("zod");
var CentrifugoOverviewStatsSchema = import_zod39.z.object({
  total: import_zod39.z.int(),
  successful: import_zod39.z.int(),
  failed: import_zod39.z.int(),
  timeout: import_zod39.z.int(),
  success_rate: import_zod39.z.number(),
  avg_duration_ms: import_zod39.z.number(),
  avg_acks_received: import_zod39.z.number(),
  period_hours: import_zod39.z.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceRequestRequest.schema.ts
var import_zod40 = require("zod");
var CentrifugoPresenceRequestRequestSchema = import_zod40.z.object({
  channel: import_zod40.z.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResponse.schema.ts
var import_zod42 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResult.schema.ts
var import_zod41 = require("zod");
var CentrifugoPresenceResultSchema = import_zod41.z.object({
  presence: import_zod41.z.record(import_zod41.z.string(), CentrifugoClientInfoSchema)
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResponse.schema.ts
var CentrifugoPresenceResponseSchema = import_zod42.z.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoPresenceResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsRequestRequest.schema.ts
var import_zod43 = require("zod");
var CentrifugoPresenceStatsRequestRequestSchema = import_zod43.z.object({
  channel: import_zod43.z.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResponse.schema.ts
var import_zod45 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResult.schema.ts
var import_zod44 = require("zod");
var CentrifugoPresenceStatsResultSchema = import_zod44.z.object({
  num_clients: import_zod44.z.int(),
  num_users: import_zod44.z.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResponse.schema.ts
var CentrifugoPresenceStatsResponseSchema = import_zod45.z.object({
  error: CentrifugoErrorSchema.optional(),
  result: CentrifugoPresenceStatsResultSchema.optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/ChannelList.schema.ts
var import_zod47 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/ChannelStats.schema.ts
var import_zod46 = require("zod");
var ChannelStatsSchema = import_zod46.z.object({
  channel: import_zod46.z.string(),
  total: import_zod46.z.int(),
  successful: import_zod46.z.int(),
  failed: import_zod46.z.int(),
  avg_duration_ms: import_zod46.z.number(),
  avg_acks: import_zod46.z.number(),
  last_activity_at: import_zod46.z.string().nullable()
});

// src/generated/cfg_centrifugo/_utils/schemas/ChannelList.schema.ts
var ChannelListSchema = import_zod47.z.object({
  channels: import_zod47.z.array(ChannelStatsSchema),
  total_channels: import_zod47.z.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/ConnectionTokenResponse.schema.ts
var import_zod48 = require("zod");
var ConnectionTokenResponseSchema = import_zod48.z.object({
  token: import_zod48.z.string(),
  centrifugo_url: import_zod48.z.string(),
  expires_at: import_zod48.z.string(),
  channels: import_zod48.z.array(import_zod48.z.string())
});

// src/generated/cfg_centrifugo/_utils/schemas/ManualAckRequestRequest.schema.ts
var import_zod49 = require("zod");
var ManualAckRequestRequestSchema = import_zod49.z.object({
  message_id: import_zod49.z.string(),
  client_id: import_zod49.z.string()
});

// src/generated/cfg_centrifugo/_utils/schemas/ManualAckResponse.schema.ts
var import_zod50 = require("zod");
var ManualAckResponseSchema = import_zod50.z.object({
  success: import_zod50.z.boolean(),
  message_id: import_zod50.z.string(),
  error: import_zod50.z.string().nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/PaginatedPublishList.schema.ts
var import_zod52 = require("zod");

// src/generated/cfg_centrifugo/_utils/schemas/Publish.schema.ts
var import_zod51 = require("zod");
var PublishSchema = import_zod51.z.object({
  message_id: import_zod51.z.string(),
  channel: import_zod51.z.string(),
  status: import_zod51.z.string(),
  wait_for_ack: import_zod51.z.boolean(),
  acks_received: import_zod51.z.int(),
  acks_expected: import_zod51.z.int().nullable(),
  duration_ms: import_zod51.z.number().nullable(),
  created_at: import_zod51.z.string().datetime({ offset: true }),
  completed_at: import_zod51.z.string().datetime({ offset: true }).nullable(),
  error_code: import_zod51.z.string().nullable(),
  error_message: import_zod51.z.string().nullable()
});

// src/generated/cfg_centrifugo/_utils/schemas/PaginatedPublishList.schema.ts
var PaginatedPublishListSchema = import_zod52.z.object({
  count: import_zod52.z.int(),
  page: import_zod52.z.int(),
  pages: import_zod52.z.int(),
  page_size: import_zod52.z.int(),
  has_next: import_zod52.z.boolean(),
  has_previous: import_zod52.z.boolean(),
  next_page: import_zod52.z.int().nullable().optional(),
  previous_page: import_zod52.z.int().nullable().optional(),
  results: import_zod52.z.array(PublishSchema)
});

// src/generated/cfg_centrifugo/_utils/schemas/PublishTestRequestRequest.schema.ts
var import_zod53 = require("zod");
var PublishTestRequestRequestSchema = import_zod53.z.object({
  channel: import_zod53.z.string(),
  data: import_zod53.z.record(import_zod53.z.string(), import_zod53.z.any()),
  wait_for_ack: import_zod53.z.boolean().optional(),
  ack_timeout: import_zod53.z.int().min(1).max(60).optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/PublishTestResponse.schema.ts
var import_zod54 = require("zod");
var PublishTestResponseSchema = import_zod54.z.object({
  success: import_zod54.z.boolean(),
  message_id: import_zod54.z.string(),
  channel: import_zod54.z.string(),
  acks_received: import_zod54.z.int().optional(),
  delivered: import_zod54.z.boolean().optional(),
  error: import_zod54.z.string().nullable().optional()
});

// src/generated/cfg_centrifugo/_utils/schemas/TimelineItem.schema.ts
var import_zod55 = require("zod");
var TimelineItemSchema = import_zod55.z.object({
  timestamp: import_zod55.z.string(),
  count: import_zod55.z.int(),
  successful: import_zod55.z.int(),
  failed: import_zod55.z.int(),
  timeout: import_zod55.z.int()
});

// src/generated/cfg_centrifugo/_utils/schemas/TimelineResponse.schema.ts
var import_zod56 = require("zod");
var TimelineResponseSchema = import_zod56.z.object({
  timeline: import_zod56.z.array(TimelineItemSchema),
  period_hours: import_zod56.z.int(),
  interval: import_zod56.z.string()
});

// src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_admin_api.ts
var import_consola7 = require("consola");

// src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_auth.ts
var import_consola8 = require("consola");

// src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_monitoring.ts
var import_consola9 = require("consola");

// src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_testing.ts
var import_consola10 = require("consola");

// src/generated/cfg_webpush/logger.ts
var import_consola11 = require("consola");
var DEFAULT_CONFIG3 = {
  enabled: process.env.NODE_ENV !== "production",
  logRequests: true,
  logResponses: true,
  logErrors: true,
  logBodies: true,
  logHeaders: false
};
var SENSITIVE_HEADERS3 = [
  "authorization",
  "cookie",
  "set-cookie",
  "x-api-key",
  "x-csrf-token"
];
var APILogger3 = class {
  static {
    __name(this, "APILogger");
  }
  constructor(config = {}) {
    this.config = { ...DEFAULT_CONFIG3, ...config };
    this.consola = config.consola || (0, import_consola11.createConsola)({
      level: this.config.enabled ? 4 : 0
    });
  }
  /**
   * Enable logging
   */
  enable() {
    this.config.enabled = true;
  }
  /**
   * Disable logging
   */
  disable() {
    this.config.enabled = false;
  }
  /**
   * Update configuration
   */
  setConfig(config) {
    this.config = { ...this.config, ...config };
  }
  /**
   * Filter sensitive headers
   */
  filterHeaders(headers) {
    if (!headers) return {};
    const filtered = {};
    Object.keys(headers).forEach((key) => {
      const lowerKey = key.toLowerCase();
      if (SENSITIVE_HEADERS3.includes(lowerKey)) {
        filtered[key] = "***";
      } else {
        filtered[key] = headers[key] || "";
      }
    });
    return filtered;
  }
  /**
   * Log request
   */
  logRequest(request) {
    if (!this.config.enabled || !this.config.logRequests) return;
    const { method, url, headers, body } = request;
    this.consola.start(`${method} ${url}`);
    if (this.config.logHeaders && headers) {
      this.consola.debug("Headers:", this.filterHeaders(headers));
    }
    if (this.config.logBodies && body) {
      this.consola.debug("Body:", body);
    }
  }
  /**
   * Log response
   */
  logResponse(request, response) {
    if (!this.config.enabled || !this.config.logResponses) return;
    const { method, url } = request;
    const { status, statusText, data, duration } = response;
    const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
    this.consola.success(
      `${method} ${url} ${status} ${statusText} (${duration}ms)`
    );
    if (this.config.logBodies && data) {
      this.consola.debug("Response:", data);
    }
  }
  /**
   * Log error
   */
  logError(request, error) {
    if (!this.config.enabled || !this.config.logErrors) return;
    const { method, url } = request;
    const { message, statusCode, fieldErrors, duration } = error;
    this.consola.error(
      `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
    );
    this.consola.error("Message:", message);
    if (fieldErrors && Object.keys(fieldErrors).length > 0) {
      this.consola.error("Field Errors:");
      Object.entries(fieldErrors).forEach(([field, errors]) => {
        errors.forEach((err) => {
          this.consola.error(`  \u2022 ${field}: ${err}`);
        });
      });
    }
  }
  /**
   * Log general info
   */
  info(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.info(message, ...args);
  }
  /**
   * Log warning
   */
  warn(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.warn(message, ...args);
  }
  /**
   * Log error
   */
  error(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.error(message, ...args);
  }
  /**
   * Log debug
   */
  debug(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.debug(message, ...args);
  }
  /**
   * Log success
   */
  success(message, ...args) {
    if (!this.config.enabled) return;
    this.consola.success(message, ...args);
  }
  /**
   * Create a sub-logger with prefix
   */
  withTag(tag) {
    return this.consola.withTag(tag);
  }
};
var defaultLogger3 = new APILogger3();

// src/generated/cfg_webpush/retry.ts
var import_p_retry3 = __toESM(require("p-retry"), 1);

// src/generated/cfg_webpush/_utils/schemas/SendPushRequestRequest.schema.ts
var import_zod57 = require("zod");
var SendPushRequestRequestSchema = import_zod57.z.object({
  title: import_zod57.z.string().min(1).max(255),
  body: import_zod57.z.string().min(1),
  icon: import_zod57.z.union([import_zod57.z.url(), import_zod57.z.literal("")]).nullable().optional(),
  url: import_zod57.z.union([import_zod57.z.url(), import_zod57.z.literal("")]).nullable().optional()
});

// src/generated/cfg_webpush/_utils/schemas/SendPushResponse.schema.ts
var import_zod58 = require("zod");
var SendPushResponseSchema = import_zod58.z.object({
  success: import_zod58.z.boolean(),
  sent_to: import_zod58.z.int()
});

// src/generated/cfg_webpush/_utils/schemas/SubscribeRequestRequest.schema.ts
var import_zod59 = require("zod");
var SubscribeRequestRequestSchema = import_zod59.z.object({
  endpoint: import_zod59.z.union([import_zod59.z.url(), import_zod59.z.literal("")]),
  keys: import_zod59.z.record(import_zod59.z.string(), import_zod59.z.string().min(1))
});

// src/generated/cfg_webpush/_utils/schemas/SubscribeResponse.schema.ts
var import_zod60 = require("zod");
var SubscribeResponseSchema = import_zod60.z.object({
  success: import_zod60.z.boolean(),
  subscription_id: import_zod60.z.int(),
  created: import_zod60.z.boolean()
});

// src/generated/cfg_webpush/_utils/schemas/VapidPublicKeyResponse.schema.ts
var import_zod61 = require("zod");
var VapidPublicKeyResponseSchema = import_zod61.z.object({
  publicKey: import_zod61.z.string()
});

// src/generated/cfg_webpush/_utils/fetchers/webpush__web_push.ts
var import_consola12 = require("consola");

// src/index.ts
var isStaticBuild = process.env.NEXT_PUBLIC_STATIC_BUILD === "true";
var apiUrl = isStaticBuild ? "" : process.env.NEXT_PUBLIC_API_URL || "";
var api = new API(
  apiUrl,
  {
    storage: new LocalStorageAdapter()
  }
);
var BaseClient = class {
  static {
    __name(this, "BaseClient");
  }
  static {
    this.api = api;
  }
};

// src/auth/utils/logger.ts
var import_consola13 = require("consola");
var isDevelopment = process.env.NODE_ENV === "development";
var isStaticBuild2 = process.env.NEXT_PUBLIC_STATIC_BUILD === "true";
var showLogs = isDevelopment || isStaticBuild2;
var logger = (0, import_consola13.createConsola)({
  level: showLogs ? 4 : 1
  // dev: debug, production: errors only
}).withTag("api");
var authLogger = logger.withTag("auth");

// src/auth/middlewares/tokenRefresh.ts
var isRefreshing = false;
var refreshSubscribers = [];
function subscribeTokenRefresh(callback) {
  refreshSubscribers.push(callback);
}
__name(subscribeTokenRefresh, "subscribeTokenRefresh");
function onTokenRefreshed(token) {
  refreshSubscribers.forEach((callback) => callback(token));
  refreshSubscribers = [];
}
__name(onTokenRefreshed, "onTokenRefreshed");
async function refreshAccessToken() {
  if (isRefreshing) {
    return new Promise((resolve) => {
      subscribeTokenRefresh((token) => resolve(token));
    });
  }
  isRefreshing = true;
  authLogger.info("Starting token refresh...");
  try {
    const refreshToken = api.getRefreshToken();
    if (!refreshToken) {
      authLogger.warn("No refresh token available for refresh");
      onTokenRefreshed(null);
      return null;
    }
    const result = await api.auth.accountsTokenRefreshCreate({
      refresh: refreshToken
    });
    const newAccessToken = result.access;
    if (!newAccessToken) {
      authLogger.error("Token refresh response missing access token");
      onTokenRefreshed(null);
      return null;
    }
    api.setToken(newAccessToken, refreshToken);
    authLogger.info("Token refreshed successfully");
    onTokenRefreshed(newAccessToken);
    return newAccessToken;
  } catch (error) {
    authLogger.error("Token refresh error:", error);
    onTokenRefreshed(null);
    return null;
  } finally {
    isRefreshing = false;
  }
}
__name(refreshAccessToken, "refreshAccessToken");
function isAuthenticationError(response) {
  return response.status === 401;
}
__name(isAuthenticationError, "isAuthenticationError");
function createAutoRefreshFetch(originalFetch) {
  return async (input, init) => {
    let response = await originalFetch(input, init);
    if (isAuthenticationError(response) && api.getRefreshToken()) {
      authLogger.info("Received 401, attempting token refresh...");
      const newToken = await refreshAccessToken();
      if (newToken) {
        const newInit = {
          ...init,
          headers: {
            ...init?.headers,
            Authorization: `Bearer ${newToken}`
          }
        };
        authLogger.info("Retrying request with new token...");
        response = await originalFetch(input, newInit);
      } else {
        authLogger.warn("Token refresh failed, returning original 401 response");
      }
    }
    return response;
  };
}
__name(createAutoRefreshFetch, "createAutoRefreshFetch");
function isTokenExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
  const token = api.getToken();
  if (!token) return false;
  try {
    const payload = JSON.parse(atob(token.split(".")[1]));
    const expiresAt = payload.exp * 1e3;
    const now = Date.now();
    const timeUntilExpiry = expiresAt - now;
    return timeUntilExpiry < thresholdMs;
  } catch (error) {
    authLogger.error("Error checking token expiry:", error);
    return false;
  }
}
__name(isTokenExpiringSoon, "isTokenExpiringSoon");
async function refreshIfExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
  if (isTokenExpiringSoon(thresholdMs)) {
    authLogger.info("Token expiring soon, proactively refreshing...");
    await refreshAccessToken();
  }
}
__name(refreshIfExpiringSoon, "refreshIfExpiringSoon");
//# sourceMappingURL=auth-server.cjs.map