@vaiftech/client 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -5516,6 +5516,24 @@ interface AdminMemoryUpdateInput {
5516
5516
  confidence?: number;
5517
5517
  expiresAt?: string | null;
5518
5518
  }
5519
+ /**
5520
+ * Classification feedback (Admin)
5521
+ */
5522
+ interface AdminClassificationFeedback {
5523
+ id: string;
5524
+ sessionId: string;
5525
+ messageId: string;
5526
+ originalPrompt: string | null;
5527
+ classifiedIntent: string | null;
5528
+ classifiedCategory: string | null;
5529
+ originalConfidence: number | null;
5530
+ feedbackType: string;
5531
+ correctedIntent: string | null;
5532
+ userFeedback: string | null;
5533
+ wasSuccessful: boolean | null;
5534
+ classificationMethod: string | null;
5535
+ createdAt: string;
5536
+ }
5519
5537
  /**
5520
5538
  * Training data export options
5521
5539
  */
@@ -5966,6 +5984,12 @@ interface AdminModule {
5966
5984
  ok: boolean;
5967
5985
  deletedCount: number;
5968
5986
  }>;
5987
+ listClassificationFeedback(options?: AdminListOptions & {
5988
+ feedbackType?: string;
5989
+ }): Promise<{
5990
+ feedback: AdminClassificationFeedback[];
5991
+ total: number;
5992
+ }>;
5969
5993
  exportTrainingData(options?: TrainingDataExportOptions): Promise<TrainingDataExportResponse>;
5970
5994
  getTrainingDataStats(): Promise<TrainingDataStats>;
5971
5995
  listErrors(options?: AdminErrorListOptions): Promise<{
@@ -9178,4 +9202,4 @@ declare function isVaifRateLimitError(error: unknown): error is VaifRateLimitErr
9178
9202
  */
9179
9203
  declare function isVaifNetworkError(error: unknown): error is VaifNetworkError;
9180
9204
 
9181
- export { type AIModule, type AIPlan, type AIPlanStep, type AIProjectOverrides, type AISettings, type AIUsageBreakdown, type AIUsageResult, type AddBillingContactInput, type AddonsResponse, type AdminAIModel, type AdminAISession, type AdminAITurn, type AdminAIWorkspaceMessage, type AdminAIWorkspaceOverview, type AdminAIWorkspaceSession, type AdminAIWorkspaceSessionDetails, type AdminApiError, type AdminContextSnapshot, type AdminCopilotExecution, type AdminCopilotMemory, type AdminCopilotMessage, type AdminCopilotOverview, type AdminCopilotPlan, type AdminCopilotSession, type AdminCopilotSessionDetails, type AdminErrorListOptions, type AdminErrorStats, type FeatureFlag$1 as AdminFeatureFlag, type AdminGeneratedBackend, type AdminListOptions, type AdminMemoryListOptions, type AdminMemoryStats, type AdminMemoryUpdateInput, type AdminModule, type AdminOrg, type AdminOrgDetails, type AdminOrgMember, type AdminOrgProfile, type AdminOverviewResponse, type AdminProject, type AdminProjectDetails, type AdminPromptTemplate, type AdminUpdateProjectInput, type AdminUser, type AdminUserDetails, type AggregateClause, type AggregateFunction, type AggregateOptions, type AggregateResult, type AnalyticsConfig, type AndFilter, type ApiErrorResponse, type ApiKey, type ApiParam, type ApiResponse, type ApiSettingsResponse, type ApplyInput, type ApplyResponse, type AuthModule, type AuthResponse, type BaseEntity, type BatchCreateOptions, type BatchCreateResult, type BatchDeleteResult$1 as BatchDeleteResult, type BatchInvokeInput, type BatchInvokeResult, type BatchUpdateOptions, type BatchUpdateResult, type BillingContact, type BillingModule, type BillingSummary, type BootstrapData, type BootstrapEntitlements, type BootstrapModule, type BootstrapOAuthEntitlements, type BootstrapPlanLimits, type BootstrapUser, type BroadcastEvent, type BroadcastOptions, type BudgetStatus, type ChangePasswordInput, type ChangelogFeature, type ChannelOptions, type ChannelType, type CheckEntitlementInput, type CheckEntitlementResponse, type CheckoutInput, type CheckoutResponse, type ClassificationFeedbackInput, type ClassificationMethod, type ClassificationStats, type CodeLanguage, type ColumnDefinition, type ColumnType, type ComponentStatus, type ComputeSettings, type ConfigureOAuthInput, type ConnectionState, type Conversation, type ConversationMessage, type CopilotChatInput, type CopilotChatResponse, type ClarificationQuestion as CopilotClarificationQuestion, type GenerationType as CopilotGenerationType, type CopilotIntentCategory, type CopilotMessage, type CopilotModule, type CopilotPlan, type CopilotPlanStep, type CopilotSession, type CopyOptions, type CreateAIModelInput, type CreateApiKeyInput, type CreateApiKeyResponse, type CreateBucketInput, type CreateBucketOptions, type CreateConversationInput, type CreateDeployTokenInput, type CreateDeployTokenResult, type CreateDocApiEndpointInput, type CreateDocChangelogInput, type CreateDocExampleInput, type CreateDocPageInput, type CreateDocSdkExampleInput, type CreateDocSdkInput, type CreateEnvVarInput, type CreateFlagInput, type CreateFunctionInput, type CreateIncidentInput, type CreateOrgInput, type CreateProjectFromTemplateResponse, type CreateProjectInput, type CreateProjectResponse, type CreateSecretInput, type CreateSubscriptionInput, type CursorPaginationOptions, type CursorPaginationResult, type DLQListOptions, type DLQMessage, type DataModule, type DbChangeEvent, type DbOperation, type DeleteOptions, type DeleteResponse, type DeleteSecretResult, type DeliveryStatus, type DeployOptions, type DeployResult, type DeployToken, type Deployment, type DeploymentStep, type DeploymentWithSteps, type DeploymentsModule, type DiscordConfig, type DlqDelivery, type DocApiEndpoint, type DocChangelogEntry, type DocExample, type DocPage, type DocSdk, type DocSdkExample, type DocSearchResult, type DocsModule, type DownloadOptions, type EmailConfig, type EmailVerificationConfirmInput, type EmailVerificationRequestInput, type EnableAllRealtimeInput, type EnableAllRealtimeResult, type EntitlementsResponse, type EnvVar, type Environment, type ErrorContext, type ErrorEvent, type ErrorInterceptor, type Event, type EventFilter, type EventHandler, type EventSource, type ExampleEndpoint, type ExampleFunction, type ExampleRealtimeEvent, type ExecutePlanInput, type ExecutePlanResult, type ExplainPlanInput, type ExplainPlanResult, type ExportCodeInput, type ExportCodeResult, type ExtractedEntity, type FeatureFlag, type FileMetadata, type FlagsModule, type FunctionEnvVar, type FunctionInvocation, type FunctionLog, type RetryConfig as FunctionRetryConfig, type FunctionRuntime, type FunctionVersion, type FunctionsModule, type GenerateEndpointInput, type GenerateEndpointResult, type GenerateFunctionInput, type GenerateFunctionResult, type GeneratePlanInput, type GeneratePlanResult, type GeneratedArtifacts, type GeneratedFile, type GetProjectResponse, type HttpMethod, type ImageTransformOptions, type IncidentAlert, type IncidentSeverity, type IncidentStatus, type IncludeClause, type IndexDefinition, type InstallApplyResponse, type InstallPreviewResponse, type InstallRealtimeInput, type InstallRealtimeResult, type IntegrationsModule, type IntentClassification, type InterceptorConfig, type InviteMemberInput, type InvokeInput, type InvokeOptions, type InvokeResult, type IsolationLevel, type ItemResponse, type JwtSettingsResponse, type ListDeliveriesOptions, type ListEventsOptions, type ListFilesOptions, type ListFilesResponse, type ListFunctionsOptions, type ListInvocationsOptions, type ListResponse, type LoginOptions, type MFAChallenge, type MFAMethod, type MFASetupResponse, type MFAVerifyResponse, type MagicLinkRequestInput, type MagicLinkVerifyInput, type MessageRole, type Migration, type MigrationResult, type Mode, type MongoAggregateOptions, type MongoArrayOperator, type MongoCollectionClient, type MongoComparisonOperator, type MongoCursor, type MongoDBModule, type MongoDeleteResult, type MongoDistinctOptions, type MongoElementOperator, type MongoEvaluationOperator, type MongoFilter, type MongoFindAndModifyResult, type MongoFindOneAndDeleteOptions, type MongoFindOneAndUpdateOptions, type MongoFindOptions, type MongoInsertManyResult, type MongoInsertOneResult, type MongoLogicalOperator, type MongoPipelineStage, type MongoProjection, type MongoSort, type MongoUpdateOperators, type MongoUpdateOptions, type MongoUpdateResult, type MoveOptions, type MultipartUpload, type MultipartUploadOptions, type NotFilter, type OAuthCallbackInput, type OAuthConnection, type OAuthModule, type OAuthProvider, type OAuthProviderType, type OAuthSignInOptions, type OAuthSignInResponse, type OrFilter, type OrderByClause, type Org, type OrgBilling, type OrgMember, type OrgMembership, type OrgProfile, type OrgsModule, type PageInfo, type PaginatedResult, type PasswordResetConfirmInput, type PasswordResetRequestInput, type PendingInvite, type PhoneVerificationConfirmInput, type PhoneVerificationRequestInput, type PlanDefinition, type PlanLimits, type PlanName, type PlanStep, type PlansResponse, type PortalInput, type PortalResponse, type PresenceEntry, type PresenceEvent, type PresenceState, type PresenceStateEvent, type PresenceTrackOptions, type PresignedUrl, type PreviewInput, type PreviewResponse, type Project, type ProjectMetrics, type ProjectResource, type ProjectResourcesResponse, type ProjectStats, type ProjectsModule, type PromoteInput, type PromoteResult, type Provider, type PublishEventInput, type PublishEventResult, type QueryOptions, type QueueStats, type QueueTotals, type RealtimeChannel, type RealtimeClient, type RealtimeClientEvent, type RealtimeConfig, type RealtimeConnection, type RealtimeEvent, type RealtimeEventType, type RealtimeMonitoringEvent, type RealtimeMonitoringModule, type RealtimeStats, type RealtimeStatus, type RealtimeSubscription, type RefreshTokenResponse, type Region, type RequestContext, type RequestInterceptor, type ResponseContext, type ResponseInterceptor, type RetryConfig$1 as RetryConfig, type RollbackResult, type SaveSchemaInput, type SavedSchema, type ScheduleConfig, type SchemaDefinition, type SchemaModule, type Secret, type SecretsModule, type SecurityAuditLog, type SecurityModule, type SecurityOverview, type SendMessageInput, type Session, type SetDedicatedDbInput, type SignUpOptions, type SignedUrlResponse, type SlackConfig, type StandardEventName, type StatusComponent, type StorageBucket, type StorageDashboardModule, type StorageFile, type StorageModule, type SubscribeOptions, type Subscription, type SubscriptionConfig, type SubscriptionFilter, type SubscriptionType, type SuperAdmin, type SystemInfo, type SystemSetting, type TableClient, type TableDefinition, type TaskType, type Template, type TemplateCategory, type TemplateDefinition, type TemplateVersion, type TemplateVisibility, type TemplatesModule, type TrainingDataExportOptions, type TrainingDataExportResponse, type TrainingDataStats, type TransactionOperation, type TransactionOptions, type TransactionResult, type TypedEventHandler, type TypedFunction, type UnsubscribeFn, type UpdateAIModelInput, type UpdateAIProjectOverridesInput, type UpdateAISettingsInput, type UpdateApiSettingsInput, type UpdateBucketInput, type UpdateBucketOptions, type UpdateComponentStatusInput, type UpdateComputeSettingsInput, type UpdateDocPageInput, type UpdateDocSdkInput, type UpdateEnvVarInput, type UpdateFlagInput, type UpdateFunctionInput, type UpdateJwtSettingsInput, type UpdateOAuthInput, type UpdateOrgProfileInput, type UpdateProfileInput, type UpdateProjectInput, type UpdateRegionInput, type UpdateSubscriptionInput, type UploadFromUrlOptions, type UploadOptions, type UploadPart, type UploadResult$1 as UploadResult, type UpsertOptions, type Usage, type UsageEntry, type User, type UserActivity, type UserMembership, VaifAuthError, type VaifClient, type VaifClientConfig, VaifConflictError, VaifError, type VaifFunction, VaifNetworkError, VaifNotFoundError, VaifRateLimitError, VaifTimeoutError, VaifValidationError, type VerifySignatureOptions, type WebhookConfig, type WebhookDelivery, type WelcomeEvent, type WhereClause, type WhereFilter, type WhereOperator, createVaifClient, isVaifAuthError, isVaifError, isVaifNetworkError, isVaifNotFoundError, isVaifRateLimitError, isVaifValidationError };
9205
+ export { type AIModule, type AIPlan, type AIPlanStep, type AIProjectOverrides, type AISettings, type AIUsageBreakdown, type AIUsageResult, type AddBillingContactInput, type AddonsResponse, type AdminAIModel, type AdminAISession, type AdminAITurn, type AdminAIWorkspaceMessage, type AdminAIWorkspaceOverview, type AdminAIWorkspaceSession, type AdminAIWorkspaceSessionDetails, type AdminApiError, type AdminClassificationFeedback, type AdminContextSnapshot, type AdminCopilotExecution, type AdminCopilotMemory, type AdminCopilotMessage, type AdminCopilotOverview, type AdminCopilotPlan, type AdminCopilotSession, type AdminCopilotSessionDetails, type AdminErrorListOptions, type AdminErrorStats, type FeatureFlag$1 as AdminFeatureFlag, type AdminGeneratedBackend, type AdminListOptions, type AdminMemoryListOptions, type AdminMemoryStats, type AdminMemoryUpdateInput, type AdminModule, type AdminOrg, type AdminOrgDetails, type AdminOrgMember, type AdminOrgProfile, type AdminOverviewResponse, type AdminProject, type AdminProjectDetails, type AdminPromptTemplate, type AdminUpdateProjectInput, type AdminUser, type AdminUserDetails, type AggregateClause, type AggregateFunction, type AggregateOptions, type AggregateResult, type AnalyticsConfig, type AndFilter, type ApiErrorResponse, type ApiKey, type ApiParam, type ApiResponse, type ApiSettingsResponse, type ApplyInput, type ApplyResponse, type AuthModule, type AuthResponse, type BaseEntity, type BatchCreateOptions, type BatchCreateResult, type BatchDeleteResult$1 as BatchDeleteResult, type BatchInvokeInput, type BatchInvokeResult, type BatchUpdateOptions, type BatchUpdateResult, type BillingContact, type BillingModule, type BillingSummary, type BootstrapData, type BootstrapEntitlements, type BootstrapModule, type BootstrapOAuthEntitlements, type BootstrapPlanLimits, type BootstrapUser, type BroadcastEvent, type BroadcastOptions, type BudgetStatus, type ChangePasswordInput, type ChangelogFeature, type ChannelOptions, type ChannelType, type CheckEntitlementInput, type CheckEntitlementResponse, type CheckoutInput, type CheckoutResponse, type ClassificationFeedbackInput, type ClassificationMethod, type ClassificationStats, type CodeLanguage, type ColumnDefinition, type ColumnType, type ComponentStatus, type ComputeSettings, type ConfigureOAuthInput, type ConnectionState, type Conversation, type ConversationMessage, type CopilotChatInput, type CopilotChatResponse, type ClarificationQuestion as CopilotClarificationQuestion, type GenerationType as CopilotGenerationType, type CopilotIntentCategory, type CopilotMessage, type CopilotModule, type CopilotPlan, type CopilotPlanStep, type CopilotSession, type CopyOptions, type CreateAIModelInput, type CreateApiKeyInput, type CreateApiKeyResponse, type CreateBucketInput, type CreateBucketOptions, type CreateConversationInput, type CreateDeployTokenInput, type CreateDeployTokenResult, type CreateDocApiEndpointInput, type CreateDocChangelogInput, type CreateDocExampleInput, type CreateDocPageInput, type CreateDocSdkExampleInput, type CreateDocSdkInput, type CreateEnvVarInput, type CreateFlagInput, type CreateFunctionInput, type CreateIncidentInput, type CreateOrgInput, type CreateProjectFromTemplateResponse, type CreateProjectInput, type CreateProjectResponse, type CreateSecretInput, type CreateSubscriptionInput, type CursorPaginationOptions, type CursorPaginationResult, type DLQListOptions, type DLQMessage, type DataModule, type DbChangeEvent, type DbOperation, type DeleteOptions, type DeleteResponse, type DeleteSecretResult, type DeliveryStatus, type DeployOptions, type DeployResult, type DeployToken, type Deployment, type DeploymentStep, type DeploymentWithSteps, type DeploymentsModule, type DiscordConfig, type DlqDelivery, type DocApiEndpoint, type DocChangelogEntry, type DocExample, type DocPage, type DocSdk, type DocSdkExample, type DocSearchResult, type DocsModule, type DownloadOptions, type EmailConfig, type EmailVerificationConfirmInput, type EmailVerificationRequestInput, type EnableAllRealtimeInput, type EnableAllRealtimeResult, type EntitlementsResponse, type EnvVar, type Environment, type ErrorContext, type ErrorEvent, type ErrorInterceptor, type Event, type EventFilter, type EventHandler, type EventSource, type ExampleEndpoint, type ExampleFunction, type ExampleRealtimeEvent, type ExecutePlanInput, type ExecutePlanResult, type ExplainPlanInput, type ExplainPlanResult, type ExportCodeInput, type ExportCodeResult, type ExtractedEntity, type FeatureFlag, type FileMetadata, type FlagsModule, type FunctionEnvVar, type FunctionInvocation, type FunctionLog, type RetryConfig as FunctionRetryConfig, type FunctionRuntime, type FunctionVersion, type FunctionsModule, type GenerateEndpointInput, type GenerateEndpointResult, type GenerateFunctionInput, type GenerateFunctionResult, type GeneratePlanInput, type GeneratePlanResult, type GeneratedArtifacts, type GeneratedFile, type GetProjectResponse, type HttpMethod, type ImageTransformOptions, type IncidentAlert, type IncidentSeverity, type IncidentStatus, type IncludeClause, type IndexDefinition, type InstallApplyResponse, type InstallPreviewResponse, type InstallRealtimeInput, type InstallRealtimeResult, type IntegrationsModule, type IntentClassification, type InterceptorConfig, type InviteMemberInput, type InvokeInput, type InvokeOptions, type InvokeResult, type IsolationLevel, type ItemResponse, type JwtSettingsResponse, type ListDeliveriesOptions, type ListEventsOptions, type ListFilesOptions, type ListFilesResponse, type ListFunctionsOptions, type ListInvocationsOptions, type ListResponse, type LoginOptions, type MFAChallenge, type MFAMethod, type MFASetupResponse, type MFAVerifyResponse, type MagicLinkRequestInput, type MagicLinkVerifyInput, type MessageRole, type Migration, type MigrationResult, type Mode, type MongoAggregateOptions, type MongoArrayOperator, type MongoCollectionClient, type MongoComparisonOperator, type MongoCursor, type MongoDBModule, type MongoDeleteResult, type MongoDistinctOptions, type MongoElementOperator, type MongoEvaluationOperator, type MongoFilter, type MongoFindAndModifyResult, type MongoFindOneAndDeleteOptions, type MongoFindOneAndUpdateOptions, type MongoFindOptions, type MongoInsertManyResult, type MongoInsertOneResult, type MongoLogicalOperator, type MongoPipelineStage, type MongoProjection, type MongoSort, type MongoUpdateOperators, type MongoUpdateOptions, type MongoUpdateResult, type MoveOptions, type MultipartUpload, type MultipartUploadOptions, type NotFilter, type OAuthCallbackInput, type OAuthConnection, type OAuthModule, type OAuthProvider, type OAuthProviderType, type OAuthSignInOptions, type OAuthSignInResponse, type OrFilter, type OrderByClause, type Org, type OrgBilling, type OrgMember, type OrgMembership, type OrgProfile, type OrgsModule, type PageInfo, type PaginatedResult, type PasswordResetConfirmInput, type PasswordResetRequestInput, type PendingInvite, type PhoneVerificationConfirmInput, type PhoneVerificationRequestInput, type PlanDefinition, type PlanLimits, type PlanName, type PlanStep, type PlansResponse, type PortalInput, type PortalResponse, type PresenceEntry, type PresenceEvent, type PresenceState, type PresenceStateEvent, type PresenceTrackOptions, type PresignedUrl, type PreviewInput, type PreviewResponse, type Project, type ProjectMetrics, type ProjectResource, type ProjectResourcesResponse, type ProjectStats, type ProjectsModule, type PromoteInput, type PromoteResult, type Provider, type PublishEventInput, type PublishEventResult, type QueryOptions, type QueueStats, type QueueTotals, type RealtimeChannel, type RealtimeClient, type RealtimeClientEvent, type RealtimeConfig, type RealtimeConnection, type RealtimeEvent, type RealtimeEventType, type RealtimeMonitoringEvent, type RealtimeMonitoringModule, type RealtimeStats, type RealtimeStatus, type RealtimeSubscription, type RefreshTokenResponse, type Region, type RequestContext, type RequestInterceptor, type ResponseContext, type ResponseInterceptor, type RetryConfig$1 as RetryConfig, type RollbackResult, type SaveSchemaInput, type SavedSchema, type ScheduleConfig, type SchemaDefinition, type SchemaModule, type Secret, type SecretsModule, type SecurityAuditLog, type SecurityModule, type SecurityOverview, type SendMessageInput, type Session, type SetDedicatedDbInput, type SignUpOptions, type SignedUrlResponse, type SlackConfig, type StandardEventName, type StatusComponent, type StorageBucket, type StorageDashboardModule, type StorageFile, type StorageModule, type SubscribeOptions, type Subscription, type SubscriptionConfig, type SubscriptionFilter, type SubscriptionType, type SuperAdmin, type SystemInfo, type SystemSetting, type TableClient, type TableDefinition, type TaskType, type Template, type TemplateCategory, type TemplateDefinition, type TemplateVersion, type TemplateVisibility, type TemplatesModule, type TrainingDataExportOptions, type TrainingDataExportResponse, type TrainingDataStats, type TransactionOperation, type TransactionOptions, type TransactionResult, type TypedEventHandler, type TypedFunction, type UnsubscribeFn, type UpdateAIModelInput, type UpdateAIProjectOverridesInput, type UpdateAISettingsInput, type UpdateApiSettingsInput, type UpdateBucketInput, type UpdateBucketOptions, type UpdateComponentStatusInput, type UpdateComputeSettingsInput, type UpdateDocPageInput, type UpdateDocSdkInput, type UpdateEnvVarInput, type UpdateFlagInput, type UpdateFunctionInput, type UpdateJwtSettingsInput, type UpdateOAuthInput, type UpdateOrgProfileInput, type UpdateProfileInput, type UpdateProjectInput, type UpdateRegionInput, type UpdateSubscriptionInput, type UploadFromUrlOptions, type UploadOptions, type UploadPart, type UploadResult$1 as UploadResult, type UpsertOptions, type Usage, type UsageEntry, type User, type UserActivity, type UserMembership, VaifAuthError, type VaifClient, type VaifClientConfig, VaifConflictError, VaifError, type VaifFunction, VaifNetworkError, VaifNotFoundError, VaifRateLimitError, VaifTimeoutError, VaifValidationError, type VerifySignatureOptions, type WebhookConfig, type WebhookDelivery, type WelcomeEvent, type WhereClause, type WhereFilter, type WhereOperator, createVaifClient, isVaifAuthError, isVaifError, isVaifNetworkError, isVaifNotFoundError, isVaifRateLimitError, isVaifValidationError };
package/dist/index.d.ts CHANGED
@@ -5516,6 +5516,24 @@ interface AdminMemoryUpdateInput {
5516
5516
  confidence?: number;
5517
5517
  expiresAt?: string | null;
5518
5518
  }
5519
+ /**
5520
+ * Classification feedback (Admin)
5521
+ */
5522
+ interface AdminClassificationFeedback {
5523
+ id: string;
5524
+ sessionId: string;
5525
+ messageId: string;
5526
+ originalPrompt: string | null;
5527
+ classifiedIntent: string | null;
5528
+ classifiedCategory: string | null;
5529
+ originalConfidence: number | null;
5530
+ feedbackType: string;
5531
+ correctedIntent: string | null;
5532
+ userFeedback: string | null;
5533
+ wasSuccessful: boolean | null;
5534
+ classificationMethod: string | null;
5535
+ createdAt: string;
5536
+ }
5519
5537
  /**
5520
5538
  * Training data export options
5521
5539
  */
@@ -5966,6 +5984,12 @@ interface AdminModule {
5966
5984
  ok: boolean;
5967
5985
  deletedCount: number;
5968
5986
  }>;
5987
+ listClassificationFeedback(options?: AdminListOptions & {
5988
+ feedbackType?: string;
5989
+ }): Promise<{
5990
+ feedback: AdminClassificationFeedback[];
5991
+ total: number;
5992
+ }>;
5969
5993
  exportTrainingData(options?: TrainingDataExportOptions): Promise<TrainingDataExportResponse>;
5970
5994
  getTrainingDataStats(): Promise<TrainingDataStats>;
5971
5995
  listErrors(options?: AdminErrorListOptions): Promise<{
@@ -9178,4 +9202,4 @@ declare function isVaifRateLimitError(error: unknown): error is VaifRateLimitErr
9178
9202
  */
9179
9203
  declare function isVaifNetworkError(error: unknown): error is VaifNetworkError;
9180
9204
 
9181
- export { type AIModule, type AIPlan, type AIPlanStep, type AIProjectOverrides, type AISettings, type AIUsageBreakdown, type AIUsageResult, type AddBillingContactInput, type AddonsResponse, type AdminAIModel, type AdminAISession, type AdminAITurn, type AdminAIWorkspaceMessage, type AdminAIWorkspaceOverview, type AdminAIWorkspaceSession, type AdminAIWorkspaceSessionDetails, type AdminApiError, type AdminContextSnapshot, type AdminCopilotExecution, type AdminCopilotMemory, type AdminCopilotMessage, type AdminCopilotOverview, type AdminCopilotPlan, type AdminCopilotSession, type AdminCopilotSessionDetails, type AdminErrorListOptions, type AdminErrorStats, type FeatureFlag$1 as AdminFeatureFlag, type AdminGeneratedBackend, type AdminListOptions, type AdminMemoryListOptions, type AdminMemoryStats, type AdminMemoryUpdateInput, type AdminModule, type AdminOrg, type AdminOrgDetails, type AdminOrgMember, type AdminOrgProfile, type AdminOverviewResponse, type AdminProject, type AdminProjectDetails, type AdminPromptTemplate, type AdminUpdateProjectInput, type AdminUser, type AdminUserDetails, type AggregateClause, type AggregateFunction, type AggregateOptions, type AggregateResult, type AnalyticsConfig, type AndFilter, type ApiErrorResponse, type ApiKey, type ApiParam, type ApiResponse, type ApiSettingsResponse, type ApplyInput, type ApplyResponse, type AuthModule, type AuthResponse, type BaseEntity, type BatchCreateOptions, type BatchCreateResult, type BatchDeleteResult$1 as BatchDeleteResult, type BatchInvokeInput, type BatchInvokeResult, type BatchUpdateOptions, type BatchUpdateResult, type BillingContact, type BillingModule, type BillingSummary, type BootstrapData, type BootstrapEntitlements, type BootstrapModule, type BootstrapOAuthEntitlements, type BootstrapPlanLimits, type BootstrapUser, type BroadcastEvent, type BroadcastOptions, type BudgetStatus, type ChangePasswordInput, type ChangelogFeature, type ChannelOptions, type ChannelType, type CheckEntitlementInput, type CheckEntitlementResponse, type CheckoutInput, type CheckoutResponse, type ClassificationFeedbackInput, type ClassificationMethod, type ClassificationStats, type CodeLanguage, type ColumnDefinition, type ColumnType, type ComponentStatus, type ComputeSettings, type ConfigureOAuthInput, type ConnectionState, type Conversation, type ConversationMessage, type CopilotChatInput, type CopilotChatResponse, type ClarificationQuestion as CopilotClarificationQuestion, type GenerationType as CopilotGenerationType, type CopilotIntentCategory, type CopilotMessage, type CopilotModule, type CopilotPlan, type CopilotPlanStep, type CopilotSession, type CopyOptions, type CreateAIModelInput, type CreateApiKeyInput, type CreateApiKeyResponse, type CreateBucketInput, type CreateBucketOptions, type CreateConversationInput, type CreateDeployTokenInput, type CreateDeployTokenResult, type CreateDocApiEndpointInput, type CreateDocChangelogInput, type CreateDocExampleInput, type CreateDocPageInput, type CreateDocSdkExampleInput, type CreateDocSdkInput, type CreateEnvVarInput, type CreateFlagInput, type CreateFunctionInput, type CreateIncidentInput, type CreateOrgInput, type CreateProjectFromTemplateResponse, type CreateProjectInput, type CreateProjectResponse, type CreateSecretInput, type CreateSubscriptionInput, type CursorPaginationOptions, type CursorPaginationResult, type DLQListOptions, type DLQMessage, type DataModule, type DbChangeEvent, type DbOperation, type DeleteOptions, type DeleteResponse, type DeleteSecretResult, type DeliveryStatus, type DeployOptions, type DeployResult, type DeployToken, type Deployment, type DeploymentStep, type DeploymentWithSteps, type DeploymentsModule, type DiscordConfig, type DlqDelivery, type DocApiEndpoint, type DocChangelogEntry, type DocExample, type DocPage, type DocSdk, type DocSdkExample, type DocSearchResult, type DocsModule, type DownloadOptions, type EmailConfig, type EmailVerificationConfirmInput, type EmailVerificationRequestInput, type EnableAllRealtimeInput, type EnableAllRealtimeResult, type EntitlementsResponse, type EnvVar, type Environment, type ErrorContext, type ErrorEvent, type ErrorInterceptor, type Event, type EventFilter, type EventHandler, type EventSource, type ExampleEndpoint, type ExampleFunction, type ExampleRealtimeEvent, type ExecutePlanInput, type ExecutePlanResult, type ExplainPlanInput, type ExplainPlanResult, type ExportCodeInput, type ExportCodeResult, type ExtractedEntity, type FeatureFlag, type FileMetadata, type FlagsModule, type FunctionEnvVar, type FunctionInvocation, type FunctionLog, type RetryConfig as FunctionRetryConfig, type FunctionRuntime, type FunctionVersion, type FunctionsModule, type GenerateEndpointInput, type GenerateEndpointResult, type GenerateFunctionInput, type GenerateFunctionResult, type GeneratePlanInput, type GeneratePlanResult, type GeneratedArtifacts, type GeneratedFile, type GetProjectResponse, type HttpMethod, type ImageTransformOptions, type IncidentAlert, type IncidentSeverity, type IncidentStatus, type IncludeClause, type IndexDefinition, type InstallApplyResponse, type InstallPreviewResponse, type InstallRealtimeInput, type InstallRealtimeResult, type IntegrationsModule, type IntentClassification, type InterceptorConfig, type InviteMemberInput, type InvokeInput, type InvokeOptions, type InvokeResult, type IsolationLevel, type ItemResponse, type JwtSettingsResponse, type ListDeliveriesOptions, type ListEventsOptions, type ListFilesOptions, type ListFilesResponse, type ListFunctionsOptions, type ListInvocationsOptions, type ListResponse, type LoginOptions, type MFAChallenge, type MFAMethod, type MFASetupResponse, type MFAVerifyResponse, type MagicLinkRequestInput, type MagicLinkVerifyInput, type MessageRole, type Migration, type MigrationResult, type Mode, type MongoAggregateOptions, type MongoArrayOperator, type MongoCollectionClient, type MongoComparisonOperator, type MongoCursor, type MongoDBModule, type MongoDeleteResult, type MongoDistinctOptions, type MongoElementOperator, type MongoEvaluationOperator, type MongoFilter, type MongoFindAndModifyResult, type MongoFindOneAndDeleteOptions, type MongoFindOneAndUpdateOptions, type MongoFindOptions, type MongoInsertManyResult, type MongoInsertOneResult, type MongoLogicalOperator, type MongoPipelineStage, type MongoProjection, type MongoSort, type MongoUpdateOperators, type MongoUpdateOptions, type MongoUpdateResult, type MoveOptions, type MultipartUpload, type MultipartUploadOptions, type NotFilter, type OAuthCallbackInput, type OAuthConnection, type OAuthModule, type OAuthProvider, type OAuthProviderType, type OAuthSignInOptions, type OAuthSignInResponse, type OrFilter, type OrderByClause, type Org, type OrgBilling, type OrgMember, type OrgMembership, type OrgProfile, type OrgsModule, type PageInfo, type PaginatedResult, type PasswordResetConfirmInput, type PasswordResetRequestInput, type PendingInvite, type PhoneVerificationConfirmInput, type PhoneVerificationRequestInput, type PlanDefinition, type PlanLimits, type PlanName, type PlanStep, type PlansResponse, type PortalInput, type PortalResponse, type PresenceEntry, type PresenceEvent, type PresenceState, type PresenceStateEvent, type PresenceTrackOptions, type PresignedUrl, type PreviewInput, type PreviewResponse, type Project, type ProjectMetrics, type ProjectResource, type ProjectResourcesResponse, type ProjectStats, type ProjectsModule, type PromoteInput, type PromoteResult, type Provider, type PublishEventInput, type PublishEventResult, type QueryOptions, type QueueStats, type QueueTotals, type RealtimeChannel, type RealtimeClient, type RealtimeClientEvent, type RealtimeConfig, type RealtimeConnection, type RealtimeEvent, type RealtimeEventType, type RealtimeMonitoringEvent, type RealtimeMonitoringModule, type RealtimeStats, type RealtimeStatus, type RealtimeSubscription, type RefreshTokenResponse, type Region, type RequestContext, type RequestInterceptor, type ResponseContext, type ResponseInterceptor, type RetryConfig$1 as RetryConfig, type RollbackResult, type SaveSchemaInput, type SavedSchema, type ScheduleConfig, type SchemaDefinition, type SchemaModule, type Secret, type SecretsModule, type SecurityAuditLog, type SecurityModule, type SecurityOverview, type SendMessageInput, type Session, type SetDedicatedDbInput, type SignUpOptions, type SignedUrlResponse, type SlackConfig, type StandardEventName, type StatusComponent, type StorageBucket, type StorageDashboardModule, type StorageFile, type StorageModule, type SubscribeOptions, type Subscription, type SubscriptionConfig, type SubscriptionFilter, type SubscriptionType, type SuperAdmin, type SystemInfo, type SystemSetting, type TableClient, type TableDefinition, type TaskType, type Template, type TemplateCategory, type TemplateDefinition, type TemplateVersion, type TemplateVisibility, type TemplatesModule, type TrainingDataExportOptions, type TrainingDataExportResponse, type TrainingDataStats, type TransactionOperation, type TransactionOptions, type TransactionResult, type TypedEventHandler, type TypedFunction, type UnsubscribeFn, type UpdateAIModelInput, type UpdateAIProjectOverridesInput, type UpdateAISettingsInput, type UpdateApiSettingsInput, type UpdateBucketInput, type UpdateBucketOptions, type UpdateComponentStatusInput, type UpdateComputeSettingsInput, type UpdateDocPageInput, type UpdateDocSdkInput, type UpdateEnvVarInput, type UpdateFlagInput, type UpdateFunctionInput, type UpdateJwtSettingsInput, type UpdateOAuthInput, type UpdateOrgProfileInput, type UpdateProfileInput, type UpdateProjectInput, type UpdateRegionInput, type UpdateSubscriptionInput, type UploadFromUrlOptions, type UploadOptions, type UploadPart, type UploadResult$1 as UploadResult, type UpsertOptions, type Usage, type UsageEntry, type User, type UserActivity, type UserMembership, VaifAuthError, type VaifClient, type VaifClientConfig, VaifConflictError, VaifError, type VaifFunction, VaifNetworkError, VaifNotFoundError, VaifRateLimitError, VaifTimeoutError, VaifValidationError, type VerifySignatureOptions, type WebhookConfig, type WebhookDelivery, type WelcomeEvent, type WhereClause, type WhereFilter, type WhereOperator, createVaifClient, isVaifAuthError, isVaifError, isVaifNetworkError, isVaifNotFoundError, isVaifRateLimitError, isVaifValidationError };
9205
+ export { type AIModule, type AIPlan, type AIPlanStep, type AIProjectOverrides, type AISettings, type AIUsageBreakdown, type AIUsageResult, type AddBillingContactInput, type AddonsResponse, type AdminAIModel, type AdminAISession, type AdminAITurn, type AdminAIWorkspaceMessage, type AdminAIWorkspaceOverview, type AdminAIWorkspaceSession, type AdminAIWorkspaceSessionDetails, type AdminApiError, type AdminClassificationFeedback, type AdminContextSnapshot, type AdminCopilotExecution, type AdminCopilotMemory, type AdminCopilotMessage, type AdminCopilotOverview, type AdminCopilotPlan, type AdminCopilotSession, type AdminCopilotSessionDetails, type AdminErrorListOptions, type AdminErrorStats, type FeatureFlag$1 as AdminFeatureFlag, type AdminGeneratedBackend, type AdminListOptions, type AdminMemoryListOptions, type AdminMemoryStats, type AdminMemoryUpdateInput, type AdminModule, type AdminOrg, type AdminOrgDetails, type AdminOrgMember, type AdminOrgProfile, type AdminOverviewResponse, type AdminProject, type AdminProjectDetails, type AdminPromptTemplate, type AdminUpdateProjectInput, type AdminUser, type AdminUserDetails, type AggregateClause, type AggregateFunction, type AggregateOptions, type AggregateResult, type AnalyticsConfig, type AndFilter, type ApiErrorResponse, type ApiKey, type ApiParam, type ApiResponse, type ApiSettingsResponse, type ApplyInput, type ApplyResponse, type AuthModule, type AuthResponse, type BaseEntity, type BatchCreateOptions, type BatchCreateResult, type BatchDeleteResult$1 as BatchDeleteResult, type BatchInvokeInput, type BatchInvokeResult, type BatchUpdateOptions, type BatchUpdateResult, type BillingContact, type BillingModule, type BillingSummary, type BootstrapData, type BootstrapEntitlements, type BootstrapModule, type BootstrapOAuthEntitlements, type BootstrapPlanLimits, type BootstrapUser, type BroadcastEvent, type BroadcastOptions, type BudgetStatus, type ChangePasswordInput, type ChangelogFeature, type ChannelOptions, type ChannelType, type CheckEntitlementInput, type CheckEntitlementResponse, type CheckoutInput, type CheckoutResponse, type ClassificationFeedbackInput, type ClassificationMethod, type ClassificationStats, type CodeLanguage, type ColumnDefinition, type ColumnType, type ComponentStatus, type ComputeSettings, type ConfigureOAuthInput, type ConnectionState, type Conversation, type ConversationMessage, type CopilotChatInput, type CopilotChatResponse, type ClarificationQuestion as CopilotClarificationQuestion, type GenerationType as CopilotGenerationType, type CopilotIntentCategory, type CopilotMessage, type CopilotModule, type CopilotPlan, type CopilotPlanStep, type CopilotSession, type CopyOptions, type CreateAIModelInput, type CreateApiKeyInput, type CreateApiKeyResponse, type CreateBucketInput, type CreateBucketOptions, type CreateConversationInput, type CreateDeployTokenInput, type CreateDeployTokenResult, type CreateDocApiEndpointInput, type CreateDocChangelogInput, type CreateDocExampleInput, type CreateDocPageInput, type CreateDocSdkExampleInput, type CreateDocSdkInput, type CreateEnvVarInput, type CreateFlagInput, type CreateFunctionInput, type CreateIncidentInput, type CreateOrgInput, type CreateProjectFromTemplateResponse, type CreateProjectInput, type CreateProjectResponse, type CreateSecretInput, type CreateSubscriptionInput, type CursorPaginationOptions, type CursorPaginationResult, type DLQListOptions, type DLQMessage, type DataModule, type DbChangeEvent, type DbOperation, type DeleteOptions, type DeleteResponse, type DeleteSecretResult, type DeliveryStatus, type DeployOptions, type DeployResult, type DeployToken, type Deployment, type DeploymentStep, type DeploymentWithSteps, type DeploymentsModule, type DiscordConfig, type DlqDelivery, type DocApiEndpoint, type DocChangelogEntry, type DocExample, type DocPage, type DocSdk, type DocSdkExample, type DocSearchResult, type DocsModule, type DownloadOptions, type EmailConfig, type EmailVerificationConfirmInput, type EmailVerificationRequestInput, type EnableAllRealtimeInput, type EnableAllRealtimeResult, type EntitlementsResponse, type EnvVar, type Environment, type ErrorContext, type ErrorEvent, type ErrorInterceptor, type Event, type EventFilter, type EventHandler, type EventSource, type ExampleEndpoint, type ExampleFunction, type ExampleRealtimeEvent, type ExecutePlanInput, type ExecutePlanResult, type ExplainPlanInput, type ExplainPlanResult, type ExportCodeInput, type ExportCodeResult, type ExtractedEntity, type FeatureFlag, type FileMetadata, type FlagsModule, type FunctionEnvVar, type FunctionInvocation, type FunctionLog, type RetryConfig as FunctionRetryConfig, type FunctionRuntime, type FunctionVersion, type FunctionsModule, type GenerateEndpointInput, type GenerateEndpointResult, type GenerateFunctionInput, type GenerateFunctionResult, type GeneratePlanInput, type GeneratePlanResult, type GeneratedArtifacts, type GeneratedFile, type GetProjectResponse, type HttpMethod, type ImageTransformOptions, type IncidentAlert, type IncidentSeverity, type IncidentStatus, type IncludeClause, type IndexDefinition, type InstallApplyResponse, type InstallPreviewResponse, type InstallRealtimeInput, type InstallRealtimeResult, type IntegrationsModule, type IntentClassification, type InterceptorConfig, type InviteMemberInput, type InvokeInput, type InvokeOptions, type InvokeResult, type IsolationLevel, type ItemResponse, type JwtSettingsResponse, type ListDeliveriesOptions, type ListEventsOptions, type ListFilesOptions, type ListFilesResponse, type ListFunctionsOptions, type ListInvocationsOptions, type ListResponse, type LoginOptions, type MFAChallenge, type MFAMethod, type MFASetupResponse, type MFAVerifyResponse, type MagicLinkRequestInput, type MagicLinkVerifyInput, type MessageRole, type Migration, type MigrationResult, type Mode, type MongoAggregateOptions, type MongoArrayOperator, type MongoCollectionClient, type MongoComparisonOperator, type MongoCursor, type MongoDBModule, type MongoDeleteResult, type MongoDistinctOptions, type MongoElementOperator, type MongoEvaluationOperator, type MongoFilter, type MongoFindAndModifyResult, type MongoFindOneAndDeleteOptions, type MongoFindOneAndUpdateOptions, type MongoFindOptions, type MongoInsertManyResult, type MongoInsertOneResult, type MongoLogicalOperator, type MongoPipelineStage, type MongoProjection, type MongoSort, type MongoUpdateOperators, type MongoUpdateOptions, type MongoUpdateResult, type MoveOptions, type MultipartUpload, type MultipartUploadOptions, type NotFilter, type OAuthCallbackInput, type OAuthConnection, type OAuthModule, type OAuthProvider, type OAuthProviderType, type OAuthSignInOptions, type OAuthSignInResponse, type OrFilter, type OrderByClause, type Org, type OrgBilling, type OrgMember, type OrgMembership, type OrgProfile, type OrgsModule, type PageInfo, type PaginatedResult, type PasswordResetConfirmInput, type PasswordResetRequestInput, type PendingInvite, type PhoneVerificationConfirmInput, type PhoneVerificationRequestInput, type PlanDefinition, type PlanLimits, type PlanName, type PlanStep, type PlansResponse, type PortalInput, type PortalResponse, type PresenceEntry, type PresenceEvent, type PresenceState, type PresenceStateEvent, type PresenceTrackOptions, type PresignedUrl, type PreviewInput, type PreviewResponse, type Project, type ProjectMetrics, type ProjectResource, type ProjectResourcesResponse, type ProjectStats, type ProjectsModule, type PromoteInput, type PromoteResult, type Provider, type PublishEventInput, type PublishEventResult, type QueryOptions, type QueueStats, type QueueTotals, type RealtimeChannel, type RealtimeClient, type RealtimeClientEvent, type RealtimeConfig, type RealtimeConnection, type RealtimeEvent, type RealtimeEventType, type RealtimeMonitoringEvent, type RealtimeMonitoringModule, type RealtimeStats, type RealtimeStatus, type RealtimeSubscription, type RefreshTokenResponse, type Region, type RequestContext, type RequestInterceptor, type ResponseContext, type ResponseInterceptor, type RetryConfig$1 as RetryConfig, type RollbackResult, type SaveSchemaInput, type SavedSchema, type ScheduleConfig, type SchemaDefinition, type SchemaModule, type Secret, type SecretsModule, type SecurityAuditLog, type SecurityModule, type SecurityOverview, type SendMessageInput, type Session, type SetDedicatedDbInput, type SignUpOptions, type SignedUrlResponse, type SlackConfig, type StandardEventName, type StatusComponent, type StorageBucket, type StorageDashboardModule, type StorageFile, type StorageModule, type SubscribeOptions, type Subscription, type SubscriptionConfig, type SubscriptionFilter, type SubscriptionType, type SuperAdmin, type SystemInfo, type SystemSetting, type TableClient, type TableDefinition, type TaskType, type Template, type TemplateCategory, type TemplateDefinition, type TemplateVersion, type TemplateVisibility, type TemplatesModule, type TrainingDataExportOptions, type TrainingDataExportResponse, type TrainingDataStats, type TransactionOperation, type TransactionOptions, type TransactionResult, type TypedEventHandler, type TypedFunction, type UnsubscribeFn, type UpdateAIModelInput, type UpdateAIProjectOverridesInput, type UpdateAISettingsInput, type UpdateApiSettingsInput, type UpdateBucketInput, type UpdateBucketOptions, type UpdateComponentStatusInput, type UpdateComputeSettingsInput, type UpdateDocPageInput, type UpdateDocSdkInput, type UpdateEnvVarInput, type UpdateFlagInput, type UpdateFunctionInput, type UpdateJwtSettingsInput, type UpdateOAuthInput, type UpdateOrgProfileInput, type UpdateProfileInput, type UpdateProjectInput, type UpdateRegionInput, type UpdateSubscriptionInput, type UploadFromUrlOptions, type UploadOptions, type UploadPart, type UploadResult$1 as UploadResult, type UpsertOptions, type Usage, type UsageEntry, type User, type UserActivity, type UserMembership, VaifAuthError, type VaifClient, type VaifClientConfig, VaifConflictError, VaifError, type VaifFunction, VaifNetworkError, VaifNotFoundError, VaifRateLimitError, VaifTimeoutError, VaifValidationError, type VerifySignatureOptions, type WebhookConfig, type WebhookDelivery, type WelcomeEvent, type WhereClause, type WhereFilter, type WhereOperator, createVaifClient, isVaifAuthError, isVaifError, isVaifNetworkError, isVaifNotFoundError, isVaifRateLimitError, isVaifValidationError };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var auth=require('@vaiftech/auth');var h=class s extends Error{constructor(n,e){super(n),this.name="VaifError",this.code=e.code,this.statusCode=e.statusCode,this.requestId=e.requestId,this.details=e.details;let t=Error;t.captureStackTrace&&t.captureStackTrace(this,s);}toJSON(){return {name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,details:this.details}}},E=class extends h{constructor(n,e){super(n,{code:e?.code??"AUTH_ERROR",statusCode:e?.statusCode??401,requestId:e?.requestId}),this.name="VaifAuthError";}},j=class extends h{constructor(n,e){super(n,{code:"VALIDATION_ERROR",statusCode:400,requestId:e?.requestId,details:e?.details??e?.fieldErrors}),this.name="VaifValidationError",this.fieldErrors=e?.fieldErrors;}},x=class extends h{constructor(n,e){super(n,{code:"NETWORK_ERROR"}),this.name="VaifNetworkError",this.cause=e;}},U=class extends h{constructor(n,e){super(n,{code:"RATE_LIMITED",statusCode:429}),this.name="VaifRateLimitError",this.retryAfter=e;}},$=class extends h{constructor(n,e){super(n,{code:"NOT_FOUND",statusCode:404,requestId:e}),this.name="VaifNotFoundError";}},L=class extends h{constructor(n,e){super(n,{code:"CONFLICT",statusCode:409,requestId:e}),this.name="VaifConflictError";}},V=class extends x{constructor(n,e){super(n),this.name="VaifTimeoutError",this.timeoutMs=e;}};function be(s){return s instanceof h}function fe(s){return s instanceof $}function Pe(s){return s instanceof E}function Ie(s){return s instanceof j}function he(s){return s instanceof U}function ke(s){return s instanceof x}async function Se(s){let n;try{n=await s.json();}catch{}let e=n?.message??n?.error??s.statusText??"Request failed",t=n?.requestId;switch(s.status){case 400:return new j(e,{details:n?.details,requestId:t});case 401:return new E(e,{code:"UNAUTHORIZED",statusCode:401,requestId:t});case 403:return new E(e,{code:"FORBIDDEN",statusCode:403,requestId:t});case 404:return new $(e,t);case 409:return new h(e,{code:"CONFLICT",statusCode:409,requestId:t,details:n?.details});case 422:return new j(e,{details:n?.details,requestId:t});case 429:{let r=s.headers.get("Retry-After"),o=r?parseInt(r,10):void 0;return new U(e,o)}default:return new h(e,{code:n?.error??"HTTP_ERROR",statusCode:s.status,requestId:t,details:n?.details})}}function Ce(s,n,e){return s instanceof x?e:s instanceof U?n.includes(429):s instanceof h&&s.statusCode?n.includes(s.statusCode):false}function ve(s,n,e,t,r){if(r!==void 0&&r>0)return Math.min(r*1e3,e);let o=n*Math.pow(t,s),a=Math.min(o,e),l=a*Math.random()*.25;return a+l}function Ae(s){return new Promise(n=>setTimeout(n,s))}async function Re(s,n){let{timeout:e=3e4,fetchFn:t,...r}=n,o=new AbortController,a=setTimeout(()=>o.abort(),e);try{let l=await t(s,{...r,signal:o.signal});if(clearTimeout(a),!l.ok)throw await Se(l);if(l.status===204)return;let i=await l.text();return i?JSON.parse(i):void 0}catch(l){throw clearTimeout(a),l instanceof h?l:l instanceof Error&&l.name==="AbortError"?new x("Request timed out"):l instanceof Error?new x(l.message,l):new x("Network request failed")}}function p(s){let{baseUrl:n,apiKey:e,apiKeyHeader:t,accessToken:r,fetch:o,timeout:a,retry:l,interceptors:i}=s;return async function(g,y={}){let k=`${n}${g}`,S=y.method||"GET",P={"Content-Type":"application/json",...y.headers??{}};if(e&&(P[t]=e),r){let O=typeof r=="function"?await r():r;P.Authorization=`Bearer ${O}`;}let A=y.timeout??a,f=l.maxRetries,R=null;for(let O=0;O<=f;O++){let C=Date.now(),d={url:k,path:g,method:S,headers:{...P},body:y.body,attempt:O};try{if(i.onRequest){let u=await i.onRequest(d);u&&(d=u);}let b=await Re(d.url,{...y,method:d.method,headers:d.headers,body:d.body,timeout:A,fetchFn:o}),T=Date.now()-C;if(i.onResponse){let u={request:d,data:b,status:200,headers:{},durationMs:T};await i.onResponse(u);}return b}catch(b){let T=Date.now()-C;R=b;let u=O<f&&Ce(b,l.retryOn,l.retryOnNetworkError);if(i.onError){let m={request:d,error:b,durationMs:T,willRetry:u};await i.onError(m);}if(u){let m=b instanceof U?b.retryAfter:void 0,I=ve(O,l.retryDelay,l.maxRetryDelay,l.backoffMultiplier,m);await Ae(I);continue}throw b}}throw R||new x("Request failed after retries")}}function v(s){let n=new URLSearchParams;for(let[t,r]of Object.entries(s))r!==void 0&&n.set(t,String(r));let e=n.toString();return e?`?${e}`:""}function Te(s){return JSON.stringify(s)}function q(s,n,e={}){let t={...e},r=()=>{let i={};if(t.limit!==void 0&&(i.limit=t.limit),t.offset!==void 0&&(i.offset=t.offset),t.where&&(i.where=Te(t.where)),t.orderBy){let c=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];i.orderBy=JSON.stringify(c);}return t.select&&t.select.length>0&&(i.select=t.select.join(",")),t.include&&t.include.length>0&&(i.include=JSON.stringify(t.include)),t.distinct&&t.distinct.length>0&&(i.distinct=t.distinct.join(",")),i},o=()=>v(r()),a=i=>q(s,n,{...t,...i}),l={async list(i){i&&(t={...t,...i});let c=o();return n(`/generated/${s}${c}`)},async get(i){let c={};t.select&&t.select.length>0&&(c.select=t.select.join(",")),t.include&&t.include.length>0&&(c.include=JSON.stringify(t.include));let g=v(c);return n(`/generated/${s}/${encodeURIComponent(i)}${g}`)},async first(){let i=await l.limit(1).list();return i.data.length>0?i.data[0]:null},async firstOrFail(){let i=await l.first();if(!i)throw new $(`No record found in table '${s}' matching the query`);return i},async create(i){return n(`/generated/${s}`,{method:"POST",body:JSON.stringify(i)})},async update(i,c){return n(`/generated/${s}/${encodeURIComponent(i)}`,{method:"PATCH",body:JSON.stringify(c)})},async delete(i){return n(`/generated/${s}/${encodeURIComponent(i)}`,{method:"DELETE"})},async createMany(i,c){return n(`/generated/${s}/batch`,{method:"POST",body:JSON.stringify({records:i,skipOnConflict:c?.skipOnConflict,returnRecords:c?.returnRecords})})},async updateMany(i,c){return n(`/generated/${s}/batch`,{method:"PATCH",body:JSON.stringify({data:i,where:t.where,returnRecords:c?.returnRecords})})},async deleteMany(){return n(`/generated/${s}/batch`,{method:"DELETE",body:JSON.stringify({where:t.where})})},async upsert(i,c){return n(`/generated/${s}/upsert`,{method:"POST",body:JSON.stringify({data:i,conflictFields:c.conflictFields,updateFields:c.updateFields})})},async count(){let i=r(),c=v(i);return (await n(`/generated/${s}/count${c}`)).count},async sum(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/sum${g}`)).sum},async avg(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/avg${g}`)).avg},async min(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/min${g}`)).min},async max(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/max${g}`)).max},async aggregate(i,c){return n(`/generated/${s}/aggregate`,{method:"POST",body:JSON.stringify({aggregates:i,where:c?.where||t.where,groupBy:c?.groupBy,having:c?.having})})},async paginate(i){let c=i.page||1,g=i.pageSize||20,y=(c-1)*g,k=r();k.limit=g,k.offset=y,k.includeCount=true;let S=v(k),P=await n(`/generated/${s}${S}`),A=P.total||P.data.length,f=Math.ceil(A/g);return {data:P.data,pageInfo:{total:A,page:c,pageSize:g,pageCount:f,hasNextPage:c<f,hasPrevPage:c>1}}},async cursorPaginate(i){let c=r();c.limit=i.limit||20,i.cursor&&(c.cursor=i.cursor);let g=v(c),y=await n(`/generated/${s}/cursor${g}`);return {data:y.data,nextCursor:y.nextCursor,prevCursor:y.prevCursor,hasMore:y.hasMore}},where(i){if(t.where){let c=t.where;return a({where:{AND:[...Array.isArray(c)?c:[c],i]}})}return a({where:i})},orderBy(i,c="asc"){let g={field:i,direction:c};if(t.orderBy){let y=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];return a({orderBy:[...y,g]})}return a({orderBy:g})},select(...i){return a({select:i})},limit(i){return a({limit:i})},offset(i){return a({offset:i})},include(i){let c=t.include||[];return a({include:[...c,i]})},distinct(...i){return a({distinct:i})}};return l}function W(s){let n=p(s);return {from(e){return q(e,n)},async raw(e,t){return n("/generated/raw",{method:"POST",body:JSON.stringify({query:e,params:t})})},async transaction(e,t){return n("/generated/transaction",{method:"POST",body:JSON.stringify({operations:e,isolationLevel:t?.isolationLevel,timeout:t?.timeout})})},async withTransaction(e,t){let o=(await n("/generated/transaction/start",{method:"POST",body:JSON.stringify({isolationLevel:t?.isolationLevel,timeout:t?.timeout})})).transactionId,a=(i,c)=>{let g=new Headers(c?.headers);return g.set("X-Transaction-Id",o),n(i,{...c,headers:g})},l={from(i){return q(i,a)},async raw(i,c){return a("/generated/raw",{method:"POST",body:JSON.stringify({query:i,params:c})})},async transaction(){throw new h("Nested transactions are not supported",{code:"NESTED_TRANSACTION"})},async withTransaction(){throw new h("Nested transactions are not supported",{code:"NESTED_TRANSACTION"})}};try{let i=await e(l);return await n("/generated/transaction/commit",{method:"POST",body:JSON.stringify({transactionId:o})}),i}catch(i){throw await n("/generated/transaction/rollback",{method:"POST",body:JSON.stringify({transactionId:o})}).catch(()=>{}),i}}}}function _(s){let n=p(s);return {async signUp(e,t,r){return n("/auth/signup",{method:"POST",body:JSON.stringify({email:e,password:t,name:r?.name,phone:r?.phone,metadata:r?.metadata,redirectUrl:r?.redirectUrl})})},async login(e,t,r){return n("/auth/login",{method:"POST",body:JSON.stringify({email:e,password:t,mfaCode:r?.mfaCode,rememberMe:r?.rememberMe})})},async logout(){await n("/auth/logout",{method:"POST"});},async logoutAll(){await n("/auth/logout-all",{method:"POST"});},async getUser(){return (await n("/auth/me")).user},async updateProfile(e){return (await n("/users/me",{method:"PATCH",body:JSON.stringify(e)})).user},async changePassword(e){return n("/users/me/change-password",{method:"POST",body:JSON.stringify(e)})},async requestPasswordReset(e){return n("/auth/forgot-password",{method:"POST",body:JSON.stringify(e)})},async confirmPasswordReset(e){return n("/auth/reset-password",{method:"POST",body:JSON.stringify(e)})},async requestEmailVerification(e){return n("/auth/verify-email/send",{method:"POST",body:JSON.stringify(e||{})})},async confirmEmailVerification(e){return n("/auth/verify-email/confirm",{method:"POST",body:JSON.stringify(e)})},async getOAuthSignInUrl(e){return n("/auth/oauth/authorize",{method:"POST",body:JSON.stringify(e)})},async handleOAuthCallback(e){return n("/auth/oauth/callback",{method:"POST",body:JSON.stringify(e)})},async linkOAuthProvider(e){return n("/auth/oauth/link",{method:"POST",body:JSON.stringify(e)})},async unlinkOAuthProvider(e){return n(`/auth/oauth/unlink/${e}`,{method:"POST"})},async listLinkedProviders(){return n("/auth/oauth/providers")},async requestMagicLink(e){return n("/auth/magic-link/send",{method:"POST",body:JSON.stringify(e)})},async verifyMagicLink(e){return n("/auth/magic-link/verify",{method:"POST",body:JSON.stringify(e)})},async requestPhoneVerification(e){return n("/auth/phone/send",{method:"POST",body:JSON.stringify(e)})},async confirmPhoneVerification(e){return n("/auth/phone/verify",{method:"POST",body:JSON.stringify(e)})},async setupMFA(e){return n("/auth/mfa/setup",{method:"POST",body:JSON.stringify({method:e})})},async enableMFA(e){return n("/auth/mfa/enable",{method:"POST",body:JSON.stringify({code:e})})},async disableMFA(e){return n("/auth/mfa/disable",{method:"POST",body:JSON.stringify({code:e})})},async verifyMFA(e,t){return n("/auth/mfa/verify",{method:"POST",body:JSON.stringify({mfaToken:e,code:t})})},async regenerateBackupCodes(){return n("/auth/mfa/backup-codes",{method:"POST"})},async refreshToken(e){return n("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})})},async listSessions(){return n("/auth/sessions")},async revokeSession(e){return n(`/auth/sessions/${e}`,{method:"DELETE"})},async revokeOtherSessions(){return n("/auth/sessions/revoke-others",{method:"POST"})}}}function K(s){return new Promise(n=>setTimeout(n,s))}function H(s){let n=p(s);async function e(t,r,o){let a=o?.retry||{},l=a.maxRetries??0,i=a.initialDelay??1e3,c=a.maxDelay??3e4,g=a.backoffMultiplier??2,y=a.retryOnStatus??[429,500,502,503,504],k=a.retryOnNetworkError??true,S=null,P=i;for(let A=0;A<=l;A++)try{let f={};o?.version!==void 0&&(f.version=o.version),o?.includeLogs&&(f.includeLogs=!0);let R=v(f),O=await n(`/functions/${t}/invoke${R}`,{method:"POST",body:JSON.stringify(r??{}),headers:o?.headers});if(y.includes(O.status)&&A<l){S=new Error(`Function returned status ${O.status}`),await K(P),P=Math.min(P*g,c);continue}return O}catch(f){S=f;let R=f instanceof TypeError||f.message?.includes("network")||f.message?.includes("fetch");if(k&&R&&A<l){await K(P),P=Math.min(P*g,c);continue}throw f}throw S||new Error("Function invocation failed after retries")}return {invoke:e,async invokeByName(t,r,o){let a={};o?.version!==void 0&&(a.version=o.version),o?.includeLogs&&(a.includeLogs=true);let l=v(a);return n(`/functions/name/${encodeURIComponent(t)}/invoke${l}`,{method:"POST",body:JSON.stringify(r??{}),headers:o?.headers})},async batchInvoke(t,r){let a=(await Promise.allSettled(t.map(l=>this.invoke(l.functionId,l.input,r)))).map((l,i)=>l.status==="fulfilled"?{functionId:t[i].functionId,success:true,result:l.value}:{functionId:t[i].functionId,success:false,error:l.reason?.message||"Unknown error"});return {results:a,successCount:a.filter(l=>l.success).length,errorCount:a.filter(l=>!l.success).length}},rpc(t,r){let o=this,a=async(l,i)=>{let c={...r,...i};return (await e(t,{body:l},c)).data};return Object.defineProperty(a,"id",{value:t,writable:false}),a.getInfo=()=>o.get(t),a.getInvocations=l=>o.getInvocations({...l,functionId:t}),a},async list(t){let r={envId:t.envId,enabled:t.enabled,limit:t.limit,offset:t.offset},o=v(r);return n(`/functions/project/${t.projectId}${o}`)},async get(t){return n(`/functions/${t}`)},async getByName(t,r){return n(`/functions/project/${r}/name/${encodeURIComponent(t)}`)},async create(t){return n("/functions",{method:"POST",body:JSON.stringify(t)})},async update(t,r){return n(`/functions/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(t){return n(`/functions/${t}`,{method:"DELETE"})},async enable(t){return this.update(t,{enabled:true})},async disable(t){return this.update(t,{enabled:false})},async deploy(t,r,o){return n(`/functions/${t}/source`,{method:"PUT",body:JSON.stringify({sourceCode:r})})},async getSource(t,r){return {sourceCode:(await n(`/functions/${t}`)).sourceCode||"",version:1}},async listVersions(t){return (await n(`/functions/${t}/versions`)).versions},async rollback(t,r){return n(`/functions/${t}/rollback`,{method:"POST",body:JSON.stringify({version:r})})},async getEnvVars(t){return (await n(`/functions/${t}/env`)).envVars},async setEnvVars(t,r){return n(`/functions/${t}/env`,{method:"PUT",body:JSON.stringify({envVars:r})})},async deleteEnvVar(t,r){return n(`/functions/${t}/env/${encodeURIComponent(r)}`,{method:"DELETE"})},async bindSecrets(t,r){return n(`/functions/${t}/secrets`,{method:"PUT",body:JSON.stringify({secrets:r})})},async setSchedule(t,r){return n(`/functions/${t}/schedule`,{method:"PUT",body:JSON.stringify(r)})},async removeSchedule(t){return n(`/functions/${t}/schedule`,{method:"DELETE"})},async getInvocations(t){let r={functionId:t.functionId,projectId:t.projectId,status:t.status,since:t.since,until:t.until,limit:t.limit,offset:t.offset},o=v(r);return (await n(`/functions/invocations${o}`)).invocations},async getInvocation(t){return n(`/functions/invocations/${t}`)},async getLogs(t,r){let o={since:r?.since,until:r?.until,level:r?.level,limit:r?.limit},a=v(o);return (await n(`/functions/${t}/logs${a}`)).logs}}}function G(s){let n=p(s),e="default";return {async getUploadUrl(t,r){return n("/storage/upload-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,sizeBytes:r?.sizeBytes,metadata:r?.metadata,isPublic:r?.isPublic,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,upsert:r?.upsert})})},async getDownloadUrl(t,r){return n("/storage/download-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,expiresIn:r?.expiresIn,download:r?.download,transform:r?.transform})})},async createSignedUrl(t,r=3600,o){return (await this.getDownloadUrl(t,{...o,expiresIn:r})).url},async createSignedUrls(t,r=3600,o){return await Promise.all(t.map(async l=>({key:l,url:await this.createSignedUrl(l,r,o)})))},async upload(t,r,o){let a=r instanceof Blob?r:new Blob([r]),l=a.size,i=o?.contentType||(r instanceof File?r.type:void 0)||"application/octet-stream",c=await this.getUploadUrl(t,{...o,contentType:i,sizeBytes:l}),g=await s.fetch(c.url,{method:"PUT",body:a,headers:{"Content-Type":i,...o?.cacheControl&&{"Cache-Control":o.cacheControl},...o?.contentDisposition&&{"Content-Disposition":o.contentDisposition}}});if(!g.ok)throw new h(`Upload failed: ${g.statusText}`,{code:"UPLOAD_ERROR",statusCode:g.status});let y=o?.bucket||e,k=c.url.split("?")[0];return {ok:true,key:t,bucket:y,url:k,publicUrl:o?.isPublic?this.getPublicUrl(t,{bucket:y}):void 0,size:l,contentType:i}},async uploadFromUrl(t,r,o){return n("/storage/upload-from-url",{method:"POST",body:JSON.stringify({key:t,url:r,bucket:o?.bucket||e,contentType:o?.contentType,metadata:o?.metadata,isPublic:o?.isPublic,timeout:o?.timeout})})},async download(t,r){let o=await this.getDownloadUrl(t,r),a=await s.fetch(o.url);if(!a.ok)throw new h(`Download failed: ${a.statusText}`,{code:"DOWNLOAD_ERROR",statusCode:a.status});return a.blob()},async list(t){let r={bucket:t?.bucket||e,prefix:t?.prefix,delimiter:t?.delimiter,limit:t?.limit,cursor:t?.cursor,includeUrls:t?.includeUrls},o=v(r);return n(`/storage/files${o}`)},async getMetadata(t,r){let o=r?.bucket||e;return n(`/storage/files/${encodeURIComponent(o)}/${encodeURIComponent(t)}/metadata`)},async updateMetadata(t,r,o){let a=o?.bucket||e;return n(`/storage/files/${encodeURIComponent(a)}/${encodeURIComponent(t)}/metadata`,{method:"PATCH",body:JSON.stringify(r)})},async exists(t,r){try{return await this.getMetadata(t,r),!0}catch{return false}},async copy(t,r,o){return n("/storage/files/copy",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:o?.sourceBucket||e,destinationKey:r,destinationBucket:o?.destinationBucket||o?.sourceBucket||e,metadata:o?.metadata})})},async move(t,r,o){return n("/storage/files/move",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:o?.sourceBucket||e,destinationKey:r,destinationBucket:o?.destinationBucket||o?.sourceBucket||e,metadata:o?.metadata})})},async delete(t,r){let o=r?.bucket||e;await n(`/storage/files/${encodeURIComponent(o)}/${encodeURIComponent(t)}`,{method:"DELETE"});},async deleteMany(t,r){return n("/storage/files/delete-batch",{method:"POST",body:JSON.stringify({keys:t,bucket:r?.bucket||e})})},getPublicUrl(t,r){let o=r?.bucket||e;return `${s.baseUrl.replace("/api","")}/storage/${encodeURIComponent(o)}/${encodeURIComponent(t)}`},async createBucket(t,r){return n("/storage/buckets",{method:"POST",body:JSON.stringify({name:t,isPublic:r?.isPublic,allowedMimeTypes:r?.allowedMimeTypes,maxFileSize:r?.maxFileSize,fileSizeLimit:r?.fileSizeLimit})})},async getBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}`)},async updateBucket(t,r){return n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})},async listBuckets(){return (await n("/storage/buckets")).buckets},async deleteBucket(t){await n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"DELETE"});},async emptyBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}/empty`,{method:"POST"})},async createMultipartUpload(t,r){return n("/storage/multipart/create",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,metadata:r?.metadata,partSize:r?.partSize})})},async uploadPart(t,r,o){let a=o instanceof Blob?o:new Blob([o]),{url:l}=await n(`/storage/multipart/${t}/part-url`,{method:"POST",body:JSON.stringify({partNumber:r})}),i=await s.fetch(l,{method:"PUT",body:a});if(!i.ok)throw new h(`Part upload failed: ${i.statusText}`,{code:"UPLOAD_PART_ERROR",statusCode:i.status});let c=i.headers.get("etag")||"";return {partNumber:r,etag:c}},async completeMultipartUpload(t,r){return n(`/storage/multipart/${t}/complete`,{method:"POST",body:JSON.stringify({parts:r})})},async abortMultipartUpload(t){await n(`/storage/multipart/${t}/abort`,{method:"POST"});}}}function z(s){let n=p(s);return {async list(e){let t=new URLSearchParams;e?.orgId&&t.set("orgId",e.orgId);let r=t.toString();return n(`/projects${r?`?${r}`:""}`)},async get(e){return n(`/projects/${e}`)},async create(e){return n("/projects",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async delete(e){return n(`/projects/${e}`,{method:"DELETE"})},async getComputeSettings(e){return n(`/projects/${e}/settings/compute`)},async updateComputeSettings(e,t){return n(`/projects/${e}/settings/compute`,{method:"PATCH",body:JSON.stringify(t)})},async getApiSettings(e){return n(`/projects/${e}/settings/api`)},async updateApiSettings(e,t){return n(`/projects/${e}/settings/api`,{method:"PATCH",body:JSON.stringify(t)})},async getJwtSettings(e){return n(`/projects/${e}/settings/jwt`)},async updateJwtSettings(e,t){return n(`/projects/${e}/settings/jwt`,{method:"PATCH",body:JSON.stringify(t)})},async rotateJwtSecret(e){return n(`/projects/${e}/settings/jwt/rotate`,{method:"POST"})},async getAddons(e){return n(`/projects/${e}/settings/addons`)},async updateAddons(e,t){return n(`/projects/${e}/settings/addons`,{method:"PATCH",body:JSON.stringify({enabledAddons:t})})},async getApiKeys(e){return n(`/projects/${e}/api-keys`)},async createApiKey(e,t){return n(`/projects/${e}/api-keys`,{method:"POST",body:JSON.stringify(t??{})})},async revokeApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/revoke`,{method:"POST"})},async rotateApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/rotate`,{method:"POST"})},async setCustomDomain(e,t,r){return n(`/projects/${e}/environments/${t}`,{method:"PATCH",body:JSON.stringify({customDomain:r})})},async getDomainVerificationInstructions(e,t){return n(`/projects/${e}/environments/${t}/domain-verification`)},async verifyDomainTxt(e,t){return n(`/projects/${e}/environments/${t}/verify-domain`,{method:"POST"})},async verifyDomainCname(e,t){return n(`/projects/${e}/environments/${t}/verify-cname`,{method:"POST"})},async getDomainStatus(e,t){return n(`/projects/${e}/environments/${t}/domain-status`)},async provisionSsl(e,t){return n(`/projects/${e}/environments/${t}/provision-ssl`,{method:"POST"})},async removeCustomDomain(e,t){return n(`/projects/${e}/environments/${t}`,{method:"PATCH",body:JSON.stringify({customDomain:null})})},async listApiKeys(e){return (await n(`/projects/${e}/api-keys`)).keys}}}function Q(s){let n=p(s);return {async list(){return n("/orgs")},async create(e){return n("/orgs",{method:"POST",body:JSON.stringify(e)})},async getProfile(e){return (await n(`/orgs/${e}/profile`)).profile||{}},async updateProfile(e,t){return (await n(`/orgs/${e}/profile`,{method:"PATCH",body:JSON.stringify(t)})).profile},async listBillingContacts(e){return (await n(`/orgs/${e}/billing-contacts`)).contacts},async addBillingContact(e,t){return n(`/orgs/${e}/billing-contacts`,{method:"POST",body:JSON.stringify(t)})},async removeBillingContact(e,t){return n(`/orgs/${e}/billing-contacts/${t}`,{method:"DELETE"})},async listMembers(e){return (await n(`/orgs/${e}/members`)).members},async inviteMember(e,t){return n(`/orgs/${e}/members/invite`,{method:"POST",body:JSON.stringify(t)})},async listInvites(e){return (await n(`/orgs/${e}/invites`)).invites},async cancelInvite(e,t){return n(`/orgs/${e}/invites/${t}`,{method:"DELETE"})},async removeMember(e,t){return n(`/orgs/${e}/members/${t}`,{method:"DELETE"})},async updateMemberRole(e,t,r){return n(`/orgs/${e}/members/${t}/role`,{method:"PATCH",body:JSON.stringify({role:r})})},async getMyMembership(e){try{return (await n(`/orgs/${e}/membership`)).membership}catch{return null}}}}function X(s){let n=p(s);return {async preview(e){return n("/schema-engine/preview",{method:"POST",body:JSON.stringify(e)})},async apply(e){return n("/schema-engine/apply",{method:"POST",body:JSON.stringify(e)})},async getMigrations(e,t){let r=t?`/schema-engine/migrations/project/${e}?limit=${t}`:`/schema-engine/migrations/project/${e}`;return n(r)},async saveSchema(e){return n("/schemas/",{method:"POST",body:JSON.stringify(e)})},async getSchemas(e){return n(`/schemas/project/${e}`)}}}function Y(s){let n=p(s);return {async create(e){return n("/functions/secrets",{method:"POST",body:JSON.stringify(e)})},async list(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/functions/secrets/project/${e}${o?`?${o}`:""}`;return n(a)},async reveal(e){return n(`/functions/secrets/${e}/value`)},async update(e,t){return n(`/functions/secrets/${e}`,{method:"PUT",body:JSON.stringify({value:t})})},async delete(e){return n(`/functions/secrets/${e}`,{method:"DELETE"})}}}function Z(s){let n=p(s);return {async list(e,t){let r=new URLSearchParams;t&&r.set("env",t);let o=r.toString(),a=`/deployments/project/${e}${o?`?${o}`:""}`;return (await n(a)).deployments},async get(e){let t=await n(`/deployments/${e}`);return {...t.deployment,steps:t.steps}},async getSteps(e){return (await n(`/deployments/${e}/steps`)).steps},async promote(e){let t={projectId:e.projectId,fromEnv:e.sourceEnv,toEnv:e.targetEnv},r=await n("/deployments/promote",{method:"POST",body:JSON.stringify(t)}),o=await n(`/deployments/${r.deploymentId}`);return {deployment:{...o.deployment,steps:o.steps}}},async rollback(e){return n(`/deployments/${e}/rollback`,{method:"POST"})},async listTokens(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/deployments/tokens/project/${encodeURIComponent(e)}${o?`?${o}`:""}`;return (await n(a)).tokens},async createToken(e){return n("/deployments/tokens",{method:"POST",body:JSON.stringify(e)})},async revokeToken(e){return n(`/deployments/tokens/${encodeURIComponent(e)}/revoke`,{method:"POST"})}}}function ee(s){let n=p(s);return {async getStats(e){return n(`/realtime/stats/project/${e}`)},async getConnections(e){return (await n(`/realtime/connections/project/${e}`)).connections},async getSubscriptions(e){return (await n(`/realtime/subscriptions/project/${e}`)).subscriptions},async getEvents(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.source&&t.source!=="all"&&r.set("source",t.source),t?.level&&t.level!=="all"&&r.set("level",t.level);let o=r.toString(),a=`/realtime/events/project/${e}${o?`?${o}`:""}`;return (await n(a)).events},async getStatus(e){return n(`/realtime/status/project/${e}`)},async install(e){return n("/realtime/install",{method:"POST",body:JSON.stringify(e)})},async enableAll(e){return n("/realtime/enable-all",{method:"POST",body:JSON.stringify(e)})}}}function te(s){let n=p(s);return {async listBuckets(e,t){let r=new URLSearchParams;r.set("projectId",e),t&&r.set("envId",t);let a=`/storage/buckets?${r.toString()}`;return (await n(a)).buckets},async getBucket(e){return (await n(`/buckets/${e}`)).bucket},async createBucket(e){return (await n("/buckets",{method:"POST",body:JSON.stringify(e)})).bucket},async updateBucket(e,t){return (await n(`/buckets/${e}`,{method:"PUT",body:JSON.stringify(t)})).bucket},async deleteBucket(e){return n(`/buckets/${e}`,{method:"DELETE"})},async listFiles(e,t){let r=new URLSearchParams;t?.prefix&&r.set("prefix",t.prefix),t?.maxKeys&&r.set("maxKeys",String(t.maxKeys)),t?.continuationToken&&r.set("continuationToken",t.continuationToken);let o=r.toString(),a=`/buckets/${e}/files${o?`?${o}`:""}`;return n(a)},async deleteFile(e,t){return n(`/buckets/${e}/files?key=${encodeURIComponent(t)}`,{method:"DELETE"})},async getSignedUrl(e,t,r){return n(`/buckets/${e}/signed-url`,{method:"POST",body:JSON.stringify({key:t,expiresIn:r})})},async getUploadUrl(e,t,r){return n(`/buckets/${e}/upload-url`,{method:"POST",body:JSON.stringify({key:t,...r})})},async uploadFile(e,t,r,o){let a=o?.prefix?`${o.prefix}${t}`:t,l=o?.contentType??(r instanceof Blob?r.type:"application/octet-stream"),i=new URLSearchParams;return i.set("key",a),l&&i.set("contentType",l),n(`/buckets/${e}/upload?${i.toString()}`,{method:"POST",body:r,headers:{"Content-Type":l||"application/octet-stream"}})}}}function ne(s){let n=p(s);return {async list(e,t){let r={type:t?.type,enabled:t?.enabled},o=v(r);return (await n(`/integrations/subscriptions/project/${e}${o}`)).subscriptions},async get(e){return n(`/integrations/subscriptions/${e}`)},async create(e){return (await n("/integrations/subscriptions",{method:"POST",body:JSON.stringify(e)})).subscription},async update(e,t){return (await n(`/integrations/subscriptions/${e}`,{method:"PATCH",body:JSON.stringify(t)})).subscription},async delete(e){return n(`/integrations/subscriptions/${e}`,{method:"DELETE"})},async enable(e){return this.update(e,{enabled:true})},async disable(e){return this.update(e,{enabled:false})},async test(e){return n(`/integrations/subscriptions/${e}/test`,{method:"POST"})},async publish(e){return n("/integrations/events/publish",{method:"POST",body:JSON.stringify(e)})},async publishBatch(e){return (await n("/integrations/events/publish-batch",{method:"POST",body:JSON.stringify({events:e})})).results},async listEvents(e){let t={envId:e.envId,source:e.source,name:e.name,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/events/project/${e.projectId}${r}`)).events},async getEvent(e){return n(`/integrations/events/${e}`)},async getDeliveries(e){let t={subscriptionId:e.subscriptionId,eventId:e.eventId,status:e.status,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/deliveries${r}`)).deliveries},async getDelivery(e){return n(`/integrations/deliveries/${e}`)},async retryDelivery(e){return n(`/integrations/deliveries/${e}/retry`,{method:"POST"})},async retryAllFailed(e){return n(`/integrations/subscriptions/${e}/retry-failed`,{method:"POST"})},async getDlq(e,t){let r={limit:t?.limit,offset:t?.offset},o=v(r);return (await n(`/integrations/dlq/project/${e}${o}`)).deliveries},async purgeDlq(e,t){return n(`/integrations/dlq/project/${e}/purge`,{method:"POST",body:JSON.stringify({olderThan:t.olderThan})})},async replayDlq(e,t){return n(`/integrations/dlq/project/${e}/replay`,{method:"POST",body:JSON.stringify(t)})},verifySignature(e){let t=e.tolerance??300;try{let r=e.signature.split(","),o=r.find(f=>f.startsWith("t=")),a=r.find(f=>f.startsWith("v1="));if(!o||!a)return !1;let l=parseInt(o.slice(2),10),i=a.slice(3),c=Math.floor(Date.now()/1e3);if(Math.abs(c-l)>t)return !1;let g=`${l}.${e.payload}`,y=new TextEncoder,k=y.encode(e.secret),S=y.encode(g),P=Array.from(k).concat(Array.from(S)).reduce((f,R)=>f+R,0).toString(16);if(i.length!==P.length)return !1;let A=0;for(let f=0;f<i.length;f++)A|=i.charCodeAt(f)^P.charCodeAt(f);return A===0}catch{return false}},generateSecret(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="whsec_";for(let r=0;r<32;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}}}function re(s){let n=p(s);return {async getSummary(e){return n(`/billing/org/${e}/summary`)},async getEntitlements(e){return n(`/entitlements/org/${e}`)},async checkEntitlement(e,t){return n(`/entitlements/org/${e}/check`,{method:"POST",body:JSON.stringify(t)})},async getPlans(){return (await n("/pricing/plans")).plans},async createCheckout(e){return n("/billing/checkout",{method:"POST",body:JSON.stringify(e)})},async verifyCheckoutSession(e){return n(`/billing/checkout/verify/${e}`)},async openPortal(e){return n(`/billing/org/${e.orgId}/portal`,{method:"POST",body:JSON.stringify({returnUrl:e.returnUrl})})},async getAIUsageSummary(e){return n(`/ai-usage/org/${e}/summary`)},async getAIUsageHistory(e,t=30){return n(`/ai-usage/org/${e}/history?days=${t}`)},async getAIUsageBreakdown(e){return n(`/ai-usage/org/${e}/breakdown`)},async getRecentAIRequests(e,t=50,r=0){return n(`/ai-usage/org/${e}/recent?limit=${t}&offset=${r}`)}}}function oe(s){let n=p(s);return {async getOverview(){return n("/admin/overview")},async listUsers(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/users${r?`?${r}`:""}`)},async getUser(e){return n(`/admin/users/${e}`)},async updateUserStatus(e,t){return n(`/admin/users/${e}/status`,{method:"PATCH",body:JSON.stringify({status:t})})},async updateUserAdmin(e,t){return n(`/admin/users/${e}/admin`,{method:"PATCH",body:JSON.stringify({isAdmin:t})})},async listOrganizations(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.plan&&t.set("plan",e.plan),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/organizations${r?`?${r}`:""}`)},async getOrganization(e){return n(`/admin/organizations/${e}`)},async updateOrganization(e,t){return n(`/admin/organizations/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async listProjects(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.orgId&&t.set("orgId",e.orgId),e?.region&&t.set("region",e.region),e?.tenancy&&t.set("tenancy",e.tenancy),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/projects${r?`?${r}`:""}`)},async getProject(e){return n(`/admin/projects/${e}`)},async updateProject(e,t){return n(`/admin/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getProjectResources(e){return n(`/admin/resources/project/${e}`)},async setDedicatedDb(e){return n(`/admin/resources/project/${e.projectId}/db`,{method:"POST",body:JSON.stringify({connectionString:e.connectionString})})},async listIncidents(e="open"){return (await n(`/admin/incidents?status=${e}`)).incidents},async createIncident(e){return n("/admin/incidents",{method:"POST",body:JSON.stringify(e)})},async acknowledgeIncident(e){return n(`/admin/incidents/${e}/ack`,{method:"POST"})},async resolveIncident(e){return n(`/admin/incidents/${e}/resolve`,{method:"POST"})},async listRegions(){return n("/admin/regions")},async updateRegion(e,t){return n(`/admin/regions/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getHealthComponents(){return n("/admin/health/components")},async updateHealthComponent(e,t){return n(`/admin/health/components/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getSystemInfo(){return n("/admin/system/info")},async listQueues(){return n("/admin/queues")},async listDlqMessages(e){let t=new URLSearchParams;e?.queue&&t.set("queue",e.queue),e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/dlq${r?`?${r}`:""}`)},async retryDlqMessage(e){return n(`/admin/dlq/${e}/retry`,{method:"POST"})},async archiveDlqMessage(e){return n(`/admin/dlq/${e}`,{method:"DELETE"})},async listFeatureFlags(){return (await n("/flags")).flags},async createFeatureFlag(e,t){return n("/flags",{method:"POST",body:JSON.stringify({key:e,enabled:t})})},async updateFeatureFlag(e,t){return n(`/flags/${e}`,{method:"PUT",body:JSON.stringify({enabled:t})})},async deleteFeatureFlag(e){return n(`/flags/${e}`,{method:"DELETE"})},async listAdmins(){return (await n("/admin/admins")).admins||[]},async addAdmin(e,t,r){return n("/admin/admins",{method:"POST",body:JSON.stringify({userId:e,role:t,notes:r})})},async updateAdmin(e,t){return n(`/admin/admins/${e}`,{method:"PUT",body:JSON.stringify(t)})},async removeAdmin(e){return n(`/admin/admins/${e}`,{method:"DELETE"})},async getSettings(e){let t=e?`?category=${e}`:"";return n(`/admin/settings${t}`)},async updateSetting(e,t){return n(`/admin/settings/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({value:t})})},async listAIModels(){return n("/admin/ai/models")},async getAIModel(e){return n(`/admin/ai/models/${e}`)},async createAIModel(e){return n("/admin/ai/models",{method:"POST",body:JSON.stringify(e)})},async updateAIModel(e,t){return n(`/admin/ai/models/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteAIModel(e){return n(`/admin/ai/models/${e}`,{method:"DELETE"})},async toggleAIModel(e,t,r){return n(`/admin/ai/models/${e}/toggle`,{method:"POST",body:JSON.stringify({enabled:t,disabledMessage:r})})},async listAISessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/workspace/sessions${r?`?${r}`:""}`)},async getAISession(e){return n(`/admin/ai/workspace/sessions/${e}`)},async deleteAISession(e){return n(`/admin/ai/workspace/sessions/${e}`,{method:"DELETE"})},async listGeneratedBackends(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/backends${r?`?${r}`:""}`)},async getGeneratedBackend(e){return n(`/admin/ai/backends/${e}`)},async deleteGeneratedBackend(e){return n(`/admin/ai/backends/${e}`,{method:"DELETE"})},async listPromptTemplates(e){let t=new URLSearchParams;e?.category&&t.set("category",e.category),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/prompt-templates${r?`?${r}`:""}`)},async createPromptTemplate(e){return n("/admin/ai/prompt-templates",{method:"POST",body:JSON.stringify(e)})},async updatePromptTemplate(e,t){return n(`/admin/ai/prompt-templates/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deletePromptTemplate(e){return n(`/admin/ai/prompt-templates/${e}`,{method:"DELETE"})},async listContextSnapshots(e){let t=new URLSearchParams;e?.projectId&&t.set("projectId",e.projectId),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/context-snapshots${r?`?${r}`:""}`)},async invalidateContextSnapshot(e){return n(`/admin/ai/context-snapshots/${e}/invalidate`,{method:"POST"})},async deleteContextSnapshot(e){return n(`/admin/ai/context-snapshots/${e}`,{method:"DELETE"})},async getCopilotOverview(){return n("/admin/copilot/overview")},async listCopilotSessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/sessions${r?`?${r}`:""}`)},async getCopilotSession(e){return n(`/admin/copilot/sessions/${e}`)},async deleteCopilotSession(e){return n(`/admin/copilot/sessions/${e}`,{method:"DELETE"})},async listCopilotMemories(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.projectId&&t.set("projectId",e.projectId),e?.memoryType&&t.set("memoryType",e.memoryType),e?.importance&&t.set("importance",e.importance),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/memories${r?`?${r}`:""}`)},async getCopilotMemoryStats(){return n("/admin/copilot/memories/stats")},async getCopilotMemory(e){return n(`/admin/copilot/memories/${e}`)},async updateCopilotMemory(e,t){return n(`/admin/copilot/memories/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteCopilotMemory(e){return n(`/admin/copilot/memories/${e}`,{method:"DELETE"})},async cleanupExpiredMemories(){return n("/admin/copilot/memories/cleanup",{method:"POST"})},async exportTrainingData(e){let t=new URLSearchParams;e?.format&&t.set("format",e.format),e?.dataType&&t.set("dataType",e.dataType),e?.minConfidence!==void 0&&t.set("minConfidence",String(e.minConfidence)),e?.limit&&t.set("limit",String(e.limit)),e?.includeExecuted!==void 0&&t.set("includeExecuted",String(e.includeExecuted)),e?.includeSuccessful!==void 0&&t.set("includeSuccessful",String(e.includeSuccessful));let r=t.toString();return n(`/admin/copilot/training-data/export${r?`?${r}`:""}`)},async getTrainingDataStats(){return n("/admin/copilot/training-data/stats")},async listErrors(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.path&&t.set("path",e.path),e?.errorCode&&t.set("errorCode",e.errorCode),e?.status&&t.set("status",e.status),e?.environment&&t.set("environment",e.environment),e?.startDate&&t.set("startDate",e.startDate),e?.endDate&&t.set("endDate",e.endDate),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/errors${r?`?${r}`:""}`)},async getErrorStats(){return n("/admin/errors/stats")},async getError(e){return n(`/admin/errors/${e}`)},async resolveError(e,t){return n(`/admin/errors/${e}/resolve`,{method:"PUT",body:JSON.stringify({notes:t})})},async deleteError(e){return n(`/admin/errors/${e}`,{method:"DELETE"})},async bulkDeleteErrors(e){let t=e?`?olderThanDays=${e}`:"";return n(`/admin/errors${t}`,{method:"DELETE"})},async getAIWorkspaceOverview(){return n("/admin/ai-workspace/overview")},async listAIWorkspaceSessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.taskType&&t.set("taskType",e.taskType),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai-workspace/sessions${r?`?${r}`:""}`)},async getAIWorkspaceSession(e){return n(`/admin/ai-workspace/sessions/${e}`)},async deleteAIWorkspaceSession(e){return n(`/admin/ai-workspace/sessions/${e}`,{method:"DELETE"})}}}function se(s){let n=p(s);return {async list(){return (await n("/flags")).flags},async create(e){return n("/flags",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/flags/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)})},async delete(e){return n(`/flags/${encodeURIComponent(e)}`,{method:"DELETE"})}}}function ie(s){let n=p(s);return {async getOverview(e){return (await n(`/security/overview/${encodeURIComponent(e)}`)).overview},async getAuditLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));let o=r.toString(),a=`/security/audit/${encodeURIComponent(e)}${o?`?${o}`:""}`;return n(a)},async listEnvVars(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/projects/${encodeURIComponent(e)}/env-vars${o?`?${o}`:""}`;return (await n(a)).envVars},async createEnvVar(e,t){return (await n(`/projects/${encodeURIComponent(e)}/env-vars`,{method:"POST",body:JSON.stringify(t)})).envVar},async updateEnvVar(e,t,r){return (await n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})).envVar},async deleteEnvVar(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"DELETE"})},async getEnvVarValue(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}/value`)}}}function ae(s){let n=p(s);return {async generatePlan(e){return n("/ai/plan",{method:"POST",body:JSON.stringify({projectId:e.projectId,prompt:e.prompt,context:e.context,taskType:e.taskType,mode:e.mode})})},async explainPlan(e){return n("/ai/explain",{method:"POST",body:JSON.stringify({plan:e.plan,projectId:e.projectId,taskType:e.taskType,mode:e.mode})})},async getOrgSettings(e){return n(`/ai/settings/org/${encodeURIComponent(e)}`)},async updateOrgSettings(e,t){return n(`/ai/settings/org/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getProjectOverrides(e){return n(`/ai/settings/project/${encodeURIComponent(e)}`)},async updateProjectOverrides(e,t){return n(`/ai/settings/project/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getUsage(e,t){let r=new URLSearchParams;t&&r.set("month",t);let o=r.toString(),a=`/ai/usage/org/${encodeURIComponent(e)}${o?`?${o}`:""}`;return n(a)},async getBudgetStatus(e){let[t,r]=await Promise.all([this.getOrgSettings(e),this.getUsage(e)]),o=t?.monthlyBudgetCents??1e4,a=r.costCents,l=Math.max(0,o-a),i=o>0?Math.round(a/o*100):0;return {spent:a,budget:o,remaining:l,hardStop:t?.hardStopEnabled??false,percentUsed:i}},async generateFunction(e){return n("/ai/generate-function",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,language:e.language??"typescript",mode:e.mode})})},async generateEndpoint(e){return n("/ai/generate-endpoint",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,method:e.method??"GET",authRequired:e.authRequired??true,mode:e.mode})})},async exportCode(e){return n("/ai/export-code",{method:"POST",body:JSON.stringify({projectId:e.projectId,targetLanguage:e.targetLanguage,includeSchema:e.includeSchema??true,includeFunctions:e.includeFunctions??true,includeEndpoints:e.includeEndpoints??true})})},async createConversation(e,t){return n("/ai/conversations",{method:"POST",body:JSON.stringify({projectId:e,title:t?.title,context:t?.context})})},async sendMessage(e,t){return n(`/ai/conversations/${encodeURIComponent(e)}/messages`,{method:"POST",body:JSON.stringify({content:t.content,taskType:t.taskType})})},async getConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`)},async listConversations(e){return (await n(`/ai/conversations/project/${encodeURIComponent(e)}`)).conversations},async deleteConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`,{method:"DELETE"})},async getAvailableModels(){return n("/ai/models/available")},async getModel(e){return n(`/ai/models/${encodeURIComponent(e)}`)},async getProjectContext(e){return n(`/ai/context/${encodeURIComponent(e)}`)},async estimateTokens(e,t){return n("/ai/context/estimate",{method:"POST",body:JSON.stringify({prompt:e,projectId:t})})},async analyzeForClarification(e){return n("/ai/clarify",{method:"POST",body:JSON.stringify(e)})},async getSuggestions(e){return n("/ai/suggestions",{method:"POST",body:JSON.stringify(e)})},workspace:{async create(e){return n("/ai/workspace/create",{method:"POST",body:JSON.stringify(e)})},async get(e){return n(`/ai/workspace/${encodeURIComponent(e)}`)},async list(e){return n(`/ai/workspace/list/${encodeURIComponent(e)}`)},async submitPrompt(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/prompt`,{method:"POST",body:JSON.stringify(t),timeout:12e4})},async submitClarification(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/clarify`,{method:"POST",body:JSON.stringify({responses:t}),timeout:9e4})},async generate(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/generate`,{method:"POST",body:JSON.stringify(t),timeout:18e4})},async submitModification(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/modify`,{method:"POST",body:JSON.stringify(t),timeout:18e4})},async submitFeedback(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/feedback`,{method:"POST",body:JSON.stringify(t)})}},backends:{async get(e){return n(`/ai/backends/${encodeURIComponent(e)}`)},async list(e){return n(`/ai/backends/list/${encodeURIComponent(e)}`)},async delete(e){return n(`/ai/backends/${encodeURIComponent(e)}`,{method:"DELETE"})},async deploy(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/deploy`,{method:"POST",body:JSON.stringify(t)})},async apply(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify(t)})},async deployLive(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/deploy-live`,{method:"POST",body:JSON.stringify(t),timeout:3e5})},async getDeployments(e){return n(`/ai/backends/${encodeURIComponent(e)}/deployments`)}},deployments:{async getLimits(e){return n(`/ai/deployments/limits/${encodeURIComponent(e)}`)},async getStatus(e){return n(`/ai/deployments/${encodeURIComponent(e)}/status`)},async getLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.severity&&r.set("severity",t.severity);let o=r.toString();return n(`/ai/deployments/${encodeURIComponent(e)}/logs${o?`?${o}`:""}`)},async terminate(e){return n(`/ai/deployments/${encodeURIComponent(e)}`,{method:"DELETE"})},async redeploy(e){return n(`/ai/deployments/${encodeURIComponent(e)}/redeploy`,{method:"POST",timeout:3e5})}},async getUserOrganizations(){return n("/ai/user/organizations")},async getProjectLimits(e){return n(`/ai/org/${encodeURIComponent(e)}/project-limits`)},async createProjectWithSchema(e){return n("/ai/schema/create-project",{method:"POST",body:JSON.stringify(e)})}}}function le(s){let n=p(s);return {async load(){return n("/bootstrap")}}}function ce(s){let n=p(s);return {async list(e){let t=new URLSearchParams;e?.visibility&&t.set("visibility",e.visibility),e?.category&&t.set("category",e.category),e?.orgId&&t.set("orgId",e.orgId);let r=t.toString(),o=`/templates${r?`?${r}`:""}`;return (await n(o)).templates},async get(e){return n(`/templates/${e}`)},async create(e){return n("/templates",{method:"POST",body:JSON.stringify(e)})},async previewInstall(e){return n("/templates/install/preview",{method:"POST",body:JSON.stringify(e)})},async applyInstall(e){return n("/templates/install/apply",{method:"POST",body:JSON.stringify(e)})},async rollback(e){return n(`/templates/install/${e}/rollback`,{method:"POST"})},async createProject(e){return n("/templates/create-project",{method:"POST",body:JSON.stringify(e)})}}}function de(s){let n=p(s);return {async list(e){return (await n(`/oauth/org/${e}`)).connections},async configure(e,t){return n(`/oauth/org/${e}/configure`,{method:"POST",body:JSON.stringify(t)})},async update(e,t,r){return n(`/oauth/org/${e}/provider/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(e,t){return n(`/oauth/org/${e}/provider/${t}`,{method:"DELETE"})}}}function ue(s){let n=p(s);return {async listPages(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/pages${t}`)).pages},async getPage(e){return (await n(`/docs/pages/${encodeURIComponent(e)}`)).page},async createPage(e){return (await n("/docs/pages",{method:"POST",body:JSON.stringify(e)})).page},async updatePage(e,t){return (await n(`/docs/pages/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).page},async deletePage(e){return n(`/docs/pages/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdks(){return (await n("/docs/sdks")).sdks},async getSdk(e){return (await n(`/docs/sdks/${encodeURIComponent(e)}`)).sdk},async createSdk(e){return (await n("/docs/sdks",{method:"POST",body:JSON.stringify(e)})).sdk},async updateSdk(e,t){return (await n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).sdk},async deleteSdk(e){return n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdkExamples(e,t){let r=t?`?topic=${encodeURIComponent(t)}`:"";return (await n(`/docs/sdks/${encodeURIComponent(e)}/examples${r}`)).examples},async createSdkExample(e){return (await n("/docs/sdk-examples",{method:"POST",body:JSON.stringify(e)})).example},async deleteSdkExample(e){return n(`/docs/sdk-examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listEndpoints(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/api-endpoints${t}`)).endpoints},async getEndpoint(e){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`)).endpoint},async createEndpoint(e){return (await n("/docs/api-endpoints",{method:"POST",body:JSON.stringify(e)})).endpoint},async updateEndpoint(e,t){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).endpoint},async deleteEndpoint(e){return n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},async listExamples(e){let t=e!==void 0?`?featured=${e}`:"";return (await n(`/docs/examples${t}`)).examples},async getExample(e){return (await n(`/docs/examples/${encodeURIComponent(e)}`)).example},async createExample(e){return (await n("/docs/examples",{method:"POST",body:JSON.stringify(e)})).example},async updateExample(e,t){return (await n(`/docs/examples/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).example},async deleteExample(e){return n(`/docs/examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listChangelog(){return (await n("/docs/changelog")).entries},async getChangelogEntry(e){return (await n(`/docs/changelog/${encodeURIComponent(e)}`)).entry},async createChangelogEntry(e){return (await n("/docs/changelog",{method:"POST",body:JSON.stringify(e)})).entry},async updateChangelogEntry(e,t){return (await n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).entry},async deleteChangelogEntry(e){return n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"DELETE"})},async search(e){return (await n(`/docs/search?q=${encodeURIComponent(e)}`)).results}}}function J(s,n,e,t){let r=[...n],o=0,a=false,l=false,i=async()=>{if(l||a)return;let c=await e(`/mongodb/${t}/cursor/${s}/next`,{method:"POST"});r=c.batch,o=0,a=c.exhausted;};return {id:s,async hasNext(){return l?false:o<r.length?true:a?false:(await i(),r.length>0)},async next(){return l?null:o<r.length?r[o++]:a||(await i(),r.length===0)?null:r[o++]},async toArray(){if(l)return [];let c=[];for(;o<r.length;)c.push(r[o++]);for(;!a;)await i(),c.push(...r),o=r.length;return c},async forEach(c){if(!l){for(;o<r.length;)await c(r[o++]);for(;!a;){await i();for(let g of r)await c(g);o=r.length;}}},map(c){let g=r.slice(o).map(c);return J(s,g,e,t)},async close(){if(!l){l=true;try{await e(`/mongodb/${t}/cursor/${s}/close`,{method:"POST"});}catch{}}},isClosed(){return l}}}function Oe(s,n){let e=`/mongodb/${encodeURIComponent(s)}`;return {collectionName:s,async find(t,r){return n(`${e}/find`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async findCursor(t,r){let o=await n(`${e}/find/cursor`,{method:"POST",body:JSON.stringify({filter:t,options:r})});return J(o.cursorId,o.batch,n,s)},async findOne(t,r){return n(`${e}/findOne`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async findById(t,r){return n(`${e}/findById/${encodeURIComponent(t)}`,{method:"GET",...r&&{body:JSON.stringify({options:r})}})},async countDocuments(t){return (await n(`${e}/count`,{method:"POST",body:JSON.stringify({filter:t})})).count},async estimatedDocumentCount(){return (await n(`${e}/estimatedCount`)).count},async distinct(t,r){return n(`${e}/distinct`,{method:"POST",body:JSON.stringify({field:t,...r})})},async insertOne(t){return n(`${e}/insertOne`,{method:"POST",body:JSON.stringify({document:t})})},async insertMany(t,r){return n(`${e}/insertMany`,{method:"POST",body:JSON.stringify({documents:t,options:r})})},async updateOne(t,r,o){return n(`${e}/updateOne`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async updateMany(t,r,o){return n(`${e}/updateMany`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async replaceOne(t,r,o){return n(`${e}/replaceOne`,{method:"POST",body:JSON.stringify({filter:t,replacement:r,options:o})})},async findOneAndUpdate(t,r,o){return n(`${e}/findOneAndUpdate`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async findOneAndReplace(t,r,o){return n(`${e}/findOneAndReplace`,{method:"POST",body:JSON.stringify({filter:t,replacement:r,options:o})})},async deleteOne(t){return n(`${e}/deleteOne`,{method:"POST",body:JSON.stringify({filter:t})})},async deleteMany(t){return n(`${e}/deleteMany`,{method:"POST",body:JSON.stringify({filter:t})})},async findOneAndDelete(t,r){return n(`${e}/findOneAndDelete`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async aggregate(t,r){return n(`${e}/aggregate`,{method:"POST",body:JSON.stringify({pipeline:t,options:r})})},async aggregateCursor(t,r){let o=await n(`${e}/aggregate/cursor`,{method:"POST",body:JSON.stringify({pipeline:t,options:r})});return J(o.cursorId,o.batch,n,s)},async createIndex(t,r){return (await n(`${e}/indexes`,{method:"POST",body:JSON.stringify({keys:t,options:r})})).indexName},async dropIndex(t){await n(`${e}/indexes/${encodeURIComponent(t)}`,{method:"DELETE"});},async listIndexes(){return n(`${e}/indexes`)},async bulkWrite(t,r){return n(`${e}/bulkWrite`,{method:"POST",body:JSON.stringify({operations:t,options:r})})}}}function ge(s){let n=p(s);return {collection(e){return Oe(e,n)},async listCollections(){return n("/mongodb/collections")},async createCollection(e,t){await n("/mongodb/collections",{method:"POST",body:JSON.stringify({name:e,options:t})});},async dropCollection(e){await n(`/mongodb/collections/${encodeURIComponent(e)}`,{method:"DELETE"});},async renameCollection(e,t){await n(`/mongodb/collections/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({newName:t})});},async command(e){return n("/mongodb/command",{method:"POST",body:JSON.stringify(e)})}}}function pe(s){let n=p(s);return {async chat(e){return n("/ai/copilot/chat",{method:"POST",body:JSON.stringify(e),timeout:12e4})},getStreamUrl(){return `${s.baseUrl}/ai/copilot/chat/stream`},async getModels(e){return n(`/ai/copilot/models/${encodeURIComponent(e)}`)},async getCreditStatus(e){return n(`/ai/copilot/credit-status/${encodeURIComponent(e)}`)},async listSessions(e){return n(`/ai/copilot/sessions/${encodeURIComponent(e)}`)},async getSession(e){return n(`/ai/copilot/session/${encodeURIComponent(e)}`)},async updateSession(e,t){return n(`/ai/copilot/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteSession(e){return n(`/ai/copilot/session/${encodeURIComponent(e)}`,{method:"DELETE"})},async executePlan(e){return n("/ai/copilot/execute",{method:"POST",body:JSON.stringify(e),timeout:18e4})},async submitFeedback(e){return n("/ai/copilot/feedback",{method:"POST",body:JSON.stringify(e)})},async getClassificationStats(){return n("/ai/copilot/stats")},async getUsage(e){return n(`/ai/copilot/usage-org/${encodeURIComponent(e)}`)}}}function xe(s,n,e,t){let r=n.type||"public",o="unsubscribed",a=new Map,l=[],i={},c=null,g=null,y=new Set,k=new Set,S=new Set,P=d=>{if(d.event){let b=a.get(d.event);b&&b.forEach(T=>T(d.payload));}},A=d=>{i=d.state||{},y.forEach(b=>b(i));},f=d=>{let b=d.key||"",T=d.currentPresences||[],u=d.joinedPresences||[],m=d.leftPresences||[];u.length>0&&(i[b]=T,k.forEach(I=>I(b,T,u))),m.length>0&&(T.length===0?delete i[b]:i[b]=T,S.forEach(I=>I(b,T,m))),y.forEach(I=>I(i));},R=d=>{let b={type:"db_change",projectId:d.projectId||"",schema:d.schema||"",table:d.table||"",operation:d.op,new:d.record,old:d.old_record,timestamp:d.ts||new Date().toISOString(),partial:d.partial};l.forEach(({options:T,handler:u})=>{if(T.table===b.table){let m=T.event||"*";(m==="*"||(Array.isArray(m)?m.includes(b.operation):m===b.operation))&&u(b);}});},C={get name(){return s},get type(){return r},get status(){return o},_handleMessage:d=>{switch(d.type){case "broadcast":P(d);break;case "presence_state":A(d);break;case "presence":f(d);break;case "db_change":R(d);break;case "subscribed":o="subscribed";break;case "error":o="error";break}},onDbChange(d,b){return l.push({options:d,handler:b}),o==="subscribed"&&e({type:"subscribe",channel:s,options:{table:d.table,filter:d.filter,event:d.event,columns:d.columns}}),C},on(d,b){return a.has(d)||a.set(d,new Set),a.get(d).add(b),C},off(d,b){return b?a.get(d)?.delete(b):a.delete(d),C},async broadcast(d){if(o!=="subscribed")throw new h("Channel must be subscribed before broadcasting",{code:"CHANNEL_NOT_SUBSCRIBED"});e({type:"broadcast",channel:s,event:d.event,payload:d.payload,includeSelf:d.includeSelf});},presence:{async track(d){if(r!=="presence")throw new h("Presence tracking is only available on presence channels",{code:"INVALID_CHANNEL_TYPE"});c=d.key||t()||"anonymous",g=d.state,e({type:"presence_track",channel:s,key:c,state:g});},async update(d){if(!g)throw new h("Must call track() before update()",{code:"PRESENCE_NOT_TRACKED"});g={...g,...d},e({type:"presence_update",channel:s,key:c??void 0,state:g});},async untrack(){c&&(e({type:"presence_untrack",channel:s,key:c}),c=null,g=null);},state(){return {...i}},onSync(d){return y.add(d),C},onJoin(d){return k.add(d),C},onLeave(d){return S.add(d),C}},async subscribe(){return o==="subscribed"||(o="subscribing",e({type:"subscribe",channel:s}),l.forEach(({options:d})=>{e({type:"subscribe",channel:s,options:{table:d.table,filter:d.filter,event:d.event,columns:d.columns}});}),n.presenceState&&r==="presence"&&await C.presence.track({state:n.presenceState})),C},async unsubscribe(){o!=="unsubscribed"&&(c&&await C.presence.untrack(),e({type:"unsubscribe",channel:s}),o="unsubscribed",i={},a.clear(),l.length=0);}};return C}function me(s,n){let{wsUrl:e=s.baseUrl.replace(/^http/,"ws")+"/realtime/ws",autoReconnect:t=true,reconnectDelay:r=1e3,maxReconnectAttempts:o=10}=n??{},a=null,l="disconnected",i=null,c=null,g=0,y=null,k=null,S=new Map,P=new Map,A=new Set,f={connect:new Set,disconnect:new Set,error:new Set,reconnect:new Set},R=u=>{f[u].forEach(m=>m());},O=u=>{let m=`table:${u.table}`;if(u.filter){let M=(Array.isArray(u.filter)?u.filter:[u.filter]).map(w=>`${w.field}${w.operator||"eq"}${w.value}`).join("&");m+=`?${M}`;}return m},C=u=>{a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(u));},d=u=>{if(u.channel){let m=S.get(u.channel);if(m){m._handleMessage(u);return}}switch(u.type){case "db_change":{let m={type:"db_change",projectId:u.projectId??"",schema:u.schema??"",table:u.table??"",operation:u.op,new:u.record,old:u.old_record,timestamp:u.ts??new Date().toISOString(),partial:u.partial},I=`table:${u.table}`;P.forEach((M,w)=>{(w===I||w.startsWith(I+"?"))&&M.forEach(N=>N(m));});break}case "presence":{let m={type:"presence",event:u.event,key:u.key||u.connectionId||"",connectionId:u.connectionId??"",projectId:u.projectId??"",currentPresences:u.currentPresences||[],leftPresences:u.leftPresences||[],joinedPresences:u.joinedPresences||[]};A.forEach(I=>I(m));break}case "welcome":i=u.connectionId||null;break;case "error":{R("error");break}}},b=()=>new Promise((u,m)=>{try{a=new WebSocket(e);}catch{m(new x("Failed to create WebSocket connection"));return}let I=()=>{l="connected",g=0;let D={type:"auth"};s.apiKey&&(D[s.apiKeyHeader]=s.apiKey),c&&(D.token=c),C(D),R("connect"),S.forEach(B=>{(B.status==="subscribed"||B.status==="subscribing")&&B.subscribe();}),P.forEach((B,ye)=>{C({type:"subscribe",channel:ye});}),k=setInterval(()=>{C({type:"ping"});},3e4),u();},M=D=>{try{let B=JSON.parse(D.data);d(B);}catch{}},w=()=>{if(l="disconnected",i=null,a=null,k&&(clearInterval(k),k=null),R("disconnect"),t&&g<o){l="reconnecting";let D=r*Math.pow(2,g);y=setTimeout(()=>{g++,R("reconnect"),b().catch(()=>{});},Math.min(D,3e4));}},N=()=>{R("error"),m(new x("WebSocket connection error"));};a.addEventListener("open",I),a.addEventListener("message",M),a.addEventListener("close",w),a.addEventListener("error",N);}),T=()=>{y&&(clearTimeout(y),y=null),k&&(clearInterval(k),k=null),g=o;};return {channel(u,m={}){let I=S.get(u);if(I)return I;let M=xe(u,m,C,()=>i);return S.set(u,M),M},async removeChannel(u){let m=S.get(u.name);m&&(await m.unsubscribe(),S.delete(u.name));},getChannels(){return Array.from(S.values())},subscribe(u,m){let I=O(u);return P.has(I)||P.set(I,new Set),P.get(I).add(m),a?.readyState===WebSocket.OPEN&&C({type:"subscribe",channel:I}),()=>{let M=P.get(I);M&&(M.delete(m),M.size===0&&(P.delete(I),a?.readyState===WebSocket.OPEN&&C({type:"unsubscribe",channel:I})));}},subscribeToPresence(u){return A.add(u),()=>{A.delete(u);}},async connect(){if(l!=="connected"){if(!s.apiKey)throw new E("API key is required for realtime connections");l="connecting",await b();}},disconnect(){T(),S.forEach(u=>{u.unsubscribe();}),S.clear(),a&&(a.close(),a=null),l="disconnected",i=null;},get isConnected(){return l==="connected"},get connectionState(){return l},get connectionId(){return i},on(u,m){f[u].add(m);},off(u,m){f[u].delete(m);},setAuth(u){c=u;}}}var F={apiKeyHeader:"x-vaif-key",timeout:3e4,retry:{maxRetries:3,retryDelay:1e3,maxRetryDelay:3e4,backoffMultiplier:2,retryOn:[429,500,502,503,504],retryOnNetworkError:true}};function Me(s){return {baseUrl:s.baseUrl.replace(/\/$/,""),apiKey:s.apiKey,apiKeyHeader:s.apiKeyHeader??F.apiKeyHeader,accessToken:s.accessToken,fetch:s.fetch??globalThis.fetch.bind(globalThis),timeout:s.timeout??F.timeout,retry:{maxRetries:s.retry?.maxRetries??F.retry.maxRetries,retryDelay:s.retry?.retryDelay??F.retry.retryDelay,maxRetryDelay:s.retry?.maxRetryDelay??F.retry.maxRetryDelay,backoffMultiplier:s.retry?.backoffMultiplier??F.retry.backoffMultiplier,retryOn:s.retry?.retryOn??[...F.retry.retryOn],retryOnNetworkError:s.retry?.retryOnNetworkError??F.retry.retryOnNetworkError},interceptors:s.interceptors??{}}}function Ee(s){let n=Me(s),e=W(n),t=_(n),r=H(n),o=G(n),a=z(n),l=Q(n),i=X(n),c=Y(n),g=Z(n),y=ee(n),k=te(n),S=ne(n),P=re(n),A=oe(n),f=se(n),R=ie(n),O=ae(n),C=le(n),d=ce(n),b=de(n),T=ue(n),u=ge(n),m=pe(n);return {from:e.from,auth:t,functions:r,storage:o,projects:a,orgs:l,schema:i,secrets:c,deployments:g,realtimeMonitoring:y,storageDashboard:k,integrations:S,billing:P,admin:A,flags:f,security:R,ai:O,bootstrap:C,templates:d,oauth:b,docs:T,mongodb:u,copilot:m,realtime:I=>me(n,I)}}Object.defineProperty(exports,"AuthError",{enumerable:true,get:function(){return auth.AuthError}});Object.defineProperty(exports,"InvalidCredentialsError",{enumerable:true,get:function(){return auth.InvalidCredentialsError}});Object.defineProperty(exports,"SessionExpiredError",{enumerable:true,get:function(){return auth.SessionExpiredError}});Object.defineProperty(exports,"SessionStorage",{enumerable:true,get:function(){return auth.SessionStorage}});Object.defineProperty(exports,"VaifAuthClient",{enumerable:true,get:function(){return auth.VaifAuthClient}});Object.defineProperty(exports,"authLocalStorage",{enumerable:true,get:function(){return auth.localStorage}});Object.defineProperty(exports,"authSessionStorage",{enumerable:true,get:function(){return auth.sessionStorage}});Object.defineProperty(exports,"cookieStorage",{enumerable:true,get:function(){return auth.cookieStorage}});Object.defineProperty(exports,"createAuthClient",{enumerable:true,get:function(){return auth.createAuthClient}});Object.defineProperty(exports,"getDefaultStorage",{enumerable:true,get:function(){return auth.getDefaultStorage}});Object.defineProperty(exports,"isBrowser",{enumerable:true,get:function(){return auth.isBrowser}});Object.defineProperty(exports,"isMFAChallenge",{enumerable:true,get:function(){return auth.isMFAChallenge}});Object.defineProperty(exports,"memoryStorage",{enumerable:true,get:function(){return auth.memoryStorage}});exports.VaifAuthError=E;exports.VaifConflictError=L;exports.VaifError=h;exports.VaifNetworkError=x;exports.VaifNotFoundError=$;exports.VaifRateLimitError=U;exports.VaifTimeoutError=V;exports.VaifValidationError=j;exports.createVaifClient=Ee;exports.isVaifAuthError=Pe;exports.isVaifError=be;exports.isVaifNetworkError=ke;exports.isVaifNotFoundError=fe;exports.isVaifRateLimitError=he;exports.isVaifValidationError=Ie;
1
+ 'use strict';var auth=require('@vaiftech/auth');var k=class s extends Error{constructor(n,e){super(n),this.name="VaifError",this.code=e.code,this.statusCode=e.statusCode,this.requestId=e.requestId,this.details=e.details;let t=Error;t.captureStackTrace&&t.captureStackTrace(this,s);}toJSON(){return {name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,details:this.details}}},E=class extends k{constructor(n,e){super(n,{code:e?.code??"AUTH_ERROR",statusCode:e?.statusCode??401,requestId:e?.requestId}),this.name="VaifAuthError";}},j=class extends k{constructor(n,e){super(n,{code:"VALIDATION_ERROR",statusCode:400,requestId:e?.requestId,details:e?.details??e?.fieldErrors}),this.name="VaifValidationError",this.fieldErrors=e?.fieldErrors;}},x=class extends k{constructor(n,e){super(n,{code:"NETWORK_ERROR"}),this.name="VaifNetworkError",this.cause=e;}},U=class extends k{constructor(n,e){super(n,{code:"RATE_LIMITED",statusCode:429}),this.name="VaifRateLimitError",this.retryAfter=e;}},$=class extends k{constructor(n,e){super(n,{code:"NOT_FOUND",statusCode:404,requestId:e}),this.name="VaifNotFoundError";}},L=class extends k{constructor(n,e){super(n,{code:"CONFLICT",statusCode:409,requestId:e}),this.name="VaifConflictError";}},V=class extends x{constructor(n,e){super(n),this.name="VaifTimeoutError",this.timeoutMs=e;}};function be(s){return s instanceof k}function fe(s){return s instanceof $}function Pe(s){return s instanceof E}function Ie(s){return s instanceof j}function ke(s){return s instanceof U}function he(s){return s instanceof x}async function Se(s){let n;try{n=await s.json();}catch{}let e=n?.message??n?.error??s.statusText??"Request failed",t=n?.requestId;switch(s.status){case 400:return new j(e,{details:n?.details,requestId:t});case 401:return new E(e,{code:"UNAUTHORIZED",statusCode:401,requestId:t});case 403:return new E(e,{code:"FORBIDDEN",statusCode:403,requestId:t});case 404:return new $(e,t);case 409:return new k(e,{code:"CONFLICT",statusCode:409,requestId:t,details:n?.details});case 422:return new j(e,{details:n?.details,requestId:t});case 429:{let r=s.headers.get("Retry-After"),o=r?parseInt(r,10):void 0;return new U(e,o)}default:return new k(e,{code:n?.error??"HTTP_ERROR",statusCode:s.status,requestId:t,details:n?.details})}}function Ce(s,n,e){return s instanceof x?e:s instanceof U?n.includes(429):s instanceof k&&s.statusCode?n.includes(s.statusCode):false}function ve(s,n,e,t,r){if(r!==void 0&&r>0)return Math.min(r*1e3,e);let o=n*Math.pow(t,s),a=Math.min(o,e),l=a*Math.random()*.25;return a+l}function Ae(s){return new Promise(n=>setTimeout(n,s))}async function Te(s,n){let{timeout:e=3e4,fetchFn:t,...r}=n,o=new AbortController,a=setTimeout(()=>o.abort(),e);try{let l=await t(s,{...r,signal:o.signal});if(clearTimeout(a),!l.ok)throw await Se(l);if(l.status===204)return;let i=await l.text();return i?JSON.parse(i):void 0}catch(l){throw clearTimeout(a),l instanceof k?l:l instanceof Error&&l.name==="AbortError"?new x("Request timed out"):l instanceof Error?new x(l.message,l):new x("Network request failed")}}function p(s){let{baseUrl:n,apiKey:e,apiKeyHeader:t,accessToken:r,fetch:o,timeout:a,retry:l,interceptors:i}=s;return async function(g,y={}){let h=`${n}${g}`,S=y.method||"GET",P={"Content-Type":"application/json",...y.headers??{}};if(e&&(P[t]=e),r){let O=typeof r=="function"?await r():r;P.Authorization=`Bearer ${O}`;}let A=y.timeout??a,f=l.maxRetries,T=null;for(let O=0;O<=f;O++){let C=Date.now(),d={url:h,path:g,method:S,headers:{...P},body:y.body,attempt:O};try{if(i.onRequest){let u=await i.onRequest(d);u&&(d=u);}let b=await Te(d.url,{...y,method:d.method,headers:d.headers,body:d.body,timeout:A,fetchFn:o}),R=Date.now()-C;if(i.onResponse){let u={request:d,data:b,status:200,headers:{},durationMs:R};await i.onResponse(u);}return b}catch(b){let R=Date.now()-C;T=b;let u=O<f&&Ce(b,l.retryOn,l.retryOnNetworkError);if(i.onError){let m={request:d,error:b,durationMs:R,willRetry:u};await i.onError(m);}if(u){let m=b instanceof U?b.retryAfter:void 0,I=ve(O,l.retryDelay,l.maxRetryDelay,l.backoffMultiplier,m);await Ae(I);continue}throw b}}throw T||new x("Request failed after retries")}}function v(s){let n=new URLSearchParams;for(let[t,r]of Object.entries(s))r!==void 0&&n.set(t,String(r));let e=n.toString();return e?`?${e}`:""}function Re(s){return JSON.stringify(s)}function q(s,n,e={}){let t={...e},r=()=>{let i={};if(t.limit!==void 0&&(i.limit=t.limit),t.offset!==void 0&&(i.offset=t.offset),t.where&&(i.where=Re(t.where)),t.orderBy){let c=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];i.orderBy=JSON.stringify(c);}return t.select&&t.select.length>0&&(i.select=t.select.join(",")),t.include&&t.include.length>0&&(i.include=JSON.stringify(t.include)),t.distinct&&t.distinct.length>0&&(i.distinct=t.distinct.join(",")),i},o=()=>v(r()),a=i=>q(s,n,{...t,...i}),l={async list(i){i&&(t={...t,...i});let c=o();return n(`/generated/${s}${c}`)},async get(i){let c={};t.select&&t.select.length>0&&(c.select=t.select.join(",")),t.include&&t.include.length>0&&(c.include=JSON.stringify(t.include));let g=v(c);return n(`/generated/${s}/${encodeURIComponent(i)}${g}`)},async first(){let i=await l.limit(1).list();return i.data.length>0?i.data[0]:null},async firstOrFail(){let i=await l.first();if(!i)throw new $(`No record found in table '${s}' matching the query`);return i},async create(i){return n(`/generated/${s}`,{method:"POST",body:JSON.stringify(i)})},async update(i,c){return n(`/generated/${s}/${encodeURIComponent(i)}`,{method:"PATCH",body:JSON.stringify(c)})},async delete(i){return n(`/generated/${s}/${encodeURIComponent(i)}`,{method:"DELETE"})},async createMany(i,c){return n(`/generated/${s}/batch`,{method:"POST",body:JSON.stringify({records:i,skipOnConflict:c?.skipOnConflict,returnRecords:c?.returnRecords})})},async updateMany(i,c){return n(`/generated/${s}/batch`,{method:"PATCH",body:JSON.stringify({data:i,where:t.where,returnRecords:c?.returnRecords})})},async deleteMany(){return n(`/generated/${s}/batch`,{method:"DELETE",body:JSON.stringify({where:t.where})})},async upsert(i,c){return n(`/generated/${s}/upsert`,{method:"POST",body:JSON.stringify({data:i,conflictFields:c.conflictFields,updateFields:c.updateFields})})},async count(){let i=r(),c=v(i);return (await n(`/generated/${s}/count${c}`)).count},async sum(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/sum${g}`)).sum},async avg(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/avg${g}`)).avg},async min(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/min${g}`)).min},async max(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/max${g}`)).max},async aggregate(i,c){return n(`/generated/${s}/aggregate`,{method:"POST",body:JSON.stringify({aggregates:i,where:c?.where||t.where,groupBy:c?.groupBy,having:c?.having})})},async paginate(i){let c=i.page||1,g=i.pageSize||20,y=(c-1)*g,h=r();h.limit=g,h.offset=y,h.includeCount=true;let S=v(h),P=await n(`/generated/${s}${S}`),A=P.total||P.data.length,f=Math.ceil(A/g);return {data:P.data,pageInfo:{total:A,page:c,pageSize:g,pageCount:f,hasNextPage:c<f,hasPrevPage:c>1}}},async cursorPaginate(i){let c=r();c.limit=i.limit||20,i.cursor&&(c.cursor=i.cursor);let g=v(c),y=await n(`/generated/${s}/cursor${g}`);return {data:y.data,nextCursor:y.nextCursor,prevCursor:y.prevCursor,hasMore:y.hasMore}},where(i){if(t.where){let c=t.where;return a({where:{AND:[...Array.isArray(c)?c:[c],i]}})}return a({where:i})},orderBy(i,c="asc"){let g={field:i,direction:c};if(t.orderBy){let y=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];return a({orderBy:[...y,g]})}return a({orderBy:g})},select(...i){return a({select:i})},limit(i){return a({limit:i})},offset(i){return a({offset:i})},include(i){let c=t.include||[];return a({include:[...c,i]})},distinct(...i){return a({distinct:i})}};return l}function W(s){let n=p(s);return {from(e){return q(e,n)},async raw(e,t){return n("/generated/raw",{method:"POST",body:JSON.stringify({query:e,params:t})})},async transaction(e,t){return n("/generated/transaction",{method:"POST",body:JSON.stringify({operations:e,isolationLevel:t?.isolationLevel,timeout:t?.timeout})})},async withTransaction(e,t){let o=(await n("/generated/transaction/start",{method:"POST",body:JSON.stringify({isolationLevel:t?.isolationLevel,timeout:t?.timeout})})).transactionId,a=(i,c)=>{let g=new Headers(c?.headers);return g.set("X-Transaction-Id",o),n(i,{...c,headers:g})},l={from(i){return q(i,a)},async raw(i,c){return a("/generated/raw",{method:"POST",body:JSON.stringify({query:i,params:c})})},async transaction(){throw new k("Nested transactions are not supported",{code:"NESTED_TRANSACTION"})},async withTransaction(){throw new k("Nested transactions are not supported",{code:"NESTED_TRANSACTION"})}};try{let i=await e(l);return await n("/generated/transaction/commit",{method:"POST",body:JSON.stringify({transactionId:o})}),i}catch(i){throw await n("/generated/transaction/rollback",{method:"POST",body:JSON.stringify({transactionId:o})}).catch(()=>{}),i}}}}function _(s){let n=p(s);return {async signUp(e,t,r){return n("/auth/signup",{method:"POST",body:JSON.stringify({email:e,password:t,name:r?.name,phone:r?.phone,metadata:r?.metadata,redirectUrl:r?.redirectUrl})})},async login(e,t,r){return n("/auth/login",{method:"POST",body:JSON.stringify({email:e,password:t,mfaCode:r?.mfaCode,rememberMe:r?.rememberMe})})},async logout(){await n("/auth/logout",{method:"POST"});},async logoutAll(){await n("/auth/logout-all",{method:"POST"});},async getUser(){return (await n("/auth/me")).user},async updateProfile(e){return (await n("/users/me",{method:"PATCH",body:JSON.stringify(e)})).user},async changePassword(e){return n("/users/me/change-password",{method:"POST",body:JSON.stringify(e)})},async requestPasswordReset(e){return n("/auth/forgot-password",{method:"POST",body:JSON.stringify(e)})},async confirmPasswordReset(e){return n("/auth/reset-password",{method:"POST",body:JSON.stringify(e)})},async requestEmailVerification(e){return n("/auth/verify-email/send",{method:"POST",body:JSON.stringify(e||{})})},async confirmEmailVerification(e){return n("/auth/verify-email/confirm",{method:"POST",body:JSON.stringify(e)})},async getOAuthSignInUrl(e){return n("/auth/oauth/authorize",{method:"POST",body:JSON.stringify(e)})},async handleOAuthCallback(e){return n("/auth/oauth/callback",{method:"POST",body:JSON.stringify(e)})},async linkOAuthProvider(e){return n("/auth/oauth/link",{method:"POST",body:JSON.stringify(e)})},async unlinkOAuthProvider(e){return n(`/auth/oauth/unlink/${e}`,{method:"POST"})},async listLinkedProviders(){return n("/auth/oauth/providers")},async requestMagicLink(e){return n("/auth/magic-link/send",{method:"POST",body:JSON.stringify(e)})},async verifyMagicLink(e){return n("/auth/magic-link/verify",{method:"POST",body:JSON.stringify(e)})},async requestPhoneVerification(e){return n("/auth/phone/send",{method:"POST",body:JSON.stringify(e)})},async confirmPhoneVerification(e){return n("/auth/phone/verify",{method:"POST",body:JSON.stringify(e)})},async setupMFA(e){return n("/auth/mfa/setup",{method:"POST",body:JSON.stringify({method:e})})},async enableMFA(e){return n("/auth/mfa/enable",{method:"POST",body:JSON.stringify({code:e})})},async disableMFA(e){return n("/auth/mfa/disable",{method:"POST",body:JSON.stringify({code:e})})},async verifyMFA(e,t){return n("/auth/mfa/verify",{method:"POST",body:JSON.stringify({mfaToken:e,code:t})})},async regenerateBackupCodes(){return n("/auth/mfa/backup-codes",{method:"POST"})},async refreshToken(e){return n("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})})},async listSessions(){return n("/auth/sessions")},async revokeSession(e){return n(`/auth/sessions/${e}`,{method:"DELETE"})},async revokeOtherSessions(){return n("/auth/sessions/revoke-others",{method:"POST"})}}}function K(s){return new Promise(n=>setTimeout(n,s))}function H(s){let n=p(s);async function e(t,r,o){let a=o?.retry||{},l=a.maxRetries??0,i=a.initialDelay??1e3,c=a.maxDelay??3e4,g=a.backoffMultiplier??2,y=a.retryOnStatus??[429,500,502,503,504],h=a.retryOnNetworkError??true,S=null,P=i;for(let A=0;A<=l;A++)try{let f={};o?.version!==void 0&&(f.version=o.version),o?.includeLogs&&(f.includeLogs=!0);let T=v(f),O=await n(`/functions/${t}/invoke${T}`,{method:"POST",body:JSON.stringify(r??{}),headers:o?.headers});if(y.includes(O.status)&&A<l){S=new Error(`Function returned status ${O.status}`),await K(P),P=Math.min(P*g,c);continue}return O}catch(f){S=f;let T=f instanceof TypeError||f.message?.includes("network")||f.message?.includes("fetch");if(h&&T&&A<l){await K(P),P=Math.min(P*g,c);continue}throw f}throw S||new Error("Function invocation failed after retries")}return {invoke:e,async invokeByName(t,r,o){let a={};o?.version!==void 0&&(a.version=o.version),o?.includeLogs&&(a.includeLogs=true);let l=v(a);return n(`/functions/name/${encodeURIComponent(t)}/invoke${l}`,{method:"POST",body:JSON.stringify(r??{}),headers:o?.headers})},async batchInvoke(t,r){let a=(await Promise.allSettled(t.map(l=>this.invoke(l.functionId,l.input,r)))).map((l,i)=>l.status==="fulfilled"?{functionId:t[i].functionId,success:true,result:l.value}:{functionId:t[i].functionId,success:false,error:l.reason?.message||"Unknown error"});return {results:a,successCount:a.filter(l=>l.success).length,errorCount:a.filter(l=>!l.success).length}},rpc(t,r){let o=this,a=async(l,i)=>{let c={...r,...i};return (await e(t,{body:l},c)).data};return Object.defineProperty(a,"id",{value:t,writable:false}),a.getInfo=()=>o.get(t),a.getInvocations=l=>o.getInvocations({...l,functionId:t}),a},async list(t){let r={envId:t.envId,enabled:t.enabled,limit:t.limit,offset:t.offset},o=v(r);return n(`/functions/project/${t.projectId}${o}`)},async get(t){return n(`/functions/${t}`)},async getByName(t,r){return n(`/functions/project/${r}/name/${encodeURIComponent(t)}`)},async create(t){return n("/functions",{method:"POST",body:JSON.stringify(t)})},async update(t,r){return n(`/functions/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(t){return n(`/functions/${t}`,{method:"DELETE"})},async enable(t){return this.update(t,{enabled:true})},async disable(t){return this.update(t,{enabled:false})},async deploy(t,r,o){return n(`/functions/${t}/source`,{method:"PUT",body:JSON.stringify({sourceCode:r})})},async getSource(t,r){return {sourceCode:(await n(`/functions/${t}`)).sourceCode||"",version:1}},async listVersions(t){return (await n(`/functions/${t}/versions`)).versions},async rollback(t,r){return n(`/functions/${t}/rollback`,{method:"POST",body:JSON.stringify({version:r})})},async getEnvVars(t){return (await n(`/functions/${t}/env`)).envVars},async setEnvVars(t,r){return n(`/functions/${t}/env`,{method:"PUT",body:JSON.stringify({envVars:r})})},async deleteEnvVar(t,r){return n(`/functions/${t}/env/${encodeURIComponent(r)}`,{method:"DELETE"})},async bindSecrets(t,r){return n(`/functions/${t}/secrets`,{method:"PUT",body:JSON.stringify({secrets:r})})},async setSchedule(t,r){return n(`/functions/${t}/schedule`,{method:"PUT",body:JSON.stringify(r)})},async removeSchedule(t){return n(`/functions/${t}/schedule`,{method:"DELETE"})},async getInvocations(t){let r={functionId:t.functionId,projectId:t.projectId,status:t.status,since:t.since,until:t.until,limit:t.limit,offset:t.offset},o=v(r);return (await n(`/functions/invocations${o}`)).invocations},async getInvocation(t){return n(`/functions/invocations/${t}`)},async getLogs(t,r){let o={since:r?.since,until:r?.until,level:r?.level,limit:r?.limit},a=v(o);return (await n(`/functions/${t}/logs${a}`)).logs}}}function G(s){let n=p(s),e="default";return {async getUploadUrl(t,r){return n("/storage/upload-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,sizeBytes:r?.sizeBytes,metadata:r?.metadata,isPublic:r?.isPublic,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,upsert:r?.upsert})})},async getDownloadUrl(t,r){return n("/storage/download-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,expiresIn:r?.expiresIn,download:r?.download,transform:r?.transform})})},async createSignedUrl(t,r=3600,o){return (await this.getDownloadUrl(t,{...o,expiresIn:r})).url},async createSignedUrls(t,r=3600,o){return await Promise.all(t.map(async l=>({key:l,url:await this.createSignedUrl(l,r,o)})))},async upload(t,r,o){let a=r instanceof Blob?r:new Blob([r]),l=a.size,i=o?.contentType||(r instanceof File?r.type:void 0)||"application/octet-stream",c=await this.getUploadUrl(t,{...o,contentType:i,sizeBytes:l}),g=await s.fetch(c.url,{method:"PUT",body:a,headers:{"Content-Type":i,...o?.cacheControl&&{"Cache-Control":o.cacheControl},...o?.contentDisposition&&{"Content-Disposition":o.contentDisposition}}});if(!g.ok)throw new k(`Upload failed: ${g.statusText}`,{code:"UPLOAD_ERROR",statusCode:g.status});let y=o?.bucket||e,h=c.url.split("?")[0];return {ok:true,key:t,bucket:y,url:h,publicUrl:o?.isPublic?this.getPublicUrl(t,{bucket:y}):void 0,size:l,contentType:i}},async uploadFromUrl(t,r,o){return n("/storage/upload-from-url",{method:"POST",body:JSON.stringify({key:t,url:r,bucket:o?.bucket||e,contentType:o?.contentType,metadata:o?.metadata,isPublic:o?.isPublic,timeout:o?.timeout})})},async download(t,r){let o=await this.getDownloadUrl(t,r),a=await s.fetch(o.url);if(!a.ok)throw new k(`Download failed: ${a.statusText}`,{code:"DOWNLOAD_ERROR",statusCode:a.status});return a.blob()},async list(t){let r={bucket:t?.bucket||e,prefix:t?.prefix,delimiter:t?.delimiter,limit:t?.limit,cursor:t?.cursor,includeUrls:t?.includeUrls},o=v(r);return n(`/storage/files${o}`)},async getMetadata(t,r){let o=r?.bucket||e;return n(`/storage/files/${encodeURIComponent(o)}/${encodeURIComponent(t)}/metadata`)},async updateMetadata(t,r,o){let a=o?.bucket||e;return n(`/storage/files/${encodeURIComponent(a)}/${encodeURIComponent(t)}/metadata`,{method:"PATCH",body:JSON.stringify(r)})},async exists(t,r){try{return await this.getMetadata(t,r),!0}catch{return false}},async copy(t,r,o){return n("/storage/files/copy",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:o?.sourceBucket||e,destinationKey:r,destinationBucket:o?.destinationBucket||o?.sourceBucket||e,metadata:o?.metadata})})},async move(t,r,o){return n("/storage/files/move",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:o?.sourceBucket||e,destinationKey:r,destinationBucket:o?.destinationBucket||o?.sourceBucket||e,metadata:o?.metadata})})},async delete(t,r){let o=r?.bucket||e;await n(`/storage/files/${encodeURIComponent(o)}/${encodeURIComponent(t)}`,{method:"DELETE"});},async deleteMany(t,r){return n("/storage/files/delete-batch",{method:"POST",body:JSON.stringify({keys:t,bucket:r?.bucket||e})})},getPublicUrl(t,r){let o=r?.bucket||e;return `${s.baseUrl.replace("/api","")}/storage/${encodeURIComponent(o)}/${encodeURIComponent(t)}`},async createBucket(t,r){return n("/storage/buckets",{method:"POST",body:JSON.stringify({name:t,isPublic:r?.isPublic,allowedMimeTypes:r?.allowedMimeTypes,maxFileSize:r?.maxFileSize,fileSizeLimit:r?.fileSizeLimit})})},async getBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}`)},async updateBucket(t,r){return n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})},async listBuckets(){return (await n("/storage/buckets")).buckets},async deleteBucket(t){await n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"DELETE"});},async emptyBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}/empty`,{method:"POST"})},async createMultipartUpload(t,r){return n("/storage/multipart/create",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,metadata:r?.metadata,partSize:r?.partSize})})},async uploadPart(t,r,o){let a=o instanceof Blob?o:new Blob([o]),{url:l}=await n(`/storage/multipart/${t}/part-url`,{method:"POST",body:JSON.stringify({partNumber:r})}),i=await s.fetch(l,{method:"PUT",body:a});if(!i.ok)throw new k(`Part upload failed: ${i.statusText}`,{code:"UPLOAD_PART_ERROR",statusCode:i.status});let c=i.headers.get("etag")||"";return {partNumber:r,etag:c}},async completeMultipartUpload(t,r){return n(`/storage/multipart/${t}/complete`,{method:"POST",body:JSON.stringify({parts:r})})},async abortMultipartUpload(t){await n(`/storage/multipart/${t}/abort`,{method:"POST"});}}}function z(s){let n=p(s);return {async list(e){let t=new URLSearchParams;e?.orgId&&t.set("orgId",e.orgId);let r=t.toString();return n(`/projects${r?`?${r}`:""}`)},async get(e){return n(`/projects/${e}`)},async create(e){return n("/projects",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async delete(e){return n(`/projects/${e}`,{method:"DELETE"})},async getComputeSettings(e){return n(`/projects/${e}/settings/compute`)},async updateComputeSettings(e,t){return n(`/projects/${e}/settings/compute`,{method:"PATCH",body:JSON.stringify(t)})},async getApiSettings(e){return n(`/projects/${e}/settings/api`)},async updateApiSettings(e,t){return n(`/projects/${e}/settings/api`,{method:"PATCH",body:JSON.stringify(t)})},async getJwtSettings(e){return n(`/projects/${e}/settings/jwt`)},async updateJwtSettings(e,t){return n(`/projects/${e}/settings/jwt`,{method:"PATCH",body:JSON.stringify(t)})},async rotateJwtSecret(e){return n(`/projects/${e}/settings/jwt/rotate`,{method:"POST"})},async getAddons(e){return n(`/projects/${e}/settings/addons`)},async updateAddons(e,t){return n(`/projects/${e}/settings/addons`,{method:"PATCH",body:JSON.stringify({enabledAddons:t})})},async getApiKeys(e){return n(`/projects/${e}/api-keys`)},async createApiKey(e,t){return n(`/projects/${e}/api-keys`,{method:"POST",body:JSON.stringify(t??{})})},async revokeApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/revoke`,{method:"POST"})},async rotateApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/rotate`,{method:"POST"})},async setCustomDomain(e,t,r){return n(`/projects/${e}/environments/${t}`,{method:"PATCH",body:JSON.stringify({customDomain:r})})},async getDomainVerificationInstructions(e,t){return n(`/projects/${e}/environments/${t}/domain-verification`)},async verifyDomainTxt(e,t){return n(`/projects/${e}/environments/${t}/verify-domain`,{method:"POST"})},async verifyDomainCname(e,t){return n(`/projects/${e}/environments/${t}/verify-cname`,{method:"POST"})},async getDomainStatus(e,t){return n(`/projects/${e}/environments/${t}/domain-status`)},async provisionSsl(e,t){return n(`/projects/${e}/environments/${t}/provision-ssl`,{method:"POST"})},async removeCustomDomain(e,t){return n(`/projects/${e}/environments/${t}`,{method:"PATCH",body:JSON.stringify({customDomain:null})})},async listApiKeys(e){return (await n(`/projects/${e}/api-keys`)).keys}}}function Q(s){let n=p(s);return {async list(){return n("/orgs")},async create(e){return n("/orgs",{method:"POST",body:JSON.stringify(e)})},async getProfile(e){return (await n(`/orgs/${e}/profile`)).profile||{}},async updateProfile(e,t){return (await n(`/orgs/${e}/profile`,{method:"PATCH",body:JSON.stringify(t)})).profile},async listBillingContacts(e){return (await n(`/orgs/${e}/billing-contacts`)).contacts},async addBillingContact(e,t){return n(`/orgs/${e}/billing-contacts`,{method:"POST",body:JSON.stringify(t)})},async removeBillingContact(e,t){return n(`/orgs/${e}/billing-contacts/${t}`,{method:"DELETE"})},async listMembers(e){return (await n(`/orgs/${e}/members`)).members},async inviteMember(e,t){return n(`/orgs/${e}/members/invite`,{method:"POST",body:JSON.stringify(t)})},async listInvites(e){return (await n(`/orgs/${e}/invites`)).invites},async cancelInvite(e,t){return n(`/orgs/${e}/invites/${t}`,{method:"DELETE"})},async removeMember(e,t){return n(`/orgs/${e}/members/${t}`,{method:"DELETE"})},async updateMemberRole(e,t,r){return n(`/orgs/${e}/members/${t}/role`,{method:"PATCH",body:JSON.stringify({role:r})})},async getMyMembership(e){try{return (await n(`/orgs/${e}/membership`)).membership}catch{return null}}}}function X(s){let n=p(s);return {async preview(e){return n("/schema-engine/preview",{method:"POST",body:JSON.stringify(e)})},async apply(e){return n("/schema-engine/apply",{method:"POST",body:JSON.stringify(e)})},async getMigrations(e,t){let r=t?`/schema-engine/migrations/project/${e}?limit=${t}`:`/schema-engine/migrations/project/${e}`;return n(r)},async saveSchema(e){return n("/schemas/",{method:"POST",body:JSON.stringify(e)})},async getSchemas(e){return n(`/schemas/project/${e}`)}}}function Y(s){let n=p(s);return {async create(e){return n("/functions/secrets",{method:"POST",body:JSON.stringify(e)})},async list(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/functions/secrets/project/${e}${o?`?${o}`:""}`;return n(a)},async reveal(e){return n(`/functions/secrets/${e}/value`)},async update(e,t){return n(`/functions/secrets/${e}`,{method:"PUT",body:JSON.stringify({value:t})})},async delete(e){return n(`/functions/secrets/${e}`,{method:"DELETE"})}}}function Z(s){let n=p(s);return {async list(e,t){let r=new URLSearchParams;t&&r.set("env",t);let o=r.toString(),a=`/deployments/project/${e}${o?`?${o}`:""}`;return (await n(a)).deployments},async get(e){let t=await n(`/deployments/${e}`);return {...t.deployment,steps:t.steps}},async getSteps(e){return (await n(`/deployments/${e}/steps`)).steps},async promote(e){let t={projectId:e.projectId,fromEnv:e.sourceEnv,toEnv:e.targetEnv},r=await n("/deployments/promote",{method:"POST",body:JSON.stringify(t)}),o=await n(`/deployments/${r.deploymentId}`);return {deployment:{...o.deployment,steps:o.steps}}},async rollback(e){return n(`/deployments/${e}/rollback`,{method:"POST"})},async listTokens(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/deployments/tokens/project/${encodeURIComponent(e)}${o?`?${o}`:""}`;return (await n(a)).tokens},async createToken(e){return n("/deployments/tokens",{method:"POST",body:JSON.stringify(e)})},async revokeToken(e){return n(`/deployments/tokens/${encodeURIComponent(e)}/revoke`,{method:"POST"})}}}function ee(s){let n=p(s);return {async getStats(e){return n(`/realtime/stats/project/${e}`)},async getConnections(e){return (await n(`/realtime/connections/project/${e}`)).connections},async getSubscriptions(e){return (await n(`/realtime/subscriptions/project/${e}`)).subscriptions},async getEvents(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.source&&t.source!=="all"&&r.set("source",t.source),t?.level&&t.level!=="all"&&r.set("level",t.level);let o=r.toString(),a=`/realtime/events/project/${e}${o?`?${o}`:""}`;return (await n(a)).events},async getStatus(e){return n(`/realtime/status/project/${e}`)},async install(e){return n("/realtime/install",{method:"POST",body:JSON.stringify(e)})},async enableAll(e){return n("/realtime/enable-all",{method:"POST",body:JSON.stringify(e)})}}}function te(s){let n=p(s);return {async listBuckets(e,t){let r=new URLSearchParams;r.set("projectId",e),t&&r.set("envId",t);let a=`/storage/buckets?${r.toString()}`;return (await n(a)).buckets},async getBucket(e){return (await n(`/buckets/${e}`)).bucket},async createBucket(e){return (await n("/buckets",{method:"POST",body:JSON.stringify(e)})).bucket},async updateBucket(e,t){return (await n(`/buckets/${e}`,{method:"PUT",body:JSON.stringify(t)})).bucket},async deleteBucket(e){return n(`/buckets/${e}`,{method:"DELETE"})},async listFiles(e,t){let r=new URLSearchParams;t?.prefix&&r.set("prefix",t.prefix),t?.maxKeys&&r.set("maxKeys",String(t.maxKeys)),t?.continuationToken&&r.set("continuationToken",t.continuationToken);let o=r.toString(),a=`/buckets/${e}/files${o?`?${o}`:""}`;return n(a)},async deleteFile(e,t){return n(`/buckets/${e}/files?key=${encodeURIComponent(t)}`,{method:"DELETE"})},async getSignedUrl(e,t,r){return n(`/buckets/${e}/signed-url`,{method:"POST",body:JSON.stringify({key:t,expiresIn:r})})},async getUploadUrl(e,t,r){return n(`/buckets/${e}/upload-url`,{method:"POST",body:JSON.stringify({key:t,...r})})},async uploadFile(e,t,r,o){let a=o?.prefix?`${o.prefix}${t}`:t,l=o?.contentType??(r instanceof Blob?r.type:"application/octet-stream"),i=new URLSearchParams;return i.set("key",a),l&&i.set("contentType",l),n(`/buckets/${e}/upload?${i.toString()}`,{method:"POST",body:r,headers:{"Content-Type":l||"application/octet-stream"}})}}}function ne(s){let n=p(s);return {async list(e,t){let r={type:t?.type,enabled:t?.enabled},o=v(r);return (await n(`/integrations/subscriptions/project/${e}${o}`)).subscriptions},async get(e){return n(`/integrations/subscriptions/${e}`)},async create(e){return (await n("/integrations/subscriptions",{method:"POST",body:JSON.stringify(e)})).subscription},async update(e,t){return (await n(`/integrations/subscriptions/${e}`,{method:"PATCH",body:JSON.stringify(t)})).subscription},async delete(e){return n(`/integrations/subscriptions/${e}`,{method:"DELETE"})},async enable(e){return this.update(e,{enabled:true})},async disable(e){return this.update(e,{enabled:false})},async test(e){return n(`/integrations/subscriptions/${e}/test`,{method:"POST"})},async publish(e){return n("/integrations/events/publish",{method:"POST",body:JSON.stringify(e)})},async publishBatch(e){return (await n("/integrations/events/publish-batch",{method:"POST",body:JSON.stringify({events:e})})).results},async listEvents(e){let t={envId:e.envId,source:e.source,name:e.name,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/events/project/${e.projectId}${r}`)).events},async getEvent(e){return n(`/integrations/events/${e}`)},async getDeliveries(e){let t={subscriptionId:e.subscriptionId,eventId:e.eventId,status:e.status,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/deliveries${r}`)).deliveries},async getDelivery(e){return n(`/integrations/deliveries/${e}`)},async retryDelivery(e){return n(`/integrations/deliveries/${e}/retry`,{method:"POST"})},async retryAllFailed(e){return n(`/integrations/subscriptions/${e}/retry-failed`,{method:"POST"})},async getDlq(e,t){let r={limit:t?.limit,offset:t?.offset},o=v(r);return (await n(`/integrations/dlq/project/${e}${o}`)).deliveries},async purgeDlq(e,t){return n(`/integrations/dlq/project/${e}/purge`,{method:"POST",body:JSON.stringify({olderThan:t.olderThan})})},async replayDlq(e,t){return n(`/integrations/dlq/project/${e}/replay`,{method:"POST",body:JSON.stringify(t)})},verifySignature(e){let t=e.tolerance??300;try{let r=e.signature.split(","),o=r.find(f=>f.startsWith("t=")),a=r.find(f=>f.startsWith("v1="));if(!o||!a)return !1;let l=parseInt(o.slice(2),10),i=a.slice(3),c=Math.floor(Date.now()/1e3);if(Math.abs(c-l)>t)return !1;let g=`${l}.${e.payload}`,y=new TextEncoder,h=y.encode(e.secret),S=y.encode(g),P=Array.from(h).concat(Array.from(S)).reduce((f,T)=>f+T,0).toString(16);if(i.length!==P.length)return !1;let A=0;for(let f=0;f<i.length;f++)A|=i.charCodeAt(f)^P.charCodeAt(f);return A===0}catch{return false}},generateSecret(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="whsec_";for(let r=0;r<32;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}}}function re(s){let n=p(s);return {async getSummary(e){return n(`/billing/org/${e}/summary`)},async getEntitlements(e){return n(`/entitlements/org/${e}`)},async checkEntitlement(e,t){return n(`/entitlements/org/${e}/check`,{method:"POST",body:JSON.stringify(t)})},async getPlans(){return (await n("/pricing/plans")).plans},async createCheckout(e){return n("/billing/checkout",{method:"POST",body:JSON.stringify(e)})},async verifyCheckoutSession(e){return n(`/billing/checkout/verify/${e}`)},async openPortal(e){return n(`/billing/org/${e.orgId}/portal`,{method:"POST",body:JSON.stringify({returnUrl:e.returnUrl})})},async getAIUsageSummary(e){return n(`/ai-usage/org/${e}/summary`)},async getAIUsageHistory(e,t=30){return n(`/ai-usage/org/${e}/history?days=${t}`)},async getAIUsageBreakdown(e){return n(`/ai-usage/org/${e}/breakdown`)},async getRecentAIRequests(e,t=50,r=0){return n(`/ai-usage/org/${e}/recent?limit=${t}&offset=${r}`)}}}function oe(s){let n=p(s);return {async getOverview(){return n("/admin/overview")},async listUsers(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/users${r?`?${r}`:""}`)},async getUser(e){return n(`/admin/users/${e}`)},async updateUserStatus(e,t){return n(`/admin/users/${e}/status`,{method:"PATCH",body:JSON.stringify({status:t})})},async updateUserAdmin(e,t){return n(`/admin/users/${e}/admin`,{method:"PATCH",body:JSON.stringify({isAdmin:t})})},async listOrganizations(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.plan&&t.set("plan",e.plan),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/organizations${r?`?${r}`:""}`)},async getOrganization(e){return n(`/admin/organizations/${e}`)},async updateOrganization(e,t){return n(`/admin/organizations/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async listProjects(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.orgId&&t.set("orgId",e.orgId),e?.region&&t.set("region",e.region),e?.tenancy&&t.set("tenancy",e.tenancy),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/projects${r?`?${r}`:""}`)},async getProject(e){return n(`/admin/projects/${e}`)},async updateProject(e,t){return n(`/admin/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getProjectResources(e){return n(`/admin/resources/project/${e}`)},async setDedicatedDb(e){return n(`/admin/resources/project/${e.projectId}/db`,{method:"POST",body:JSON.stringify({connectionString:e.connectionString})})},async listIncidents(e="open"){return (await n(`/admin/incidents?status=${e}`)).incidents},async createIncident(e){return n("/admin/incidents",{method:"POST",body:JSON.stringify(e)})},async acknowledgeIncident(e){return n(`/admin/incidents/${e}/ack`,{method:"POST"})},async resolveIncident(e){return n(`/admin/incidents/${e}/resolve`,{method:"POST"})},async listRegions(){return n("/admin/regions")},async updateRegion(e,t){return n(`/admin/regions/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getHealthComponents(){return n("/admin/health/components")},async updateHealthComponent(e,t){return n(`/admin/health/components/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getSystemInfo(){return n("/admin/system/info")},async listQueues(){return n("/admin/queues")},async listDlqMessages(e){let t=new URLSearchParams;e?.queue&&t.set("queue",e.queue),e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/dlq${r?`?${r}`:""}`)},async retryDlqMessage(e){return n(`/admin/dlq/${e}/retry`,{method:"POST"})},async archiveDlqMessage(e){return n(`/admin/dlq/${e}`,{method:"DELETE"})},async listFeatureFlags(){return (await n("/flags")).flags},async createFeatureFlag(e,t){return n("/flags",{method:"POST",body:JSON.stringify({key:e,enabled:t})})},async updateFeatureFlag(e,t){return n(`/flags/${e}`,{method:"PUT",body:JSON.stringify({enabled:t})})},async deleteFeatureFlag(e){return n(`/flags/${e}`,{method:"DELETE"})},async listAdmins(){return (await n("/admin/admins")).admins||[]},async addAdmin(e,t,r){return n("/admin/admins",{method:"POST",body:JSON.stringify({userId:e,role:t,notes:r})})},async updateAdmin(e,t){return n(`/admin/admins/${e}`,{method:"PUT",body:JSON.stringify(t)})},async removeAdmin(e){return n(`/admin/admins/${e}`,{method:"DELETE"})},async getSettings(e){let t=e?`?category=${e}`:"";return n(`/admin/settings${t}`)},async updateSetting(e,t){return n(`/admin/settings/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({value:t})})},async listAIModels(){return n("/admin/ai/models")},async getAIModel(e){return n(`/admin/ai/models/${e}`)},async createAIModel(e){return n("/admin/ai/models",{method:"POST",body:JSON.stringify(e)})},async updateAIModel(e,t){return n(`/admin/ai/models/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteAIModel(e){return n(`/admin/ai/models/${e}`,{method:"DELETE"})},async toggleAIModel(e,t,r){return n(`/admin/ai/models/${e}/toggle`,{method:"POST",body:JSON.stringify({enabled:t,disabledMessage:r})})},async listAISessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/workspace/sessions${r?`?${r}`:""}`)},async getAISession(e){return n(`/admin/ai/workspace/sessions/${e}`)},async deleteAISession(e){return n(`/admin/ai/workspace/sessions/${e}`,{method:"DELETE"})},async listGeneratedBackends(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/backends${r?`?${r}`:""}`)},async getGeneratedBackend(e){return n(`/admin/ai/backends/${e}`)},async deleteGeneratedBackend(e){return n(`/admin/ai/backends/${e}`,{method:"DELETE"})},async listPromptTemplates(e){let t=new URLSearchParams;e?.category&&t.set("category",e.category),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/prompt-templates${r?`?${r}`:""}`)},async createPromptTemplate(e){return n("/admin/ai/prompt-templates",{method:"POST",body:JSON.stringify(e)})},async updatePromptTemplate(e,t){return n(`/admin/ai/prompt-templates/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deletePromptTemplate(e){return n(`/admin/ai/prompt-templates/${e}`,{method:"DELETE"})},async listContextSnapshots(e){let t=new URLSearchParams;e?.projectId&&t.set("projectId",e.projectId),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/context-snapshots${r?`?${r}`:""}`)},async invalidateContextSnapshot(e){return n(`/admin/ai/context-snapshots/${e}/invalidate`,{method:"POST"})},async deleteContextSnapshot(e){return n(`/admin/ai/context-snapshots/${e}`,{method:"DELETE"})},async getCopilotOverview(){return n("/admin/copilot/overview")},async listCopilotSessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/sessions${r?`?${r}`:""}`)},async getCopilotSession(e){return n(`/admin/copilot/sessions/${e}`)},async deleteCopilotSession(e){return n(`/admin/copilot/sessions/${e}`,{method:"DELETE"})},async listCopilotMemories(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.projectId&&t.set("projectId",e.projectId),e?.memoryType&&t.set("memoryType",e.memoryType),e?.importance&&t.set("importance",e.importance),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/memories${r?`?${r}`:""}`)},async getCopilotMemoryStats(){return n("/admin/copilot/memories/stats")},async getCopilotMemory(e){return n(`/admin/copilot/memories/${e}`)},async updateCopilotMemory(e,t){return n(`/admin/copilot/memories/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteCopilotMemory(e){return n(`/admin/copilot/memories/${e}`,{method:"DELETE"})},async cleanupExpiredMemories(){return n("/admin/copilot/memories/cleanup",{method:"POST"})},async listClassificationFeedback(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.feedbackType&&t.set("feedbackType",e.feedbackType),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/classification-feedback${r?`?${r}`:""}`)},async exportTrainingData(e){let t=new URLSearchParams;e?.format&&t.set("format",e.format),e?.dataType&&t.set("dataType",e.dataType),e?.minConfidence!==void 0&&t.set("minConfidence",String(e.minConfidence)),e?.limit&&t.set("limit",String(e.limit)),e?.includeExecuted!==void 0&&t.set("includeExecuted",String(e.includeExecuted)),e?.includeSuccessful!==void 0&&t.set("includeSuccessful",String(e.includeSuccessful));let r=t.toString();return n(`/admin/copilot/training-data/export${r?`?${r}`:""}`)},async getTrainingDataStats(){return n("/admin/copilot/training-data/stats")},async listErrors(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.path&&t.set("path",e.path),e?.errorCode&&t.set("errorCode",e.errorCode),e?.status&&t.set("status",e.status),e?.environment&&t.set("environment",e.environment),e?.startDate&&t.set("startDate",e.startDate),e?.endDate&&t.set("endDate",e.endDate),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/errors${r?`?${r}`:""}`)},async getErrorStats(){return n("/admin/errors/stats")},async getError(e){return n(`/admin/errors/${e}`)},async resolveError(e,t){return n(`/admin/errors/${e}/resolve`,{method:"PUT",body:JSON.stringify({notes:t})})},async deleteError(e){return n(`/admin/errors/${e}`,{method:"DELETE"})},async bulkDeleteErrors(e){let t=e?`?olderThanDays=${e}`:"";return n(`/admin/errors${t}`,{method:"DELETE"})},async getAIWorkspaceOverview(){return n("/admin/ai-workspace/overview")},async listAIWorkspaceSessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.taskType&&t.set("taskType",e.taskType),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai-workspace/sessions${r?`?${r}`:""}`)},async getAIWorkspaceSession(e){return n(`/admin/ai-workspace/sessions/${e}`)},async deleteAIWorkspaceSession(e){return n(`/admin/ai-workspace/sessions/${e}`,{method:"DELETE"})}}}function se(s){let n=p(s);return {async list(){return (await n("/flags")).flags},async create(e){return n("/flags",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/flags/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)})},async delete(e){return n(`/flags/${encodeURIComponent(e)}`,{method:"DELETE"})}}}function ie(s){let n=p(s);return {async getOverview(e){return (await n(`/security/overview/${encodeURIComponent(e)}`)).overview},async getAuditLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));let o=r.toString(),a=`/security/audit/${encodeURIComponent(e)}${o?`?${o}`:""}`;return n(a)},async listEnvVars(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/projects/${encodeURIComponent(e)}/env-vars${o?`?${o}`:""}`;return (await n(a)).envVars},async createEnvVar(e,t){return (await n(`/projects/${encodeURIComponent(e)}/env-vars`,{method:"POST",body:JSON.stringify(t)})).envVar},async updateEnvVar(e,t,r){return (await n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})).envVar},async deleteEnvVar(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"DELETE"})},async getEnvVarValue(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}/value`)}}}function ae(s){let n=p(s);return {async generatePlan(e){return n("/ai/plan",{method:"POST",body:JSON.stringify({projectId:e.projectId,prompt:e.prompt,context:e.context,taskType:e.taskType,mode:e.mode})})},async explainPlan(e){return n("/ai/explain",{method:"POST",body:JSON.stringify({plan:e.plan,projectId:e.projectId,taskType:e.taskType,mode:e.mode})})},async getOrgSettings(e){return n(`/ai/settings/org/${encodeURIComponent(e)}`)},async updateOrgSettings(e,t){return n(`/ai/settings/org/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getProjectOverrides(e){return n(`/ai/settings/project/${encodeURIComponent(e)}`)},async updateProjectOverrides(e,t){return n(`/ai/settings/project/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getUsage(e,t){let r=new URLSearchParams;t&&r.set("month",t);let o=r.toString(),a=`/ai/usage/org/${encodeURIComponent(e)}${o?`?${o}`:""}`;return n(a)},async getBudgetStatus(e){let[t,r]=await Promise.all([this.getOrgSettings(e),this.getUsage(e)]),o=t?.monthlyBudgetCents??1e4,a=r.costCents,l=Math.max(0,o-a),i=o>0?Math.round(a/o*100):0;return {spent:a,budget:o,remaining:l,hardStop:t?.hardStopEnabled??false,percentUsed:i}},async generateFunction(e){return n("/ai/generate-function",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,language:e.language??"typescript",mode:e.mode})})},async generateEndpoint(e){return n("/ai/generate-endpoint",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,method:e.method??"GET",authRequired:e.authRequired??true,mode:e.mode})})},async exportCode(e){return n("/ai/export-code",{method:"POST",body:JSON.stringify({projectId:e.projectId,targetLanguage:e.targetLanguage,includeSchema:e.includeSchema??true,includeFunctions:e.includeFunctions??true,includeEndpoints:e.includeEndpoints??true})})},async createConversation(e,t){return n("/ai/conversations",{method:"POST",body:JSON.stringify({projectId:e,title:t?.title,context:t?.context})})},async sendMessage(e,t){return n(`/ai/conversations/${encodeURIComponent(e)}/messages`,{method:"POST",body:JSON.stringify({content:t.content,taskType:t.taskType})})},async getConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`)},async listConversations(e){return (await n(`/ai/conversations/project/${encodeURIComponent(e)}`)).conversations},async deleteConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`,{method:"DELETE"})},async getAvailableModels(){return n("/ai/models/available")},async getModel(e){return n(`/ai/models/${encodeURIComponent(e)}`)},async getProjectContext(e){return n(`/ai/context/${encodeURIComponent(e)}`)},async estimateTokens(e,t){return n("/ai/context/estimate",{method:"POST",body:JSON.stringify({prompt:e,projectId:t})})},async analyzeForClarification(e){return n("/ai/clarify",{method:"POST",body:JSON.stringify(e)})},async getSuggestions(e){return n("/ai/suggestions",{method:"POST",body:JSON.stringify(e)})},workspace:{async create(e){return n("/ai/workspace/create",{method:"POST",body:JSON.stringify(e)})},async get(e){return n(`/ai/workspace/${encodeURIComponent(e)}`)},async list(e){return n(`/ai/workspace/list/${encodeURIComponent(e)}`)},async submitPrompt(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/prompt`,{method:"POST",body:JSON.stringify(t),timeout:12e4})},async submitClarification(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/clarify`,{method:"POST",body:JSON.stringify({responses:t}),timeout:9e4})},async generate(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/generate`,{method:"POST",body:JSON.stringify(t),timeout:18e4})},async submitModification(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/modify`,{method:"POST",body:JSON.stringify(t),timeout:18e4})},async submitFeedback(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/feedback`,{method:"POST",body:JSON.stringify(t)})}},backends:{async get(e){return n(`/ai/backends/${encodeURIComponent(e)}`)},async list(e){return n(`/ai/backends/list/${encodeURIComponent(e)}`)},async delete(e){return n(`/ai/backends/${encodeURIComponent(e)}`,{method:"DELETE"})},async deploy(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/deploy`,{method:"POST",body:JSON.stringify(t)})},async apply(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify(t)})},async deployLive(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/deploy-live`,{method:"POST",body:JSON.stringify(t),timeout:3e5})},async getDeployments(e){return n(`/ai/backends/${encodeURIComponent(e)}/deployments`)}},deployments:{async getLimits(e){return n(`/ai/deployments/limits/${encodeURIComponent(e)}`)},async getStatus(e){return n(`/ai/deployments/${encodeURIComponent(e)}/status`)},async getLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.severity&&r.set("severity",t.severity);let o=r.toString();return n(`/ai/deployments/${encodeURIComponent(e)}/logs${o?`?${o}`:""}`)},async terminate(e){return n(`/ai/deployments/${encodeURIComponent(e)}`,{method:"DELETE"})},async redeploy(e){return n(`/ai/deployments/${encodeURIComponent(e)}/redeploy`,{method:"POST",timeout:3e5})}},async getUserOrganizations(){return n("/ai/user/organizations")},async getProjectLimits(e){return n(`/ai/org/${encodeURIComponent(e)}/project-limits`)},async createProjectWithSchema(e){return n("/ai/schema/create-project",{method:"POST",body:JSON.stringify(e)})}}}function le(s){let n=p(s);return {async load(){return n("/bootstrap")}}}function ce(s){let n=p(s);return {async list(e){let t=new URLSearchParams;e?.visibility&&t.set("visibility",e.visibility),e?.category&&t.set("category",e.category),e?.orgId&&t.set("orgId",e.orgId);let r=t.toString(),o=`/templates${r?`?${r}`:""}`;return (await n(o)).templates},async get(e){return n(`/templates/${e}`)},async create(e){return n("/templates",{method:"POST",body:JSON.stringify(e)})},async previewInstall(e){return n("/templates/install/preview",{method:"POST",body:JSON.stringify(e)})},async applyInstall(e){return n("/templates/install/apply",{method:"POST",body:JSON.stringify(e)})},async rollback(e){return n(`/templates/install/${e}/rollback`,{method:"POST"})},async createProject(e){return n("/templates/create-project",{method:"POST",body:JSON.stringify(e)})}}}function de(s){let n=p(s);return {async list(e){return (await n(`/oauth/org/${e}`)).connections},async configure(e,t){return n(`/oauth/org/${e}/configure`,{method:"POST",body:JSON.stringify(t)})},async update(e,t,r){return n(`/oauth/org/${e}/provider/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(e,t){return n(`/oauth/org/${e}/provider/${t}`,{method:"DELETE"})}}}function ue(s){let n=p(s);return {async listPages(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/pages${t}`)).pages},async getPage(e){return (await n(`/docs/pages/${encodeURIComponent(e)}`)).page},async createPage(e){return (await n("/docs/pages",{method:"POST",body:JSON.stringify(e)})).page},async updatePage(e,t){return (await n(`/docs/pages/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).page},async deletePage(e){return n(`/docs/pages/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdks(){return (await n("/docs/sdks")).sdks},async getSdk(e){return (await n(`/docs/sdks/${encodeURIComponent(e)}`)).sdk},async createSdk(e){return (await n("/docs/sdks",{method:"POST",body:JSON.stringify(e)})).sdk},async updateSdk(e,t){return (await n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).sdk},async deleteSdk(e){return n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdkExamples(e,t){let r=t?`?topic=${encodeURIComponent(t)}`:"";return (await n(`/docs/sdks/${encodeURIComponent(e)}/examples${r}`)).examples},async createSdkExample(e){return (await n("/docs/sdk-examples",{method:"POST",body:JSON.stringify(e)})).example},async deleteSdkExample(e){return n(`/docs/sdk-examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listEndpoints(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/api-endpoints${t}`)).endpoints},async getEndpoint(e){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`)).endpoint},async createEndpoint(e){return (await n("/docs/api-endpoints",{method:"POST",body:JSON.stringify(e)})).endpoint},async updateEndpoint(e,t){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).endpoint},async deleteEndpoint(e){return n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},async listExamples(e){let t=e!==void 0?`?featured=${e}`:"";return (await n(`/docs/examples${t}`)).examples},async getExample(e){return (await n(`/docs/examples/${encodeURIComponent(e)}`)).example},async createExample(e){return (await n("/docs/examples",{method:"POST",body:JSON.stringify(e)})).example},async updateExample(e,t){return (await n(`/docs/examples/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).example},async deleteExample(e){return n(`/docs/examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listChangelog(){return (await n("/docs/changelog")).entries},async getChangelogEntry(e){return (await n(`/docs/changelog/${encodeURIComponent(e)}`)).entry},async createChangelogEntry(e){return (await n("/docs/changelog",{method:"POST",body:JSON.stringify(e)})).entry},async updateChangelogEntry(e,t){return (await n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).entry},async deleteChangelogEntry(e){return n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"DELETE"})},async search(e){return (await n(`/docs/search?q=${encodeURIComponent(e)}`)).results}}}function J(s,n,e,t){let r=[...n],o=0,a=false,l=false,i=async()=>{if(l||a)return;let c=await e(`/mongodb/${t}/cursor/${s}/next`,{method:"POST"});r=c.batch,o=0,a=c.exhausted;};return {id:s,async hasNext(){return l?false:o<r.length?true:a?false:(await i(),r.length>0)},async next(){return l?null:o<r.length?r[o++]:a||(await i(),r.length===0)?null:r[o++]},async toArray(){if(l)return [];let c=[];for(;o<r.length;)c.push(r[o++]);for(;!a;)await i(),c.push(...r),o=r.length;return c},async forEach(c){if(!l){for(;o<r.length;)await c(r[o++]);for(;!a;){await i();for(let g of r)await c(g);o=r.length;}}},map(c){let g=r.slice(o).map(c);return J(s,g,e,t)},async close(){if(!l){l=true;try{await e(`/mongodb/${t}/cursor/${s}/close`,{method:"POST"});}catch{}}},isClosed(){return l}}}function Oe(s,n){let e=`/mongodb/${encodeURIComponent(s)}`;return {collectionName:s,async find(t,r){return n(`${e}/find`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async findCursor(t,r){let o=await n(`${e}/find/cursor`,{method:"POST",body:JSON.stringify({filter:t,options:r})});return J(o.cursorId,o.batch,n,s)},async findOne(t,r){return n(`${e}/findOne`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async findById(t,r){return n(`${e}/findById/${encodeURIComponent(t)}`,{method:"GET",...r&&{body:JSON.stringify({options:r})}})},async countDocuments(t){return (await n(`${e}/count`,{method:"POST",body:JSON.stringify({filter:t})})).count},async estimatedDocumentCount(){return (await n(`${e}/estimatedCount`)).count},async distinct(t,r){return n(`${e}/distinct`,{method:"POST",body:JSON.stringify({field:t,...r})})},async insertOne(t){return n(`${e}/insertOne`,{method:"POST",body:JSON.stringify({document:t})})},async insertMany(t,r){return n(`${e}/insertMany`,{method:"POST",body:JSON.stringify({documents:t,options:r})})},async updateOne(t,r,o){return n(`${e}/updateOne`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async updateMany(t,r,o){return n(`${e}/updateMany`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async replaceOne(t,r,o){return n(`${e}/replaceOne`,{method:"POST",body:JSON.stringify({filter:t,replacement:r,options:o})})},async findOneAndUpdate(t,r,o){return n(`${e}/findOneAndUpdate`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async findOneAndReplace(t,r,o){return n(`${e}/findOneAndReplace`,{method:"POST",body:JSON.stringify({filter:t,replacement:r,options:o})})},async deleteOne(t){return n(`${e}/deleteOne`,{method:"POST",body:JSON.stringify({filter:t})})},async deleteMany(t){return n(`${e}/deleteMany`,{method:"POST",body:JSON.stringify({filter:t})})},async findOneAndDelete(t,r){return n(`${e}/findOneAndDelete`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async aggregate(t,r){return n(`${e}/aggregate`,{method:"POST",body:JSON.stringify({pipeline:t,options:r})})},async aggregateCursor(t,r){let o=await n(`${e}/aggregate/cursor`,{method:"POST",body:JSON.stringify({pipeline:t,options:r})});return J(o.cursorId,o.batch,n,s)},async createIndex(t,r){return (await n(`${e}/indexes`,{method:"POST",body:JSON.stringify({keys:t,options:r})})).indexName},async dropIndex(t){await n(`${e}/indexes/${encodeURIComponent(t)}`,{method:"DELETE"});},async listIndexes(){return n(`${e}/indexes`)},async bulkWrite(t,r){return n(`${e}/bulkWrite`,{method:"POST",body:JSON.stringify({operations:t,options:r})})}}}function ge(s){let n=p(s);return {collection(e){return Oe(e,n)},async listCollections(){return n("/mongodb/collections")},async createCollection(e,t){await n("/mongodb/collections",{method:"POST",body:JSON.stringify({name:e,options:t})});},async dropCollection(e){await n(`/mongodb/collections/${encodeURIComponent(e)}`,{method:"DELETE"});},async renameCollection(e,t){await n(`/mongodb/collections/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({newName:t})});},async command(e){return n("/mongodb/command",{method:"POST",body:JSON.stringify(e)})}}}function pe(s){let n=p(s);return {async chat(e){return n("/ai/copilot/chat",{method:"POST",body:JSON.stringify(e),timeout:12e4})},getStreamUrl(){return `${s.baseUrl}/ai/copilot/chat/stream`},async getModels(e){return n(`/ai/copilot/models/${encodeURIComponent(e)}`)},async getCreditStatus(e){return n(`/ai/copilot/credit-status/${encodeURIComponent(e)}`)},async listSessions(e){return n(`/ai/copilot/sessions/${encodeURIComponent(e)}`)},async getSession(e){return n(`/ai/copilot/session/${encodeURIComponent(e)}`)},async updateSession(e,t){return n(`/ai/copilot/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteSession(e){return n(`/ai/copilot/session/${encodeURIComponent(e)}`,{method:"DELETE"})},async executePlan(e){return n("/ai/copilot/execute",{method:"POST",body:JSON.stringify(e),timeout:18e4})},async submitFeedback(e){return n("/ai/copilot/feedback",{method:"POST",body:JSON.stringify(e)})},async getClassificationStats(){return n("/ai/copilot/stats")},async getUsage(e){return n(`/ai/copilot/usage-org/${encodeURIComponent(e)}`)}}}function xe(s,n,e,t){let r=n.type||"public",o="unsubscribed",a=new Map,l=[],i={},c=null,g=null,y=new Set,h=new Set,S=new Set,P=d=>{if(d.event){let b=a.get(d.event);b&&b.forEach(R=>R(d.payload));}},A=d=>{i=d.state||{},y.forEach(b=>b(i));},f=d=>{let b=d.key||"",R=d.currentPresences||[],u=d.joinedPresences||[],m=d.leftPresences||[];u.length>0&&(i[b]=R,h.forEach(I=>I(b,R,u))),m.length>0&&(R.length===0?delete i[b]:i[b]=R,S.forEach(I=>I(b,R,m))),y.forEach(I=>I(i));},T=d=>{let b={type:"db_change",projectId:d.projectId||"",schema:d.schema||"",table:d.table||"",operation:d.op,new:d.record,old:d.old_record,timestamp:d.ts||new Date().toISOString(),partial:d.partial};l.forEach(({options:R,handler:u})=>{if(R.table===b.table){let m=R.event||"*";(m==="*"||(Array.isArray(m)?m.includes(b.operation):m===b.operation))&&u(b);}});},C={get name(){return s},get type(){return r},get status(){return o},_handleMessage:d=>{switch(d.type){case "broadcast":P(d);break;case "presence_state":A(d);break;case "presence":f(d);break;case "db_change":T(d);break;case "subscribed":o="subscribed";break;case "error":o="error";break}},onDbChange(d,b){return l.push({options:d,handler:b}),o==="subscribed"&&e({type:"subscribe",channel:s,options:{table:d.table,filter:d.filter,event:d.event,columns:d.columns}}),C},on(d,b){return a.has(d)||a.set(d,new Set),a.get(d).add(b),C},off(d,b){return b?a.get(d)?.delete(b):a.delete(d),C},async broadcast(d){if(o!=="subscribed")throw new k("Channel must be subscribed before broadcasting",{code:"CHANNEL_NOT_SUBSCRIBED"});e({type:"broadcast",channel:s,event:d.event,payload:d.payload,includeSelf:d.includeSelf});},presence:{async track(d){if(r!=="presence")throw new k("Presence tracking is only available on presence channels",{code:"INVALID_CHANNEL_TYPE"});c=d.key||t()||"anonymous",g=d.state,e({type:"presence_track",channel:s,key:c,state:g});},async update(d){if(!g)throw new k("Must call track() before update()",{code:"PRESENCE_NOT_TRACKED"});g={...g,...d},e({type:"presence_update",channel:s,key:c??void 0,state:g});},async untrack(){c&&(e({type:"presence_untrack",channel:s,key:c}),c=null,g=null);},state(){return {...i}},onSync(d){return y.add(d),C},onJoin(d){return h.add(d),C},onLeave(d){return S.add(d),C}},async subscribe(){return o==="subscribed"||(o="subscribing",e({type:"subscribe",channel:s}),l.forEach(({options:d})=>{e({type:"subscribe",channel:s,options:{table:d.table,filter:d.filter,event:d.event,columns:d.columns}});}),n.presenceState&&r==="presence"&&await C.presence.track({state:n.presenceState})),C},async unsubscribe(){o!=="unsubscribed"&&(c&&await C.presence.untrack(),e({type:"unsubscribe",channel:s}),o="unsubscribed",i={},a.clear(),l.length=0);}};return C}function me(s,n){let{wsUrl:e=s.baseUrl.replace(/^http/,"ws")+"/realtime/ws",autoReconnect:t=true,reconnectDelay:r=1e3,maxReconnectAttempts:o=10}=n??{},a=null,l="disconnected",i=null,c=null,g=0,y=null,h=null,S=new Map,P=new Map,A=new Set,f={connect:new Set,disconnect:new Set,error:new Set,reconnect:new Set},T=u=>{f[u].forEach(m=>m());},O=u=>{let m=`table:${u.table}`;if(u.filter){let M=(Array.isArray(u.filter)?u.filter:[u.filter]).map(w=>`${w.field}${w.operator||"eq"}${w.value}`).join("&");m+=`?${M}`;}return m},C=u=>{a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(u));},d=u=>{if(u.channel){let m=S.get(u.channel);if(m){m._handleMessage(u);return}}switch(u.type){case "db_change":{let m={type:"db_change",projectId:u.projectId??"",schema:u.schema??"",table:u.table??"",operation:u.op,new:u.record,old:u.old_record,timestamp:u.ts??new Date().toISOString(),partial:u.partial},I=`table:${u.table}`;P.forEach((M,w)=>{(w===I||w.startsWith(I+"?"))&&M.forEach(N=>N(m));});break}case "presence":{let m={type:"presence",event:u.event,key:u.key||u.connectionId||"",connectionId:u.connectionId??"",projectId:u.projectId??"",currentPresences:u.currentPresences||[],leftPresences:u.leftPresences||[],joinedPresences:u.joinedPresences||[]};A.forEach(I=>I(m));break}case "welcome":i=u.connectionId||null;break;case "error":{T("error");break}}},b=()=>new Promise((u,m)=>{try{a=new WebSocket(e);}catch{m(new x("Failed to create WebSocket connection"));return}let I=()=>{l="connected",g=0;let D={type:"auth"};s.apiKey&&(D[s.apiKeyHeader]=s.apiKey),c&&(D.token=c),C(D),T("connect"),S.forEach(B=>{(B.status==="subscribed"||B.status==="subscribing")&&B.subscribe();}),P.forEach((B,ye)=>{C({type:"subscribe",channel:ye});}),h=setInterval(()=>{C({type:"ping"});},3e4),u();},M=D=>{try{let B=JSON.parse(D.data);d(B);}catch{}},w=()=>{if(l="disconnected",i=null,a=null,h&&(clearInterval(h),h=null),T("disconnect"),t&&g<o){l="reconnecting";let D=r*Math.pow(2,g);y=setTimeout(()=>{g++,T("reconnect"),b().catch(()=>{});},Math.min(D,3e4));}},N=()=>{T("error"),m(new x("WebSocket connection error"));};a.addEventListener("open",I),a.addEventListener("message",M),a.addEventListener("close",w),a.addEventListener("error",N);}),R=()=>{y&&(clearTimeout(y),y=null),h&&(clearInterval(h),h=null),g=o;};return {channel(u,m={}){let I=S.get(u);if(I)return I;let M=xe(u,m,C,()=>i);return S.set(u,M),M},async removeChannel(u){let m=S.get(u.name);m&&(await m.unsubscribe(),S.delete(u.name));},getChannels(){return Array.from(S.values())},subscribe(u,m){let I=O(u);return P.has(I)||P.set(I,new Set),P.get(I).add(m),a?.readyState===WebSocket.OPEN&&C({type:"subscribe",channel:I}),()=>{let M=P.get(I);M&&(M.delete(m),M.size===0&&(P.delete(I),a?.readyState===WebSocket.OPEN&&C({type:"unsubscribe",channel:I})));}},subscribeToPresence(u){return A.add(u),()=>{A.delete(u);}},async connect(){if(l!=="connected"){if(!s.apiKey)throw new E("API key is required for realtime connections");l="connecting",await b();}},disconnect(){R(),S.forEach(u=>{u.unsubscribe();}),S.clear(),a&&(a.close(),a=null),l="disconnected",i=null;},get isConnected(){return l==="connected"},get connectionState(){return l},get connectionId(){return i},on(u,m){f[u].add(m);},off(u,m){f[u].delete(m);},setAuth(u){c=u;}}}var F={apiKeyHeader:"x-vaif-key",timeout:3e4,retry:{maxRetries:3,retryDelay:1e3,maxRetryDelay:3e4,backoffMultiplier:2,retryOn:[429,500,502,503,504],retryOnNetworkError:true}};function Me(s){return {baseUrl:s.baseUrl.replace(/\/$/,""),apiKey:s.apiKey,apiKeyHeader:s.apiKeyHeader??F.apiKeyHeader,accessToken:s.accessToken,fetch:s.fetch??globalThis.fetch.bind(globalThis),timeout:s.timeout??F.timeout,retry:{maxRetries:s.retry?.maxRetries??F.retry.maxRetries,retryDelay:s.retry?.retryDelay??F.retry.retryDelay,maxRetryDelay:s.retry?.maxRetryDelay??F.retry.maxRetryDelay,backoffMultiplier:s.retry?.backoffMultiplier??F.retry.backoffMultiplier,retryOn:s.retry?.retryOn??[...F.retry.retryOn],retryOnNetworkError:s.retry?.retryOnNetworkError??F.retry.retryOnNetworkError},interceptors:s.interceptors??{}}}function Ee(s){let n=Me(s),e=W(n),t=_(n),r=H(n),o=G(n),a=z(n),l=Q(n),i=X(n),c=Y(n),g=Z(n),y=ee(n),h=te(n),S=ne(n),P=re(n),A=oe(n),f=se(n),T=ie(n),O=ae(n),C=le(n),d=ce(n),b=de(n),R=ue(n),u=ge(n),m=pe(n);return {from:e.from,auth:t,functions:r,storage:o,projects:a,orgs:l,schema:i,secrets:c,deployments:g,realtimeMonitoring:y,storageDashboard:h,integrations:S,billing:P,admin:A,flags:f,security:T,ai:O,bootstrap:C,templates:d,oauth:b,docs:R,mongodb:u,copilot:m,realtime:I=>me(n,I)}}Object.defineProperty(exports,"AuthError",{enumerable:true,get:function(){return auth.AuthError}});Object.defineProperty(exports,"InvalidCredentialsError",{enumerable:true,get:function(){return auth.InvalidCredentialsError}});Object.defineProperty(exports,"SessionExpiredError",{enumerable:true,get:function(){return auth.SessionExpiredError}});Object.defineProperty(exports,"SessionStorage",{enumerable:true,get:function(){return auth.SessionStorage}});Object.defineProperty(exports,"VaifAuthClient",{enumerable:true,get:function(){return auth.VaifAuthClient}});Object.defineProperty(exports,"authLocalStorage",{enumerable:true,get:function(){return auth.localStorage}});Object.defineProperty(exports,"authSessionStorage",{enumerable:true,get:function(){return auth.sessionStorage}});Object.defineProperty(exports,"cookieStorage",{enumerable:true,get:function(){return auth.cookieStorage}});Object.defineProperty(exports,"createAuthClient",{enumerable:true,get:function(){return auth.createAuthClient}});Object.defineProperty(exports,"getDefaultStorage",{enumerable:true,get:function(){return auth.getDefaultStorage}});Object.defineProperty(exports,"isBrowser",{enumerable:true,get:function(){return auth.isBrowser}});Object.defineProperty(exports,"isMFAChallenge",{enumerable:true,get:function(){return auth.isMFAChallenge}});Object.defineProperty(exports,"memoryStorage",{enumerable:true,get:function(){return auth.memoryStorage}});exports.VaifAuthError=E;exports.VaifConflictError=L;exports.VaifError=k;exports.VaifNetworkError=x;exports.VaifNotFoundError=$;exports.VaifRateLimitError=U;exports.VaifTimeoutError=V;exports.VaifValidationError=j;exports.createVaifClient=Ee;exports.isVaifAuthError=Pe;exports.isVaifError=be;exports.isVaifNetworkError=he;exports.isVaifNotFoundError=fe;exports.isVaifRateLimitError=ke;exports.isVaifValidationError=Ie;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export{AuthError,InvalidCredentialsError,SessionExpiredError,SessionStorage,VaifAuthClient,localStorage as authLocalStorage,sessionStorage as authSessionStorage,cookieStorage,createAuthClient,getDefaultStorage,isBrowser,isMFAChallenge,memoryStorage}from'@vaiftech/auth';var h=class s extends Error{constructor(n,e){super(n),this.name="VaifError",this.code=e.code,this.statusCode=e.statusCode,this.requestId=e.requestId,this.details=e.details;let t=Error;t.captureStackTrace&&t.captureStackTrace(this,s);}toJSON(){return {name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,details:this.details}}},E=class extends h{constructor(n,e){super(n,{code:e?.code??"AUTH_ERROR",statusCode:e?.statusCode??401,requestId:e?.requestId}),this.name="VaifAuthError";}},j=class extends h{constructor(n,e){super(n,{code:"VALIDATION_ERROR",statusCode:400,requestId:e?.requestId,details:e?.details??e?.fieldErrors}),this.name="VaifValidationError",this.fieldErrors=e?.fieldErrors;}},x=class extends h{constructor(n,e){super(n,{code:"NETWORK_ERROR"}),this.name="VaifNetworkError",this.cause=e;}},U=class extends h{constructor(n,e){super(n,{code:"RATE_LIMITED",statusCode:429}),this.name="VaifRateLimitError",this.retryAfter=e;}},$=class extends h{constructor(n,e){super(n,{code:"NOT_FOUND",statusCode:404,requestId:e}),this.name="VaifNotFoundError";}},L=class extends h{constructor(n,e){super(n,{code:"CONFLICT",statusCode:409,requestId:e}),this.name="VaifConflictError";}},V=class extends x{constructor(n,e){super(n),this.name="VaifTimeoutError",this.timeoutMs=e;}};function be(s){return s instanceof h}function fe(s){return s instanceof $}function Pe(s){return s instanceof E}function Ie(s){return s instanceof j}function he(s){return s instanceof U}function ke(s){return s instanceof x}async function Se(s){let n;try{n=await s.json();}catch{}let e=n?.message??n?.error??s.statusText??"Request failed",t=n?.requestId;switch(s.status){case 400:return new j(e,{details:n?.details,requestId:t});case 401:return new E(e,{code:"UNAUTHORIZED",statusCode:401,requestId:t});case 403:return new E(e,{code:"FORBIDDEN",statusCode:403,requestId:t});case 404:return new $(e,t);case 409:return new h(e,{code:"CONFLICT",statusCode:409,requestId:t,details:n?.details});case 422:return new j(e,{details:n?.details,requestId:t});case 429:{let r=s.headers.get("Retry-After"),o=r?parseInt(r,10):void 0;return new U(e,o)}default:return new h(e,{code:n?.error??"HTTP_ERROR",statusCode:s.status,requestId:t,details:n?.details})}}function Ce(s,n,e){return s instanceof x?e:s instanceof U?n.includes(429):s instanceof h&&s.statusCode?n.includes(s.statusCode):false}function ve(s,n,e,t,r){if(r!==void 0&&r>0)return Math.min(r*1e3,e);let o=n*Math.pow(t,s),a=Math.min(o,e),l=a*Math.random()*.25;return a+l}function Ae(s){return new Promise(n=>setTimeout(n,s))}async function Re(s,n){let{timeout:e=3e4,fetchFn:t,...r}=n,o=new AbortController,a=setTimeout(()=>o.abort(),e);try{let l=await t(s,{...r,signal:o.signal});if(clearTimeout(a),!l.ok)throw await Se(l);if(l.status===204)return;let i=await l.text();return i?JSON.parse(i):void 0}catch(l){throw clearTimeout(a),l instanceof h?l:l instanceof Error&&l.name==="AbortError"?new x("Request timed out"):l instanceof Error?new x(l.message,l):new x("Network request failed")}}function p(s){let{baseUrl:n,apiKey:e,apiKeyHeader:t,accessToken:r,fetch:o,timeout:a,retry:l,interceptors:i}=s;return async function(g,y={}){let k=`${n}${g}`,S=y.method||"GET",P={"Content-Type":"application/json",...y.headers??{}};if(e&&(P[t]=e),r){let O=typeof r=="function"?await r():r;P.Authorization=`Bearer ${O}`;}let A=y.timeout??a,f=l.maxRetries,R=null;for(let O=0;O<=f;O++){let C=Date.now(),d={url:k,path:g,method:S,headers:{...P},body:y.body,attempt:O};try{if(i.onRequest){let u=await i.onRequest(d);u&&(d=u);}let b=await Re(d.url,{...y,method:d.method,headers:d.headers,body:d.body,timeout:A,fetchFn:o}),T=Date.now()-C;if(i.onResponse){let u={request:d,data:b,status:200,headers:{},durationMs:T};await i.onResponse(u);}return b}catch(b){let T=Date.now()-C;R=b;let u=O<f&&Ce(b,l.retryOn,l.retryOnNetworkError);if(i.onError){let m={request:d,error:b,durationMs:T,willRetry:u};await i.onError(m);}if(u){let m=b instanceof U?b.retryAfter:void 0,I=ve(O,l.retryDelay,l.maxRetryDelay,l.backoffMultiplier,m);await Ae(I);continue}throw b}}throw R||new x("Request failed after retries")}}function v(s){let n=new URLSearchParams;for(let[t,r]of Object.entries(s))r!==void 0&&n.set(t,String(r));let e=n.toString();return e?`?${e}`:""}function Te(s){return JSON.stringify(s)}function q(s,n,e={}){let t={...e},r=()=>{let i={};if(t.limit!==void 0&&(i.limit=t.limit),t.offset!==void 0&&(i.offset=t.offset),t.where&&(i.where=Te(t.where)),t.orderBy){let c=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];i.orderBy=JSON.stringify(c);}return t.select&&t.select.length>0&&(i.select=t.select.join(",")),t.include&&t.include.length>0&&(i.include=JSON.stringify(t.include)),t.distinct&&t.distinct.length>0&&(i.distinct=t.distinct.join(",")),i},o=()=>v(r()),a=i=>q(s,n,{...t,...i}),l={async list(i){i&&(t={...t,...i});let c=o();return n(`/generated/${s}${c}`)},async get(i){let c={};t.select&&t.select.length>0&&(c.select=t.select.join(",")),t.include&&t.include.length>0&&(c.include=JSON.stringify(t.include));let g=v(c);return n(`/generated/${s}/${encodeURIComponent(i)}${g}`)},async first(){let i=await l.limit(1).list();return i.data.length>0?i.data[0]:null},async firstOrFail(){let i=await l.first();if(!i)throw new $(`No record found in table '${s}' matching the query`);return i},async create(i){return n(`/generated/${s}`,{method:"POST",body:JSON.stringify(i)})},async update(i,c){return n(`/generated/${s}/${encodeURIComponent(i)}`,{method:"PATCH",body:JSON.stringify(c)})},async delete(i){return n(`/generated/${s}/${encodeURIComponent(i)}`,{method:"DELETE"})},async createMany(i,c){return n(`/generated/${s}/batch`,{method:"POST",body:JSON.stringify({records:i,skipOnConflict:c?.skipOnConflict,returnRecords:c?.returnRecords})})},async updateMany(i,c){return n(`/generated/${s}/batch`,{method:"PATCH",body:JSON.stringify({data:i,where:t.where,returnRecords:c?.returnRecords})})},async deleteMany(){return n(`/generated/${s}/batch`,{method:"DELETE",body:JSON.stringify({where:t.where})})},async upsert(i,c){return n(`/generated/${s}/upsert`,{method:"POST",body:JSON.stringify({data:i,conflictFields:c.conflictFields,updateFields:c.updateFields})})},async count(){let i=r(),c=v(i);return (await n(`/generated/${s}/count${c}`)).count},async sum(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/sum${g}`)).sum},async avg(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/avg${g}`)).avg},async min(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/min${g}`)).min},async max(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/max${g}`)).max},async aggregate(i,c){return n(`/generated/${s}/aggregate`,{method:"POST",body:JSON.stringify({aggregates:i,where:c?.where||t.where,groupBy:c?.groupBy,having:c?.having})})},async paginate(i){let c=i.page||1,g=i.pageSize||20,y=(c-1)*g,k=r();k.limit=g,k.offset=y,k.includeCount=true;let S=v(k),P=await n(`/generated/${s}${S}`),A=P.total||P.data.length,f=Math.ceil(A/g);return {data:P.data,pageInfo:{total:A,page:c,pageSize:g,pageCount:f,hasNextPage:c<f,hasPrevPage:c>1}}},async cursorPaginate(i){let c=r();c.limit=i.limit||20,i.cursor&&(c.cursor=i.cursor);let g=v(c),y=await n(`/generated/${s}/cursor${g}`);return {data:y.data,nextCursor:y.nextCursor,prevCursor:y.prevCursor,hasMore:y.hasMore}},where(i){if(t.where){let c=t.where;return a({where:{AND:[...Array.isArray(c)?c:[c],i]}})}return a({where:i})},orderBy(i,c="asc"){let g={field:i,direction:c};if(t.orderBy){let y=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];return a({orderBy:[...y,g]})}return a({orderBy:g})},select(...i){return a({select:i})},limit(i){return a({limit:i})},offset(i){return a({offset:i})},include(i){let c=t.include||[];return a({include:[...c,i]})},distinct(...i){return a({distinct:i})}};return l}function W(s){let n=p(s);return {from(e){return q(e,n)},async raw(e,t){return n("/generated/raw",{method:"POST",body:JSON.stringify({query:e,params:t})})},async transaction(e,t){return n("/generated/transaction",{method:"POST",body:JSON.stringify({operations:e,isolationLevel:t?.isolationLevel,timeout:t?.timeout})})},async withTransaction(e,t){let o=(await n("/generated/transaction/start",{method:"POST",body:JSON.stringify({isolationLevel:t?.isolationLevel,timeout:t?.timeout})})).transactionId,a=(i,c)=>{let g=new Headers(c?.headers);return g.set("X-Transaction-Id",o),n(i,{...c,headers:g})},l={from(i){return q(i,a)},async raw(i,c){return a("/generated/raw",{method:"POST",body:JSON.stringify({query:i,params:c})})},async transaction(){throw new h("Nested transactions are not supported",{code:"NESTED_TRANSACTION"})},async withTransaction(){throw new h("Nested transactions are not supported",{code:"NESTED_TRANSACTION"})}};try{let i=await e(l);return await n("/generated/transaction/commit",{method:"POST",body:JSON.stringify({transactionId:o})}),i}catch(i){throw await n("/generated/transaction/rollback",{method:"POST",body:JSON.stringify({transactionId:o})}).catch(()=>{}),i}}}}function _(s){let n=p(s);return {async signUp(e,t,r){return n("/auth/signup",{method:"POST",body:JSON.stringify({email:e,password:t,name:r?.name,phone:r?.phone,metadata:r?.metadata,redirectUrl:r?.redirectUrl})})},async login(e,t,r){return n("/auth/login",{method:"POST",body:JSON.stringify({email:e,password:t,mfaCode:r?.mfaCode,rememberMe:r?.rememberMe})})},async logout(){await n("/auth/logout",{method:"POST"});},async logoutAll(){await n("/auth/logout-all",{method:"POST"});},async getUser(){return (await n("/auth/me")).user},async updateProfile(e){return (await n("/users/me",{method:"PATCH",body:JSON.stringify(e)})).user},async changePassword(e){return n("/users/me/change-password",{method:"POST",body:JSON.stringify(e)})},async requestPasswordReset(e){return n("/auth/forgot-password",{method:"POST",body:JSON.stringify(e)})},async confirmPasswordReset(e){return n("/auth/reset-password",{method:"POST",body:JSON.stringify(e)})},async requestEmailVerification(e){return n("/auth/verify-email/send",{method:"POST",body:JSON.stringify(e||{})})},async confirmEmailVerification(e){return n("/auth/verify-email/confirm",{method:"POST",body:JSON.stringify(e)})},async getOAuthSignInUrl(e){return n("/auth/oauth/authorize",{method:"POST",body:JSON.stringify(e)})},async handleOAuthCallback(e){return n("/auth/oauth/callback",{method:"POST",body:JSON.stringify(e)})},async linkOAuthProvider(e){return n("/auth/oauth/link",{method:"POST",body:JSON.stringify(e)})},async unlinkOAuthProvider(e){return n(`/auth/oauth/unlink/${e}`,{method:"POST"})},async listLinkedProviders(){return n("/auth/oauth/providers")},async requestMagicLink(e){return n("/auth/magic-link/send",{method:"POST",body:JSON.stringify(e)})},async verifyMagicLink(e){return n("/auth/magic-link/verify",{method:"POST",body:JSON.stringify(e)})},async requestPhoneVerification(e){return n("/auth/phone/send",{method:"POST",body:JSON.stringify(e)})},async confirmPhoneVerification(e){return n("/auth/phone/verify",{method:"POST",body:JSON.stringify(e)})},async setupMFA(e){return n("/auth/mfa/setup",{method:"POST",body:JSON.stringify({method:e})})},async enableMFA(e){return n("/auth/mfa/enable",{method:"POST",body:JSON.stringify({code:e})})},async disableMFA(e){return n("/auth/mfa/disable",{method:"POST",body:JSON.stringify({code:e})})},async verifyMFA(e,t){return n("/auth/mfa/verify",{method:"POST",body:JSON.stringify({mfaToken:e,code:t})})},async regenerateBackupCodes(){return n("/auth/mfa/backup-codes",{method:"POST"})},async refreshToken(e){return n("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})})},async listSessions(){return n("/auth/sessions")},async revokeSession(e){return n(`/auth/sessions/${e}`,{method:"DELETE"})},async revokeOtherSessions(){return n("/auth/sessions/revoke-others",{method:"POST"})}}}function K(s){return new Promise(n=>setTimeout(n,s))}function H(s){let n=p(s);async function e(t,r,o){let a=o?.retry||{},l=a.maxRetries??0,i=a.initialDelay??1e3,c=a.maxDelay??3e4,g=a.backoffMultiplier??2,y=a.retryOnStatus??[429,500,502,503,504],k=a.retryOnNetworkError??true,S=null,P=i;for(let A=0;A<=l;A++)try{let f={};o?.version!==void 0&&(f.version=o.version),o?.includeLogs&&(f.includeLogs=!0);let R=v(f),O=await n(`/functions/${t}/invoke${R}`,{method:"POST",body:JSON.stringify(r??{}),headers:o?.headers});if(y.includes(O.status)&&A<l){S=new Error(`Function returned status ${O.status}`),await K(P),P=Math.min(P*g,c);continue}return O}catch(f){S=f;let R=f instanceof TypeError||f.message?.includes("network")||f.message?.includes("fetch");if(k&&R&&A<l){await K(P),P=Math.min(P*g,c);continue}throw f}throw S||new Error("Function invocation failed after retries")}return {invoke:e,async invokeByName(t,r,o){let a={};o?.version!==void 0&&(a.version=o.version),o?.includeLogs&&(a.includeLogs=true);let l=v(a);return n(`/functions/name/${encodeURIComponent(t)}/invoke${l}`,{method:"POST",body:JSON.stringify(r??{}),headers:o?.headers})},async batchInvoke(t,r){let a=(await Promise.allSettled(t.map(l=>this.invoke(l.functionId,l.input,r)))).map((l,i)=>l.status==="fulfilled"?{functionId:t[i].functionId,success:true,result:l.value}:{functionId:t[i].functionId,success:false,error:l.reason?.message||"Unknown error"});return {results:a,successCount:a.filter(l=>l.success).length,errorCount:a.filter(l=>!l.success).length}},rpc(t,r){let o=this,a=async(l,i)=>{let c={...r,...i};return (await e(t,{body:l},c)).data};return Object.defineProperty(a,"id",{value:t,writable:false}),a.getInfo=()=>o.get(t),a.getInvocations=l=>o.getInvocations({...l,functionId:t}),a},async list(t){let r={envId:t.envId,enabled:t.enabled,limit:t.limit,offset:t.offset},o=v(r);return n(`/functions/project/${t.projectId}${o}`)},async get(t){return n(`/functions/${t}`)},async getByName(t,r){return n(`/functions/project/${r}/name/${encodeURIComponent(t)}`)},async create(t){return n("/functions",{method:"POST",body:JSON.stringify(t)})},async update(t,r){return n(`/functions/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(t){return n(`/functions/${t}`,{method:"DELETE"})},async enable(t){return this.update(t,{enabled:true})},async disable(t){return this.update(t,{enabled:false})},async deploy(t,r,o){return n(`/functions/${t}/source`,{method:"PUT",body:JSON.stringify({sourceCode:r})})},async getSource(t,r){return {sourceCode:(await n(`/functions/${t}`)).sourceCode||"",version:1}},async listVersions(t){return (await n(`/functions/${t}/versions`)).versions},async rollback(t,r){return n(`/functions/${t}/rollback`,{method:"POST",body:JSON.stringify({version:r})})},async getEnvVars(t){return (await n(`/functions/${t}/env`)).envVars},async setEnvVars(t,r){return n(`/functions/${t}/env`,{method:"PUT",body:JSON.stringify({envVars:r})})},async deleteEnvVar(t,r){return n(`/functions/${t}/env/${encodeURIComponent(r)}`,{method:"DELETE"})},async bindSecrets(t,r){return n(`/functions/${t}/secrets`,{method:"PUT",body:JSON.stringify({secrets:r})})},async setSchedule(t,r){return n(`/functions/${t}/schedule`,{method:"PUT",body:JSON.stringify(r)})},async removeSchedule(t){return n(`/functions/${t}/schedule`,{method:"DELETE"})},async getInvocations(t){let r={functionId:t.functionId,projectId:t.projectId,status:t.status,since:t.since,until:t.until,limit:t.limit,offset:t.offset},o=v(r);return (await n(`/functions/invocations${o}`)).invocations},async getInvocation(t){return n(`/functions/invocations/${t}`)},async getLogs(t,r){let o={since:r?.since,until:r?.until,level:r?.level,limit:r?.limit},a=v(o);return (await n(`/functions/${t}/logs${a}`)).logs}}}function G(s){let n=p(s),e="default";return {async getUploadUrl(t,r){return n("/storage/upload-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,sizeBytes:r?.sizeBytes,metadata:r?.metadata,isPublic:r?.isPublic,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,upsert:r?.upsert})})},async getDownloadUrl(t,r){return n("/storage/download-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,expiresIn:r?.expiresIn,download:r?.download,transform:r?.transform})})},async createSignedUrl(t,r=3600,o){return (await this.getDownloadUrl(t,{...o,expiresIn:r})).url},async createSignedUrls(t,r=3600,o){return await Promise.all(t.map(async l=>({key:l,url:await this.createSignedUrl(l,r,o)})))},async upload(t,r,o){let a=r instanceof Blob?r:new Blob([r]),l=a.size,i=o?.contentType||(r instanceof File?r.type:void 0)||"application/octet-stream",c=await this.getUploadUrl(t,{...o,contentType:i,sizeBytes:l}),g=await s.fetch(c.url,{method:"PUT",body:a,headers:{"Content-Type":i,...o?.cacheControl&&{"Cache-Control":o.cacheControl},...o?.contentDisposition&&{"Content-Disposition":o.contentDisposition}}});if(!g.ok)throw new h(`Upload failed: ${g.statusText}`,{code:"UPLOAD_ERROR",statusCode:g.status});let y=o?.bucket||e,k=c.url.split("?")[0];return {ok:true,key:t,bucket:y,url:k,publicUrl:o?.isPublic?this.getPublicUrl(t,{bucket:y}):void 0,size:l,contentType:i}},async uploadFromUrl(t,r,o){return n("/storage/upload-from-url",{method:"POST",body:JSON.stringify({key:t,url:r,bucket:o?.bucket||e,contentType:o?.contentType,metadata:o?.metadata,isPublic:o?.isPublic,timeout:o?.timeout})})},async download(t,r){let o=await this.getDownloadUrl(t,r),a=await s.fetch(o.url);if(!a.ok)throw new h(`Download failed: ${a.statusText}`,{code:"DOWNLOAD_ERROR",statusCode:a.status});return a.blob()},async list(t){let r={bucket:t?.bucket||e,prefix:t?.prefix,delimiter:t?.delimiter,limit:t?.limit,cursor:t?.cursor,includeUrls:t?.includeUrls},o=v(r);return n(`/storage/files${o}`)},async getMetadata(t,r){let o=r?.bucket||e;return n(`/storage/files/${encodeURIComponent(o)}/${encodeURIComponent(t)}/metadata`)},async updateMetadata(t,r,o){let a=o?.bucket||e;return n(`/storage/files/${encodeURIComponent(a)}/${encodeURIComponent(t)}/metadata`,{method:"PATCH",body:JSON.stringify(r)})},async exists(t,r){try{return await this.getMetadata(t,r),!0}catch{return false}},async copy(t,r,o){return n("/storage/files/copy",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:o?.sourceBucket||e,destinationKey:r,destinationBucket:o?.destinationBucket||o?.sourceBucket||e,metadata:o?.metadata})})},async move(t,r,o){return n("/storage/files/move",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:o?.sourceBucket||e,destinationKey:r,destinationBucket:o?.destinationBucket||o?.sourceBucket||e,metadata:o?.metadata})})},async delete(t,r){let o=r?.bucket||e;await n(`/storage/files/${encodeURIComponent(o)}/${encodeURIComponent(t)}`,{method:"DELETE"});},async deleteMany(t,r){return n("/storage/files/delete-batch",{method:"POST",body:JSON.stringify({keys:t,bucket:r?.bucket||e})})},getPublicUrl(t,r){let o=r?.bucket||e;return `${s.baseUrl.replace("/api","")}/storage/${encodeURIComponent(o)}/${encodeURIComponent(t)}`},async createBucket(t,r){return n("/storage/buckets",{method:"POST",body:JSON.stringify({name:t,isPublic:r?.isPublic,allowedMimeTypes:r?.allowedMimeTypes,maxFileSize:r?.maxFileSize,fileSizeLimit:r?.fileSizeLimit})})},async getBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}`)},async updateBucket(t,r){return n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})},async listBuckets(){return (await n("/storage/buckets")).buckets},async deleteBucket(t){await n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"DELETE"});},async emptyBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}/empty`,{method:"POST"})},async createMultipartUpload(t,r){return n("/storage/multipart/create",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,metadata:r?.metadata,partSize:r?.partSize})})},async uploadPart(t,r,o){let a=o instanceof Blob?o:new Blob([o]),{url:l}=await n(`/storage/multipart/${t}/part-url`,{method:"POST",body:JSON.stringify({partNumber:r})}),i=await s.fetch(l,{method:"PUT",body:a});if(!i.ok)throw new h(`Part upload failed: ${i.statusText}`,{code:"UPLOAD_PART_ERROR",statusCode:i.status});let c=i.headers.get("etag")||"";return {partNumber:r,etag:c}},async completeMultipartUpload(t,r){return n(`/storage/multipart/${t}/complete`,{method:"POST",body:JSON.stringify({parts:r})})},async abortMultipartUpload(t){await n(`/storage/multipart/${t}/abort`,{method:"POST"});}}}function z(s){let n=p(s);return {async list(e){let t=new URLSearchParams;e?.orgId&&t.set("orgId",e.orgId);let r=t.toString();return n(`/projects${r?`?${r}`:""}`)},async get(e){return n(`/projects/${e}`)},async create(e){return n("/projects",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async delete(e){return n(`/projects/${e}`,{method:"DELETE"})},async getComputeSettings(e){return n(`/projects/${e}/settings/compute`)},async updateComputeSettings(e,t){return n(`/projects/${e}/settings/compute`,{method:"PATCH",body:JSON.stringify(t)})},async getApiSettings(e){return n(`/projects/${e}/settings/api`)},async updateApiSettings(e,t){return n(`/projects/${e}/settings/api`,{method:"PATCH",body:JSON.stringify(t)})},async getJwtSettings(e){return n(`/projects/${e}/settings/jwt`)},async updateJwtSettings(e,t){return n(`/projects/${e}/settings/jwt`,{method:"PATCH",body:JSON.stringify(t)})},async rotateJwtSecret(e){return n(`/projects/${e}/settings/jwt/rotate`,{method:"POST"})},async getAddons(e){return n(`/projects/${e}/settings/addons`)},async updateAddons(e,t){return n(`/projects/${e}/settings/addons`,{method:"PATCH",body:JSON.stringify({enabledAddons:t})})},async getApiKeys(e){return n(`/projects/${e}/api-keys`)},async createApiKey(e,t){return n(`/projects/${e}/api-keys`,{method:"POST",body:JSON.stringify(t??{})})},async revokeApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/revoke`,{method:"POST"})},async rotateApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/rotate`,{method:"POST"})},async setCustomDomain(e,t,r){return n(`/projects/${e}/environments/${t}`,{method:"PATCH",body:JSON.stringify({customDomain:r})})},async getDomainVerificationInstructions(e,t){return n(`/projects/${e}/environments/${t}/domain-verification`)},async verifyDomainTxt(e,t){return n(`/projects/${e}/environments/${t}/verify-domain`,{method:"POST"})},async verifyDomainCname(e,t){return n(`/projects/${e}/environments/${t}/verify-cname`,{method:"POST"})},async getDomainStatus(e,t){return n(`/projects/${e}/environments/${t}/domain-status`)},async provisionSsl(e,t){return n(`/projects/${e}/environments/${t}/provision-ssl`,{method:"POST"})},async removeCustomDomain(e,t){return n(`/projects/${e}/environments/${t}`,{method:"PATCH",body:JSON.stringify({customDomain:null})})},async listApiKeys(e){return (await n(`/projects/${e}/api-keys`)).keys}}}function Q(s){let n=p(s);return {async list(){return n("/orgs")},async create(e){return n("/orgs",{method:"POST",body:JSON.stringify(e)})},async getProfile(e){return (await n(`/orgs/${e}/profile`)).profile||{}},async updateProfile(e,t){return (await n(`/orgs/${e}/profile`,{method:"PATCH",body:JSON.stringify(t)})).profile},async listBillingContacts(e){return (await n(`/orgs/${e}/billing-contacts`)).contacts},async addBillingContact(e,t){return n(`/orgs/${e}/billing-contacts`,{method:"POST",body:JSON.stringify(t)})},async removeBillingContact(e,t){return n(`/orgs/${e}/billing-contacts/${t}`,{method:"DELETE"})},async listMembers(e){return (await n(`/orgs/${e}/members`)).members},async inviteMember(e,t){return n(`/orgs/${e}/members/invite`,{method:"POST",body:JSON.stringify(t)})},async listInvites(e){return (await n(`/orgs/${e}/invites`)).invites},async cancelInvite(e,t){return n(`/orgs/${e}/invites/${t}`,{method:"DELETE"})},async removeMember(e,t){return n(`/orgs/${e}/members/${t}`,{method:"DELETE"})},async updateMemberRole(e,t,r){return n(`/orgs/${e}/members/${t}/role`,{method:"PATCH",body:JSON.stringify({role:r})})},async getMyMembership(e){try{return (await n(`/orgs/${e}/membership`)).membership}catch{return null}}}}function X(s){let n=p(s);return {async preview(e){return n("/schema-engine/preview",{method:"POST",body:JSON.stringify(e)})},async apply(e){return n("/schema-engine/apply",{method:"POST",body:JSON.stringify(e)})},async getMigrations(e,t){let r=t?`/schema-engine/migrations/project/${e}?limit=${t}`:`/schema-engine/migrations/project/${e}`;return n(r)},async saveSchema(e){return n("/schemas/",{method:"POST",body:JSON.stringify(e)})},async getSchemas(e){return n(`/schemas/project/${e}`)}}}function Y(s){let n=p(s);return {async create(e){return n("/functions/secrets",{method:"POST",body:JSON.stringify(e)})},async list(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/functions/secrets/project/${e}${o?`?${o}`:""}`;return n(a)},async reveal(e){return n(`/functions/secrets/${e}/value`)},async update(e,t){return n(`/functions/secrets/${e}`,{method:"PUT",body:JSON.stringify({value:t})})},async delete(e){return n(`/functions/secrets/${e}`,{method:"DELETE"})}}}function Z(s){let n=p(s);return {async list(e,t){let r=new URLSearchParams;t&&r.set("env",t);let o=r.toString(),a=`/deployments/project/${e}${o?`?${o}`:""}`;return (await n(a)).deployments},async get(e){let t=await n(`/deployments/${e}`);return {...t.deployment,steps:t.steps}},async getSteps(e){return (await n(`/deployments/${e}/steps`)).steps},async promote(e){let t={projectId:e.projectId,fromEnv:e.sourceEnv,toEnv:e.targetEnv},r=await n("/deployments/promote",{method:"POST",body:JSON.stringify(t)}),o=await n(`/deployments/${r.deploymentId}`);return {deployment:{...o.deployment,steps:o.steps}}},async rollback(e){return n(`/deployments/${e}/rollback`,{method:"POST"})},async listTokens(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/deployments/tokens/project/${encodeURIComponent(e)}${o?`?${o}`:""}`;return (await n(a)).tokens},async createToken(e){return n("/deployments/tokens",{method:"POST",body:JSON.stringify(e)})},async revokeToken(e){return n(`/deployments/tokens/${encodeURIComponent(e)}/revoke`,{method:"POST"})}}}function ee(s){let n=p(s);return {async getStats(e){return n(`/realtime/stats/project/${e}`)},async getConnections(e){return (await n(`/realtime/connections/project/${e}`)).connections},async getSubscriptions(e){return (await n(`/realtime/subscriptions/project/${e}`)).subscriptions},async getEvents(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.source&&t.source!=="all"&&r.set("source",t.source),t?.level&&t.level!=="all"&&r.set("level",t.level);let o=r.toString(),a=`/realtime/events/project/${e}${o?`?${o}`:""}`;return (await n(a)).events},async getStatus(e){return n(`/realtime/status/project/${e}`)},async install(e){return n("/realtime/install",{method:"POST",body:JSON.stringify(e)})},async enableAll(e){return n("/realtime/enable-all",{method:"POST",body:JSON.stringify(e)})}}}function te(s){let n=p(s);return {async listBuckets(e,t){let r=new URLSearchParams;r.set("projectId",e),t&&r.set("envId",t);let a=`/storage/buckets?${r.toString()}`;return (await n(a)).buckets},async getBucket(e){return (await n(`/buckets/${e}`)).bucket},async createBucket(e){return (await n("/buckets",{method:"POST",body:JSON.stringify(e)})).bucket},async updateBucket(e,t){return (await n(`/buckets/${e}`,{method:"PUT",body:JSON.stringify(t)})).bucket},async deleteBucket(e){return n(`/buckets/${e}`,{method:"DELETE"})},async listFiles(e,t){let r=new URLSearchParams;t?.prefix&&r.set("prefix",t.prefix),t?.maxKeys&&r.set("maxKeys",String(t.maxKeys)),t?.continuationToken&&r.set("continuationToken",t.continuationToken);let o=r.toString(),a=`/buckets/${e}/files${o?`?${o}`:""}`;return n(a)},async deleteFile(e,t){return n(`/buckets/${e}/files?key=${encodeURIComponent(t)}`,{method:"DELETE"})},async getSignedUrl(e,t,r){return n(`/buckets/${e}/signed-url`,{method:"POST",body:JSON.stringify({key:t,expiresIn:r})})},async getUploadUrl(e,t,r){return n(`/buckets/${e}/upload-url`,{method:"POST",body:JSON.stringify({key:t,...r})})},async uploadFile(e,t,r,o){let a=o?.prefix?`${o.prefix}${t}`:t,l=o?.contentType??(r instanceof Blob?r.type:"application/octet-stream"),i=new URLSearchParams;return i.set("key",a),l&&i.set("contentType",l),n(`/buckets/${e}/upload?${i.toString()}`,{method:"POST",body:r,headers:{"Content-Type":l||"application/octet-stream"}})}}}function ne(s){let n=p(s);return {async list(e,t){let r={type:t?.type,enabled:t?.enabled},o=v(r);return (await n(`/integrations/subscriptions/project/${e}${o}`)).subscriptions},async get(e){return n(`/integrations/subscriptions/${e}`)},async create(e){return (await n("/integrations/subscriptions",{method:"POST",body:JSON.stringify(e)})).subscription},async update(e,t){return (await n(`/integrations/subscriptions/${e}`,{method:"PATCH",body:JSON.stringify(t)})).subscription},async delete(e){return n(`/integrations/subscriptions/${e}`,{method:"DELETE"})},async enable(e){return this.update(e,{enabled:true})},async disable(e){return this.update(e,{enabled:false})},async test(e){return n(`/integrations/subscriptions/${e}/test`,{method:"POST"})},async publish(e){return n("/integrations/events/publish",{method:"POST",body:JSON.stringify(e)})},async publishBatch(e){return (await n("/integrations/events/publish-batch",{method:"POST",body:JSON.stringify({events:e})})).results},async listEvents(e){let t={envId:e.envId,source:e.source,name:e.name,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/events/project/${e.projectId}${r}`)).events},async getEvent(e){return n(`/integrations/events/${e}`)},async getDeliveries(e){let t={subscriptionId:e.subscriptionId,eventId:e.eventId,status:e.status,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/deliveries${r}`)).deliveries},async getDelivery(e){return n(`/integrations/deliveries/${e}`)},async retryDelivery(e){return n(`/integrations/deliveries/${e}/retry`,{method:"POST"})},async retryAllFailed(e){return n(`/integrations/subscriptions/${e}/retry-failed`,{method:"POST"})},async getDlq(e,t){let r={limit:t?.limit,offset:t?.offset},o=v(r);return (await n(`/integrations/dlq/project/${e}${o}`)).deliveries},async purgeDlq(e,t){return n(`/integrations/dlq/project/${e}/purge`,{method:"POST",body:JSON.stringify({olderThan:t.olderThan})})},async replayDlq(e,t){return n(`/integrations/dlq/project/${e}/replay`,{method:"POST",body:JSON.stringify(t)})},verifySignature(e){let t=e.tolerance??300;try{let r=e.signature.split(","),o=r.find(f=>f.startsWith("t=")),a=r.find(f=>f.startsWith("v1="));if(!o||!a)return !1;let l=parseInt(o.slice(2),10),i=a.slice(3),c=Math.floor(Date.now()/1e3);if(Math.abs(c-l)>t)return !1;let g=`${l}.${e.payload}`,y=new TextEncoder,k=y.encode(e.secret),S=y.encode(g),P=Array.from(k).concat(Array.from(S)).reduce((f,R)=>f+R,0).toString(16);if(i.length!==P.length)return !1;let A=0;for(let f=0;f<i.length;f++)A|=i.charCodeAt(f)^P.charCodeAt(f);return A===0}catch{return false}},generateSecret(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="whsec_";for(let r=0;r<32;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}}}function re(s){let n=p(s);return {async getSummary(e){return n(`/billing/org/${e}/summary`)},async getEntitlements(e){return n(`/entitlements/org/${e}`)},async checkEntitlement(e,t){return n(`/entitlements/org/${e}/check`,{method:"POST",body:JSON.stringify(t)})},async getPlans(){return (await n("/pricing/plans")).plans},async createCheckout(e){return n("/billing/checkout",{method:"POST",body:JSON.stringify(e)})},async verifyCheckoutSession(e){return n(`/billing/checkout/verify/${e}`)},async openPortal(e){return n(`/billing/org/${e.orgId}/portal`,{method:"POST",body:JSON.stringify({returnUrl:e.returnUrl})})},async getAIUsageSummary(e){return n(`/ai-usage/org/${e}/summary`)},async getAIUsageHistory(e,t=30){return n(`/ai-usage/org/${e}/history?days=${t}`)},async getAIUsageBreakdown(e){return n(`/ai-usage/org/${e}/breakdown`)},async getRecentAIRequests(e,t=50,r=0){return n(`/ai-usage/org/${e}/recent?limit=${t}&offset=${r}`)}}}function oe(s){let n=p(s);return {async getOverview(){return n("/admin/overview")},async listUsers(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/users${r?`?${r}`:""}`)},async getUser(e){return n(`/admin/users/${e}`)},async updateUserStatus(e,t){return n(`/admin/users/${e}/status`,{method:"PATCH",body:JSON.stringify({status:t})})},async updateUserAdmin(e,t){return n(`/admin/users/${e}/admin`,{method:"PATCH",body:JSON.stringify({isAdmin:t})})},async listOrganizations(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.plan&&t.set("plan",e.plan),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/organizations${r?`?${r}`:""}`)},async getOrganization(e){return n(`/admin/organizations/${e}`)},async updateOrganization(e,t){return n(`/admin/organizations/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async listProjects(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.orgId&&t.set("orgId",e.orgId),e?.region&&t.set("region",e.region),e?.tenancy&&t.set("tenancy",e.tenancy),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/projects${r?`?${r}`:""}`)},async getProject(e){return n(`/admin/projects/${e}`)},async updateProject(e,t){return n(`/admin/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getProjectResources(e){return n(`/admin/resources/project/${e}`)},async setDedicatedDb(e){return n(`/admin/resources/project/${e.projectId}/db`,{method:"POST",body:JSON.stringify({connectionString:e.connectionString})})},async listIncidents(e="open"){return (await n(`/admin/incidents?status=${e}`)).incidents},async createIncident(e){return n("/admin/incidents",{method:"POST",body:JSON.stringify(e)})},async acknowledgeIncident(e){return n(`/admin/incidents/${e}/ack`,{method:"POST"})},async resolveIncident(e){return n(`/admin/incidents/${e}/resolve`,{method:"POST"})},async listRegions(){return n("/admin/regions")},async updateRegion(e,t){return n(`/admin/regions/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getHealthComponents(){return n("/admin/health/components")},async updateHealthComponent(e,t){return n(`/admin/health/components/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getSystemInfo(){return n("/admin/system/info")},async listQueues(){return n("/admin/queues")},async listDlqMessages(e){let t=new URLSearchParams;e?.queue&&t.set("queue",e.queue),e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/dlq${r?`?${r}`:""}`)},async retryDlqMessage(e){return n(`/admin/dlq/${e}/retry`,{method:"POST"})},async archiveDlqMessage(e){return n(`/admin/dlq/${e}`,{method:"DELETE"})},async listFeatureFlags(){return (await n("/flags")).flags},async createFeatureFlag(e,t){return n("/flags",{method:"POST",body:JSON.stringify({key:e,enabled:t})})},async updateFeatureFlag(e,t){return n(`/flags/${e}`,{method:"PUT",body:JSON.stringify({enabled:t})})},async deleteFeatureFlag(e){return n(`/flags/${e}`,{method:"DELETE"})},async listAdmins(){return (await n("/admin/admins")).admins||[]},async addAdmin(e,t,r){return n("/admin/admins",{method:"POST",body:JSON.stringify({userId:e,role:t,notes:r})})},async updateAdmin(e,t){return n(`/admin/admins/${e}`,{method:"PUT",body:JSON.stringify(t)})},async removeAdmin(e){return n(`/admin/admins/${e}`,{method:"DELETE"})},async getSettings(e){let t=e?`?category=${e}`:"";return n(`/admin/settings${t}`)},async updateSetting(e,t){return n(`/admin/settings/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({value:t})})},async listAIModels(){return n("/admin/ai/models")},async getAIModel(e){return n(`/admin/ai/models/${e}`)},async createAIModel(e){return n("/admin/ai/models",{method:"POST",body:JSON.stringify(e)})},async updateAIModel(e,t){return n(`/admin/ai/models/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteAIModel(e){return n(`/admin/ai/models/${e}`,{method:"DELETE"})},async toggleAIModel(e,t,r){return n(`/admin/ai/models/${e}/toggle`,{method:"POST",body:JSON.stringify({enabled:t,disabledMessage:r})})},async listAISessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/workspace/sessions${r?`?${r}`:""}`)},async getAISession(e){return n(`/admin/ai/workspace/sessions/${e}`)},async deleteAISession(e){return n(`/admin/ai/workspace/sessions/${e}`,{method:"DELETE"})},async listGeneratedBackends(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/backends${r?`?${r}`:""}`)},async getGeneratedBackend(e){return n(`/admin/ai/backends/${e}`)},async deleteGeneratedBackend(e){return n(`/admin/ai/backends/${e}`,{method:"DELETE"})},async listPromptTemplates(e){let t=new URLSearchParams;e?.category&&t.set("category",e.category),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/prompt-templates${r?`?${r}`:""}`)},async createPromptTemplate(e){return n("/admin/ai/prompt-templates",{method:"POST",body:JSON.stringify(e)})},async updatePromptTemplate(e,t){return n(`/admin/ai/prompt-templates/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deletePromptTemplate(e){return n(`/admin/ai/prompt-templates/${e}`,{method:"DELETE"})},async listContextSnapshots(e){let t=new URLSearchParams;e?.projectId&&t.set("projectId",e.projectId),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/context-snapshots${r?`?${r}`:""}`)},async invalidateContextSnapshot(e){return n(`/admin/ai/context-snapshots/${e}/invalidate`,{method:"POST"})},async deleteContextSnapshot(e){return n(`/admin/ai/context-snapshots/${e}`,{method:"DELETE"})},async getCopilotOverview(){return n("/admin/copilot/overview")},async listCopilotSessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/sessions${r?`?${r}`:""}`)},async getCopilotSession(e){return n(`/admin/copilot/sessions/${e}`)},async deleteCopilotSession(e){return n(`/admin/copilot/sessions/${e}`,{method:"DELETE"})},async listCopilotMemories(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.projectId&&t.set("projectId",e.projectId),e?.memoryType&&t.set("memoryType",e.memoryType),e?.importance&&t.set("importance",e.importance),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/memories${r?`?${r}`:""}`)},async getCopilotMemoryStats(){return n("/admin/copilot/memories/stats")},async getCopilotMemory(e){return n(`/admin/copilot/memories/${e}`)},async updateCopilotMemory(e,t){return n(`/admin/copilot/memories/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteCopilotMemory(e){return n(`/admin/copilot/memories/${e}`,{method:"DELETE"})},async cleanupExpiredMemories(){return n("/admin/copilot/memories/cleanup",{method:"POST"})},async exportTrainingData(e){let t=new URLSearchParams;e?.format&&t.set("format",e.format),e?.dataType&&t.set("dataType",e.dataType),e?.minConfidence!==void 0&&t.set("minConfidence",String(e.minConfidence)),e?.limit&&t.set("limit",String(e.limit)),e?.includeExecuted!==void 0&&t.set("includeExecuted",String(e.includeExecuted)),e?.includeSuccessful!==void 0&&t.set("includeSuccessful",String(e.includeSuccessful));let r=t.toString();return n(`/admin/copilot/training-data/export${r?`?${r}`:""}`)},async getTrainingDataStats(){return n("/admin/copilot/training-data/stats")},async listErrors(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.path&&t.set("path",e.path),e?.errorCode&&t.set("errorCode",e.errorCode),e?.status&&t.set("status",e.status),e?.environment&&t.set("environment",e.environment),e?.startDate&&t.set("startDate",e.startDate),e?.endDate&&t.set("endDate",e.endDate),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/errors${r?`?${r}`:""}`)},async getErrorStats(){return n("/admin/errors/stats")},async getError(e){return n(`/admin/errors/${e}`)},async resolveError(e,t){return n(`/admin/errors/${e}/resolve`,{method:"PUT",body:JSON.stringify({notes:t})})},async deleteError(e){return n(`/admin/errors/${e}`,{method:"DELETE"})},async bulkDeleteErrors(e){let t=e?`?olderThanDays=${e}`:"";return n(`/admin/errors${t}`,{method:"DELETE"})},async getAIWorkspaceOverview(){return n("/admin/ai-workspace/overview")},async listAIWorkspaceSessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.taskType&&t.set("taskType",e.taskType),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai-workspace/sessions${r?`?${r}`:""}`)},async getAIWorkspaceSession(e){return n(`/admin/ai-workspace/sessions/${e}`)},async deleteAIWorkspaceSession(e){return n(`/admin/ai-workspace/sessions/${e}`,{method:"DELETE"})}}}function se(s){let n=p(s);return {async list(){return (await n("/flags")).flags},async create(e){return n("/flags",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/flags/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)})},async delete(e){return n(`/flags/${encodeURIComponent(e)}`,{method:"DELETE"})}}}function ie(s){let n=p(s);return {async getOverview(e){return (await n(`/security/overview/${encodeURIComponent(e)}`)).overview},async getAuditLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));let o=r.toString(),a=`/security/audit/${encodeURIComponent(e)}${o?`?${o}`:""}`;return n(a)},async listEnvVars(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/projects/${encodeURIComponent(e)}/env-vars${o?`?${o}`:""}`;return (await n(a)).envVars},async createEnvVar(e,t){return (await n(`/projects/${encodeURIComponent(e)}/env-vars`,{method:"POST",body:JSON.stringify(t)})).envVar},async updateEnvVar(e,t,r){return (await n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})).envVar},async deleteEnvVar(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"DELETE"})},async getEnvVarValue(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}/value`)}}}function ae(s){let n=p(s);return {async generatePlan(e){return n("/ai/plan",{method:"POST",body:JSON.stringify({projectId:e.projectId,prompt:e.prompt,context:e.context,taskType:e.taskType,mode:e.mode})})},async explainPlan(e){return n("/ai/explain",{method:"POST",body:JSON.stringify({plan:e.plan,projectId:e.projectId,taskType:e.taskType,mode:e.mode})})},async getOrgSettings(e){return n(`/ai/settings/org/${encodeURIComponent(e)}`)},async updateOrgSettings(e,t){return n(`/ai/settings/org/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getProjectOverrides(e){return n(`/ai/settings/project/${encodeURIComponent(e)}`)},async updateProjectOverrides(e,t){return n(`/ai/settings/project/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getUsage(e,t){let r=new URLSearchParams;t&&r.set("month",t);let o=r.toString(),a=`/ai/usage/org/${encodeURIComponent(e)}${o?`?${o}`:""}`;return n(a)},async getBudgetStatus(e){let[t,r]=await Promise.all([this.getOrgSettings(e),this.getUsage(e)]),o=t?.monthlyBudgetCents??1e4,a=r.costCents,l=Math.max(0,o-a),i=o>0?Math.round(a/o*100):0;return {spent:a,budget:o,remaining:l,hardStop:t?.hardStopEnabled??false,percentUsed:i}},async generateFunction(e){return n("/ai/generate-function",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,language:e.language??"typescript",mode:e.mode})})},async generateEndpoint(e){return n("/ai/generate-endpoint",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,method:e.method??"GET",authRequired:e.authRequired??true,mode:e.mode})})},async exportCode(e){return n("/ai/export-code",{method:"POST",body:JSON.stringify({projectId:e.projectId,targetLanguage:e.targetLanguage,includeSchema:e.includeSchema??true,includeFunctions:e.includeFunctions??true,includeEndpoints:e.includeEndpoints??true})})},async createConversation(e,t){return n("/ai/conversations",{method:"POST",body:JSON.stringify({projectId:e,title:t?.title,context:t?.context})})},async sendMessage(e,t){return n(`/ai/conversations/${encodeURIComponent(e)}/messages`,{method:"POST",body:JSON.stringify({content:t.content,taskType:t.taskType})})},async getConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`)},async listConversations(e){return (await n(`/ai/conversations/project/${encodeURIComponent(e)}`)).conversations},async deleteConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`,{method:"DELETE"})},async getAvailableModels(){return n("/ai/models/available")},async getModel(e){return n(`/ai/models/${encodeURIComponent(e)}`)},async getProjectContext(e){return n(`/ai/context/${encodeURIComponent(e)}`)},async estimateTokens(e,t){return n("/ai/context/estimate",{method:"POST",body:JSON.stringify({prompt:e,projectId:t})})},async analyzeForClarification(e){return n("/ai/clarify",{method:"POST",body:JSON.stringify(e)})},async getSuggestions(e){return n("/ai/suggestions",{method:"POST",body:JSON.stringify(e)})},workspace:{async create(e){return n("/ai/workspace/create",{method:"POST",body:JSON.stringify(e)})},async get(e){return n(`/ai/workspace/${encodeURIComponent(e)}`)},async list(e){return n(`/ai/workspace/list/${encodeURIComponent(e)}`)},async submitPrompt(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/prompt`,{method:"POST",body:JSON.stringify(t),timeout:12e4})},async submitClarification(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/clarify`,{method:"POST",body:JSON.stringify({responses:t}),timeout:9e4})},async generate(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/generate`,{method:"POST",body:JSON.stringify(t),timeout:18e4})},async submitModification(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/modify`,{method:"POST",body:JSON.stringify(t),timeout:18e4})},async submitFeedback(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/feedback`,{method:"POST",body:JSON.stringify(t)})}},backends:{async get(e){return n(`/ai/backends/${encodeURIComponent(e)}`)},async list(e){return n(`/ai/backends/list/${encodeURIComponent(e)}`)},async delete(e){return n(`/ai/backends/${encodeURIComponent(e)}`,{method:"DELETE"})},async deploy(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/deploy`,{method:"POST",body:JSON.stringify(t)})},async apply(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify(t)})},async deployLive(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/deploy-live`,{method:"POST",body:JSON.stringify(t),timeout:3e5})},async getDeployments(e){return n(`/ai/backends/${encodeURIComponent(e)}/deployments`)}},deployments:{async getLimits(e){return n(`/ai/deployments/limits/${encodeURIComponent(e)}`)},async getStatus(e){return n(`/ai/deployments/${encodeURIComponent(e)}/status`)},async getLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.severity&&r.set("severity",t.severity);let o=r.toString();return n(`/ai/deployments/${encodeURIComponent(e)}/logs${o?`?${o}`:""}`)},async terminate(e){return n(`/ai/deployments/${encodeURIComponent(e)}`,{method:"DELETE"})},async redeploy(e){return n(`/ai/deployments/${encodeURIComponent(e)}/redeploy`,{method:"POST",timeout:3e5})}},async getUserOrganizations(){return n("/ai/user/organizations")},async getProjectLimits(e){return n(`/ai/org/${encodeURIComponent(e)}/project-limits`)},async createProjectWithSchema(e){return n("/ai/schema/create-project",{method:"POST",body:JSON.stringify(e)})}}}function le(s){let n=p(s);return {async load(){return n("/bootstrap")}}}function ce(s){let n=p(s);return {async list(e){let t=new URLSearchParams;e?.visibility&&t.set("visibility",e.visibility),e?.category&&t.set("category",e.category),e?.orgId&&t.set("orgId",e.orgId);let r=t.toString(),o=`/templates${r?`?${r}`:""}`;return (await n(o)).templates},async get(e){return n(`/templates/${e}`)},async create(e){return n("/templates",{method:"POST",body:JSON.stringify(e)})},async previewInstall(e){return n("/templates/install/preview",{method:"POST",body:JSON.stringify(e)})},async applyInstall(e){return n("/templates/install/apply",{method:"POST",body:JSON.stringify(e)})},async rollback(e){return n(`/templates/install/${e}/rollback`,{method:"POST"})},async createProject(e){return n("/templates/create-project",{method:"POST",body:JSON.stringify(e)})}}}function de(s){let n=p(s);return {async list(e){return (await n(`/oauth/org/${e}`)).connections},async configure(e,t){return n(`/oauth/org/${e}/configure`,{method:"POST",body:JSON.stringify(t)})},async update(e,t,r){return n(`/oauth/org/${e}/provider/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(e,t){return n(`/oauth/org/${e}/provider/${t}`,{method:"DELETE"})}}}function ue(s){let n=p(s);return {async listPages(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/pages${t}`)).pages},async getPage(e){return (await n(`/docs/pages/${encodeURIComponent(e)}`)).page},async createPage(e){return (await n("/docs/pages",{method:"POST",body:JSON.stringify(e)})).page},async updatePage(e,t){return (await n(`/docs/pages/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).page},async deletePage(e){return n(`/docs/pages/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdks(){return (await n("/docs/sdks")).sdks},async getSdk(e){return (await n(`/docs/sdks/${encodeURIComponent(e)}`)).sdk},async createSdk(e){return (await n("/docs/sdks",{method:"POST",body:JSON.stringify(e)})).sdk},async updateSdk(e,t){return (await n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).sdk},async deleteSdk(e){return n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdkExamples(e,t){let r=t?`?topic=${encodeURIComponent(t)}`:"";return (await n(`/docs/sdks/${encodeURIComponent(e)}/examples${r}`)).examples},async createSdkExample(e){return (await n("/docs/sdk-examples",{method:"POST",body:JSON.stringify(e)})).example},async deleteSdkExample(e){return n(`/docs/sdk-examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listEndpoints(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/api-endpoints${t}`)).endpoints},async getEndpoint(e){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`)).endpoint},async createEndpoint(e){return (await n("/docs/api-endpoints",{method:"POST",body:JSON.stringify(e)})).endpoint},async updateEndpoint(e,t){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).endpoint},async deleteEndpoint(e){return n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},async listExamples(e){let t=e!==void 0?`?featured=${e}`:"";return (await n(`/docs/examples${t}`)).examples},async getExample(e){return (await n(`/docs/examples/${encodeURIComponent(e)}`)).example},async createExample(e){return (await n("/docs/examples",{method:"POST",body:JSON.stringify(e)})).example},async updateExample(e,t){return (await n(`/docs/examples/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).example},async deleteExample(e){return n(`/docs/examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listChangelog(){return (await n("/docs/changelog")).entries},async getChangelogEntry(e){return (await n(`/docs/changelog/${encodeURIComponent(e)}`)).entry},async createChangelogEntry(e){return (await n("/docs/changelog",{method:"POST",body:JSON.stringify(e)})).entry},async updateChangelogEntry(e,t){return (await n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).entry},async deleteChangelogEntry(e){return n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"DELETE"})},async search(e){return (await n(`/docs/search?q=${encodeURIComponent(e)}`)).results}}}function J(s,n,e,t){let r=[...n],o=0,a=false,l=false,i=async()=>{if(l||a)return;let c=await e(`/mongodb/${t}/cursor/${s}/next`,{method:"POST"});r=c.batch,o=0,a=c.exhausted;};return {id:s,async hasNext(){return l?false:o<r.length?true:a?false:(await i(),r.length>0)},async next(){return l?null:o<r.length?r[o++]:a||(await i(),r.length===0)?null:r[o++]},async toArray(){if(l)return [];let c=[];for(;o<r.length;)c.push(r[o++]);for(;!a;)await i(),c.push(...r),o=r.length;return c},async forEach(c){if(!l){for(;o<r.length;)await c(r[o++]);for(;!a;){await i();for(let g of r)await c(g);o=r.length;}}},map(c){let g=r.slice(o).map(c);return J(s,g,e,t)},async close(){if(!l){l=true;try{await e(`/mongodb/${t}/cursor/${s}/close`,{method:"POST"});}catch{}}},isClosed(){return l}}}function Oe(s,n){let e=`/mongodb/${encodeURIComponent(s)}`;return {collectionName:s,async find(t,r){return n(`${e}/find`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async findCursor(t,r){let o=await n(`${e}/find/cursor`,{method:"POST",body:JSON.stringify({filter:t,options:r})});return J(o.cursorId,o.batch,n,s)},async findOne(t,r){return n(`${e}/findOne`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async findById(t,r){return n(`${e}/findById/${encodeURIComponent(t)}`,{method:"GET",...r&&{body:JSON.stringify({options:r})}})},async countDocuments(t){return (await n(`${e}/count`,{method:"POST",body:JSON.stringify({filter:t})})).count},async estimatedDocumentCount(){return (await n(`${e}/estimatedCount`)).count},async distinct(t,r){return n(`${e}/distinct`,{method:"POST",body:JSON.stringify({field:t,...r})})},async insertOne(t){return n(`${e}/insertOne`,{method:"POST",body:JSON.stringify({document:t})})},async insertMany(t,r){return n(`${e}/insertMany`,{method:"POST",body:JSON.stringify({documents:t,options:r})})},async updateOne(t,r,o){return n(`${e}/updateOne`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async updateMany(t,r,o){return n(`${e}/updateMany`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async replaceOne(t,r,o){return n(`${e}/replaceOne`,{method:"POST",body:JSON.stringify({filter:t,replacement:r,options:o})})},async findOneAndUpdate(t,r,o){return n(`${e}/findOneAndUpdate`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async findOneAndReplace(t,r,o){return n(`${e}/findOneAndReplace`,{method:"POST",body:JSON.stringify({filter:t,replacement:r,options:o})})},async deleteOne(t){return n(`${e}/deleteOne`,{method:"POST",body:JSON.stringify({filter:t})})},async deleteMany(t){return n(`${e}/deleteMany`,{method:"POST",body:JSON.stringify({filter:t})})},async findOneAndDelete(t,r){return n(`${e}/findOneAndDelete`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async aggregate(t,r){return n(`${e}/aggregate`,{method:"POST",body:JSON.stringify({pipeline:t,options:r})})},async aggregateCursor(t,r){let o=await n(`${e}/aggregate/cursor`,{method:"POST",body:JSON.stringify({pipeline:t,options:r})});return J(o.cursorId,o.batch,n,s)},async createIndex(t,r){return (await n(`${e}/indexes`,{method:"POST",body:JSON.stringify({keys:t,options:r})})).indexName},async dropIndex(t){await n(`${e}/indexes/${encodeURIComponent(t)}`,{method:"DELETE"});},async listIndexes(){return n(`${e}/indexes`)},async bulkWrite(t,r){return n(`${e}/bulkWrite`,{method:"POST",body:JSON.stringify({operations:t,options:r})})}}}function ge(s){let n=p(s);return {collection(e){return Oe(e,n)},async listCollections(){return n("/mongodb/collections")},async createCollection(e,t){await n("/mongodb/collections",{method:"POST",body:JSON.stringify({name:e,options:t})});},async dropCollection(e){await n(`/mongodb/collections/${encodeURIComponent(e)}`,{method:"DELETE"});},async renameCollection(e,t){await n(`/mongodb/collections/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({newName:t})});},async command(e){return n("/mongodb/command",{method:"POST",body:JSON.stringify(e)})}}}function pe(s){let n=p(s);return {async chat(e){return n("/ai/copilot/chat",{method:"POST",body:JSON.stringify(e),timeout:12e4})},getStreamUrl(){return `${s.baseUrl}/ai/copilot/chat/stream`},async getModels(e){return n(`/ai/copilot/models/${encodeURIComponent(e)}`)},async getCreditStatus(e){return n(`/ai/copilot/credit-status/${encodeURIComponent(e)}`)},async listSessions(e){return n(`/ai/copilot/sessions/${encodeURIComponent(e)}`)},async getSession(e){return n(`/ai/copilot/session/${encodeURIComponent(e)}`)},async updateSession(e,t){return n(`/ai/copilot/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteSession(e){return n(`/ai/copilot/session/${encodeURIComponent(e)}`,{method:"DELETE"})},async executePlan(e){return n("/ai/copilot/execute",{method:"POST",body:JSON.stringify(e),timeout:18e4})},async submitFeedback(e){return n("/ai/copilot/feedback",{method:"POST",body:JSON.stringify(e)})},async getClassificationStats(){return n("/ai/copilot/stats")},async getUsage(e){return n(`/ai/copilot/usage-org/${encodeURIComponent(e)}`)}}}function xe(s,n,e,t){let r=n.type||"public",o="unsubscribed",a=new Map,l=[],i={},c=null,g=null,y=new Set,k=new Set,S=new Set,P=d=>{if(d.event){let b=a.get(d.event);b&&b.forEach(T=>T(d.payload));}},A=d=>{i=d.state||{},y.forEach(b=>b(i));},f=d=>{let b=d.key||"",T=d.currentPresences||[],u=d.joinedPresences||[],m=d.leftPresences||[];u.length>0&&(i[b]=T,k.forEach(I=>I(b,T,u))),m.length>0&&(T.length===0?delete i[b]:i[b]=T,S.forEach(I=>I(b,T,m))),y.forEach(I=>I(i));},R=d=>{let b={type:"db_change",projectId:d.projectId||"",schema:d.schema||"",table:d.table||"",operation:d.op,new:d.record,old:d.old_record,timestamp:d.ts||new Date().toISOString(),partial:d.partial};l.forEach(({options:T,handler:u})=>{if(T.table===b.table){let m=T.event||"*";(m==="*"||(Array.isArray(m)?m.includes(b.operation):m===b.operation))&&u(b);}});},C={get name(){return s},get type(){return r},get status(){return o},_handleMessage:d=>{switch(d.type){case "broadcast":P(d);break;case "presence_state":A(d);break;case "presence":f(d);break;case "db_change":R(d);break;case "subscribed":o="subscribed";break;case "error":o="error";break}},onDbChange(d,b){return l.push({options:d,handler:b}),o==="subscribed"&&e({type:"subscribe",channel:s,options:{table:d.table,filter:d.filter,event:d.event,columns:d.columns}}),C},on(d,b){return a.has(d)||a.set(d,new Set),a.get(d).add(b),C},off(d,b){return b?a.get(d)?.delete(b):a.delete(d),C},async broadcast(d){if(o!=="subscribed")throw new h("Channel must be subscribed before broadcasting",{code:"CHANNEL_NOT_SUBSCRIBED"});e({type:"broadcast",channel:s,event:d.event,payload:d.payload,includeSelf:d.includeSelf});},presence:{async track(d){if(r!=="presence")throw new h("Presence tracking is only available on presence channels",{code:"INVALID_CHANNEL_TYPE"});c=d.key||t()||"anonymous",g=d.state,e({type:"presence_track",channel:s,key:c,state:g});},async update(d){if(!g)throw new h("Must call track() before update()",{code:"PRESENCE_NOT_TRACKED"});g={...g,...d},e({type:"presence_update",channel:s,key:c??void 0,state:g});},async untrack(){c&&(e({type:"presence_untrack",channel:s,key:c}),c=null,g=null);},state(){return {...i}},onSync(d){return y.add(d),C},onJoin(d){return k.add(d),C},onLeave(d){return S.add(d),C}},async subscribe(){return o==="subscribed"||(o="subscribing",e({type:"subscribe",channel:s}),l.forEach(({options:d})=>{e({type:"subscribe",channel:s,options:{table:d.table,filter:d.filter,event:d.event,columns:d.columns}});}),n.presenceState&&r==="presence"&&await C.presence.track({state:n.presenceState})),C},async unsubscribe(){o!=="unsubscribed"&&(c&&await C.presence.untrack(),e({type:"unsubscribe",channel:s}),o="unsubscribed",i={},a.clear(),l.length=0);}};return C}function me(s,n){let{wsUrl:e=s.baseUrl.replace(/^http/,"ws")+"/realtime/ws",autoReconnect:t=true,reconnectDelay:r=1e3,maxReconnectAttempts:o=10}=n??{},a=null,l="disconnected",i=null,c=null,g=0,y=null,k=null,S=new Map,P=new Map,A=new Set,f={connect:new Set,disconnect:new Set,error:new Set,reconnect:new Set},R=u=>{f[u].forEach(m=>m());},O=u=>{let m=`table:${u.table}`;if(u.filter){let M=(Array.isArray(u.filter)?u.filter:[u.filter]).map(w=>`${w.field}${w.operator||"eq"}${w.value}`).join("&");m+=`?${M}`;}return m},C=u=>{a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(u));},d=u=>{if(u.channel){let m=S.get(u.channel);if(m){m._handleMessage(u);return}}switch(u.type){case "db_change":{let m={type:"db_change",projectId:u.projectId??"",schema:u.schema??"",table:u.table??"",operation:u.op,new:u.record,old:u.old_record,timestamp:u.ts??new Date().toISOString(),partial:u.partial},I=`table:${u.table}`;P.forEach((M,w)=>{(w===I||w.startsWith(I+"?"))&&M.forEach(N=>N(m));});break}case "presence":{let m={type:"presence",event:u.event,key:u.key||u.connectionId||"",connectionId:u.connectionId??"",projectId:u.projectId??"",currentPresences:u.currentPresences||[],leftPresences:u.leftPresences||[],joinedPresences:u.joinedPresences||[]};A.forEach(I=>I(m));break}case "welcome":i=u.connectionId||null;break;case "error":{R("error");break}}},b=()=>new Promise((u,m)=>{try{a=new WebSocket(e);}catch{m(new x("Failed to create WebSocket connection"));return}let I=()=>{l="connected",g=0;let D={type:"auth"};s.apiKey&&(D[s.apiKeyHeader]=s.apiKey),c&&(D.token=c),C(D),R("connect"),S.forEach(B=>{(B.status==="subscribed"||B.status==="subscribing")&&B.subscribe();}),P.forEach((B,ye)=>{C({type:"subscribe",channel:ye});}),k=setInterval(()=>{C({type:"ping"});},3e4),u();},M=D=>{try{let B=JSON.parse(D.data);d(B);}catch{}},w=()=>{if(l="disconnected",i=null,a=null,k&&(clearInterval(k),k=null),R("disconnect"),t&&g<o){l="reconnecting";let D=r*Math.pow(2,g);y=setTimeout(()=>{g++,R("reconnect"),b().catch(()=>{});},Math.min(D,3e4));}},N=()=>{R("error"),m(new x("WebSocket connection error"));};a.addEventListener("open",I),a.addEventListener("message",M),a.addEventListener("close",w),a.addEventListener("error",N);}),T=()=>{y&&(clearTimeout(y),y=null),k&&(clearInterval(k),k=null),g=o;};return {channel(u,m={}){let I=S.get(u);if(I)return I;let M=xe(u,m,C,()=>i);return S.set(u,M),M},async removeChannel(u){let m=S.get(u.name);m&&(await m.unsubscribe(),S.delete(u.name));},getChannels(){return Array.from(S.values())},subscribe(u,m){let I=O(u);return P.has(I)||P.set(I,new Set),P.get(I).add(m),a?.readyState===WebSocket.OPEN&&C({type:"subscribe",channel:I}),()=>{let M=P.get(I);M&&(M.delete(m),M.size===0&&(P.delete(I),a?.readyState===WebSocket.OPEN&&C({type:"unsubscribe",channel:I})));}},subscribeToPresence(u){return A.add(u),()=>{A.delete(u);}},async connect(){if(l!=="connected"){if(!s.apiKey)throw new E("API key is required for realtime connections");l="connecting",await b();}},disconnect(){T(),S.forEach(u=>{u.unsubscribe();}),S.clear(),a&&(a.close(),a=null),l="disconnected",i=null;},get isConnected(){return l==="connected"},get connectionState(){return l},get connectionId(){return i},on(u,m){f[u].add(m);},off(u,m){f[u].delete(m);},setAuth(u){c=u;}}}var F={apiKeyHeader:"x-vaif-key",timeout:3e4,retry:{maxRetries:3,retryDelay:1e3,maxRetryDelay:3e4,backoffMultiplier:2,retryOn:[429,500,502,503,504],retryOnNetworkError:true}};function Me(s){return {baseUrl:s.baseUrl.replace(/\/$/,""),apiKey:s.apiKey,apiKeyHeader:s.apiKeyHeader??F.apiKeyHeader,accessToken:s.accessToken,fetch:s.fetch??globalThis.fetch.bind(globalThis),timeout:s.timeout??F.timeout,retry:{maxRetries:s.retry?.maxRetries??F.retry.maxRetries,retryDelay:s.retry?.retryDelay??F.retry.retryDelay,maxRetryDelay:s.retry?.maxRetryDelay??F.retry.maxRetryDelay,backoffMultiplier:s.retry?.backoffMultiplier??F.retry.backoffMultiplier,retryOn:s.retry?.retryOn??[...F.retry.retryOn],retryOnNetworkError:s.retry?.retryOnNetworkError??F.retry.retryOnNetworkError},interceptors:s.interceptors??{}}}function Ee(s){let n=Me(s),e=W(n),t=_(n),r=H(n),o=G(n),a=z(n),l=Q(n),i=X(n),c=Y(n),g=Z(n),y=ee(n),k=te(n),S=ne(n),P=re(n),A=oe(n),f=se(n),R=ie(n),O=ae(n),C=le(n),d=ce(n),b=de(n),T=ue(n),u=ge(n),m=pe(n);return {from:e.from,auth:t,functions:r,storage:o,projects:a,orgs:l,schema:i,secrets:c,deployments:g,realtimeMonitoring:y,storageDashboard:k,integrations:S,billing:P,admin:A,flags:f,security:R,ai:O,bootstrap:C,templates:d,oauth:b,docs:T,mongodb:u,copilot:m,realtime:I=>me(n,I)}}export{E as VaifAuthError,L as VaifConflictError,h as VaifError,x as VaifNetworkError,$ as VaifNotFoundError,U as VaifRateLimitError,V as VaifTimeoutError,j as VaifValidationError,Ee as createVaifClient,Pe as isVaifAuthError,be as isVaifError,ke as isVaifNetworkError,fe as isVaifNotFoundError,he as isVaifRateLimitError,Ie as isVaifValidationError};
1
+ export{AuthError,InvalidCredentialsError,SessionExpiredError,SessionStorage,VaifAuthClient,localStorage as authLocalStorage,sessionStorage as authSessionStorage,cookieStorage,createAuthClient,getDefaultStorage,isBrowser,isMFAChallenge,memoryStorage}from'@vaiftech/auth';var k=class s extends Error{constructor(n,e){super(n),this.name="VaifError",this.code=e.code,this.statusCode=e.statusCode,this.requestId=e.requestId,this.details=e.details;let t=Error;t.captureStackTrace&&t.captureStackTrace(this,s);}toJSON(){return {name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,details:this.details}}},E=class extends k{constructor(n,e){super(n,{code:e?.code??"AUTH_ERROR",statusCode:e?.statusCode??401,requestId:e?.requestId}),this.name="VaifAuthError";}},j=class extends k{constructor(n,e){super(n,{code:"VALIDATION_ERROR",statusCode:400,requestId:e?.requestId,details:e?.details??e?.fieldErrors}),this.name="VaifValidationError",this.fieldErrors=e?.fieldErrors;}},x=class extends k{constructor(n,e){super(n,{code:"NETWORK_ERROR"}),this.name="VaifNetworkError",this.cause=e;}},U=class extends k{constructor(n,e){super(n,{code:"RATE_LIMITED",statusCode:429}),this.name="VaifRateLimitError",this.retryAfter=e;}},$=class extends k{constructor(n,e){super(n,{code:"NOT_FOUND",statusCode:404,requestId:e}),this.name="VaifNotFoundError";}},L=class extends k{constructor(n,e){super(n,{code:"CONFLICT",statusCode:409,requestId:e}),this.name="VaifConflictError";}},V=class extends x{constructor(n,e){super(n),this.name="VaifTimeoutError",this.timeoutMs=e;}};function be(s){return s instanceof k}function fe(s){return s instanceof $}function Pe(s){return s instanceof E}function Ie(s){return s instanceof j}function ke(s){return s instanceof U}function he(s){return s instanceof x}async function Se(s){let n;try{n=await s.json();}catch{}let e=n?.message??n?.error??s.statusText??"Request failed",t=n?.requestId;switch(s.status){case 400:return new j(e,{details:n?.details,requestId:t});case 401:return new E(e,{code:"UNAUTHORIZED",statusCode:401,requestId:t});case 403:return new E(e,{code:"FORBIDDEN",statusCode:403,requestId:t});case 404:return new $(e,t);case 409:return new k(e,{code:"CONFLICT",statusCode:409,requestId:t,details:n?.details});case 422:return new j(e,{details:n?.details,requestId:t});case 429:{let r=s.headers.get("Retry-After"),o=r?parseInt(r,10):void 0;return new U(e,o)}default:return new k(e,{code:n?.error??"HTTP_ERROR",statusCode:s.status,requestId:t,details:n?.details})}}function Ce(s,n,e){return s instanceof x?e:s instanceof U?n.includes(429):s instanceof k&&s.statusCode?n.includes(s.statusCode):false}function ve(s,n,e,t,r){if(r!==void 0&&r>0)return Math.min(r*1e3,e);let o=n*Math.pow(t,s),a=Math.min(o,e),l=a*Math.random()*.25;return a+l}function Ae(s){return new Promise(n=>setTimeout(n,s))}async function Te(s,n){let{timeout:e=3e4,fetchFn:t,...r}=n,o=new AbortController,a=setTimeout(()=>o.abort(),e);try{let l=await t(s,{...r,signal:o.signal});if(clearTimeout(a),!l.ok)throw await Se(l);if(l.status===204)return;let i=await l.text();return i?JSON.parse(i):void 0}catch(l){throw clearTimeout(a),l instanceof k?l:l instanceof Error&&l.name==="AbortError"?new x("Request timed out"):l instanceof Error?new x(l.message,l):new x("Network request failed")}}function p(s){let{baseUrl:n,apiKey:e,apiKeyHeader:t,accessToken:r,fetch:o,timeout:a,retry:l,interceptors:i}=s;return async function(g,y={}){let h=`${n}${g}`,S=y.method||"GET",P={"Content-Type":"application/json",...y.headers??{}};if(e&&(P[t]=e),r){let O=typeof r=="function"?await r():r;P.Authorization=`Bearer ${O}`;}let A=y.timeout??a,f=l.maxRetries,T=null;for(let O=0;O<=f;O++){let C=Date.now(),d={url:h,path:g,method:S,headers:{...P},body:y.body,attempt:O};try{if(i.onRequest){let u=await i.onRequest(d);u&&(d=u);}let b=await Te(d.url,{...y,method:d.method,headers:d.headers,body:d.body,timeout:A,fetchFn:o}),R=Date.now()-C;if(i.onResponse){let u={request:d,data:b,status:200,headers:{},durationMs:R};await i.onResponse(u);}return b}catch(b){let R=Date.now()-C;T=b;let u=O<f&&Ce(b,l.retryOn,l.retryOnNetworkError);if(i.onError){let m={request:d,error:b,durationMs:R,willRetry:u};await i.onError(m);}if(u){let m=b instanceof U?b.retryAfter:void 0,I=ve(O,l.retryDelay,l.maxRetryDelay,l.backoffMultiplier,m);await Ae(I);continue}throw b}}throw T||new x("Request failed after retries")}}function v(s){let n=new URLSearchParams;for(let[t,r]of Object.entries(s))r!==void 0&&n.set(t,String(r));let e=n.toString();return e?`?${e}`:""}function Re(s){return JSON.stringify(s)}function q(s,n,e={}){let t={...e},r=()=>{let i={};if(t.limit!==void 0&&(i.limit=t.limit),t.offset!==void 0&&(i.offset=t.offset),t.where&&(i.where=Re(t.where)),t.orderBy){let c=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];i.orderBy=JSON.stringify(c);}return t.select&&t.select.length>0&&(i.select=t.select.join(",")),t.include&&t.include.length>0&&(i.include=JSON.stringify(t.include)),t.distinct&&t.distinct.length>0&&(i.distinct=t.distinct.join(",")),i},o=()=>v(r()),a=i=>q(s,n,{...t,...i}),l={async list(i){i&&(t={...t,...i});let c=o();return n(`/generated/${s}${c}`)},async get(i){let c={};t.select&&t.select.length>0&&(c.select=t.select.join(",")),t.include&&t.include.length>0&&(c.include=JSON.stringify(t.include));let g=v(c);return n(`/generated/${s}/${encodeURIComponent(i)}${g}`)},async first(){let i=await l.limit(1).list();return i.data.length>0?i.data[0]:null},async firstOrFail(){let i=await l.first();if(!i)throw new $(`No record found in table '${s}' matching the query`);return i},async create(i){return n(`/generated/${s}`,{method:"POST",body:JSON.stringify(i)})},async update(i,c){return n(`/generated/${s}/${encodeURIComponent(i)}`,{method:"PATCH",body:JSON.stringify(c)})},async delete(i){return n(`/generated/${s}/${encodeURIComponent(i)}`,{method:"DELETE"})},async createMany(i,c){return n(`/generated/${s}/batch`,{method:"POST",body:JSON.stringify({records:i,skipOnConflict:c?.skipOnConflict,returnRecords:c?.returnRecords})})},async updateMany(i,c){return n(`/generated/${s}/batch`,{method:"PATCH",body:JSON.stringify({data:i,where:t.where,returnRecords:c?.returnRecords})})},async deleteMany(){return n(`/generated/${s}/batch`,{method:"DELETE",body:JSON.stringify({where:t.where})})},async upsert(i,c){return n(`/generated/${s}/upsert`,{method:"POST",body:JSON.stringify({data:i,conflictFields:c.conflictFields,updateFields:c.updateFields})})},async count(){let i=r(),c=v(i);return (await n(`/generated/${s}/count${c}`)).count},async sum(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/sum${g}`)).sum},async avg(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/avg${g}`)).avg},async min(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/min${g}`)).min},async max(i){let c=r(),g=v({...c,field:i});return (await n(`/generated/${s}/max${g}`)).max},async aggregate(i,c){return n(`/generated/${s}/aggregate`,{method:"POST",body:JSON.stringify({aggregates:i,where:c?.where||t.where,groupBy:c?.groupBy,having:c?.having})})},async paginate(i){let c=i.page||1,g=i.pageSize||20,y=(c-1)*g,h=r();h.limit=g,h.offset=y,h.includeCount=true;let S=v(h),P=await n(`/generated/${s}${S}`),A=P.total||P.data.length,f=Math.ceil(A/g);return {data:P.data,pageInfo:{total:A,page:c,pageSize:g,pageCount:f,hasNextPage:c<f,hasPrevPage:c>1}}},async cursorPaginate(i){let c=r();c.limit=i.limit||20,i.cursor&&(c.cursor=i.cursor);let g=v(c),y=await n(`/generated/${s}/cursor${g}`);return {data:y.data,nextCursor:y.nextCursor,prevCursor:y.prevCursor,hasMore:y.hasMore}},where(i){if(t.where){let c=t.where;return a({where:{AND:[...Array.isArray(c)?c:[c],i]}})}return a({where:i})},orderBy(i,c="asc"){let g={field:i,direction:c};if(t.orderBy){let y=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];return a({orderBy:[...y,g]})}return a({orderBy:g})},select(...i){return a({select:i})},limit(i){return a({limit:i})},offset(i){return a({offset:i})},include(i){let c=t.include||[];return a({include:[...c,i]})},distinct(...i){return a({distinct:i})}};return l}function W(s){let n=p(s);return {from(e){return q(e,n)},async raw(e,t){return n("/generated/raw",{method:"POST",body:JSON.stringify({query:e,params:t})})},async transaction(e,t){return n("/generated/transaction",{method:"POST",body:JSON.stringify({operations:e,isolationLevel:t?.isolationLevel,timeout:t?.timeout})})},async withTransaction(e,t){let o=(await n("/generated/transaction/start",{method:"POST",body:JSON.stringify({isolationLevel:t?.isolationLevel,timeout:t?.timeout})})).transactionId,a=(i,c)=>{let g=new Headers(c?.headers);return g.set("X-Transaction-Id",o),n(i,{...c,headers:g})},l={from(i){return q(i,a)},async raw(i,c){return a("/generated/raw",{method:"POST",body:JSON.stringify({query:i,params:c})})},async transaction(){throw new k("Nested transactions are not supported",{code:"NESTED_TRANSACTION"})},async withTransaction(){throw new k("Nested transactions are not supported",{code:"NESTED_TRANSACTION"})}};try{let i=await e(l);return await n("/generated/transaction/commit",{method:"POST",body:JSON.stringify({transactionId:o})}),i}catch(i){throw await n("/generated/transaction/rollback",{method:"POST",body:JSON.stringify({transactionId:o})}).catch(()=>{}),i}}}}function _(s){let n=p(s);return {async signUp(e,t,r){return n("/auth/signup",{method:"POST",body:JSON.stringify({email:e,password:t,name:r?.name,phone:r?.phone,metadata:r?.metadata,redirectUrl:r?.redirectUrl})})},async login(e,t,r){return n("/auth/login",{method:"POST",body:JSON.stringify({email:e,password:t,mfaCode:r?.mfaCode,rememberMe:r?.rememberMe})})},async logout(){await n("/auth/logout",{method:"POST"});},async logoutAll(){await n("/auth/logout-all",{method:"POST"});},async getUser(){return (await n("/auth/me")).user},async updateProfile(e){return (await n("/users/me",{method:"PATCH",body:JSON.stringify(e)})).user},async changePassword(e){return n("/users/me/change-password",{method:"POST",body:JSON.stringify(e)})},async requestPasswordReset(e){return n("/auth/forgot-password",{method:"POST",body:JSON.stringify(e)})},async confirmPasswordReset(e){return n("/auth/reset-password",{method:"POST",body:JSON.stringify(e)})},async requestEmailVerification(e){return n("/auth/verify-email/send",{method:"POST",body:JSON.stringify(e||{})})},async confirmEmailVerification(e){return n("/auth/verify-email/confirm",{method:"POST",body:JSON.stringify(e)})},async getOAuthSignInUrl(e){return n("/auth/oauth/authorize",{method:"POST",body:JSON.stringify(e)})},async handleOAuthCallback(e){return n("/auth/oauth/callback",{method:"POST",body:JSON.stringify(e)})},async linkOAuthProvider(e){return n("/auth/oauth/link",{method:"POST",body:JSON.stringify(e)})},async unlinkOAuthProvider(e){return n(`/auth/oauth/unlink/${e}`,{method:"POST"})},async listLinkedProviders(){return n("/auth/oauth/providers")},async requestMagicLink(e){return n("/auth/magic-link/send",{method:"POST",body:JSON.stringify(e)})},async verifyMagicLink(e){return n("/auth/magic-link/verify",{method:"POST",body:JSON.stringify(e)})},async requestPhoneVerification(e){return n("/auth/phone/send",{method:"POST",body:JSON.stringify(e)})},async confirmPhoneVerification(e){return n("/auth/phone/verify",{method:"POST",body:JSON.stringify(e)})},async setupMFA(e){return n("/auth/mfa/setup",{method:"POST",body:JSON.stringify({method:e})})},async enableMFA(e){return n("/auth/mfa/enable",{method:"POST",body:JSON.stringify({code:e})})},async disableMFA(e){return n("/auth/mfa/disable",{method:"POST",body:JSON.stringify({code:e})})},async verifyMFA(e,t){return n("/auth/mfa/verify",{method:"POST",body:JSON.stringify({mfaToken:e,code:t})})},async regenerateBackupCodes(){return n("/auth/mfa/backup-codes",{method:"POST"})},async refreshToken(e){return n("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})})},async listSessions(){return n("/auth/sessions")},async revokeSession(e){return n(`/auth/sessions/${e}`,{method:"DELETE"})},async revokeOtherSessions(){return n("/auth/sessions/revoke-others",{method:"POST"})}}}function K(s){return new Promise(n=>setTimeout(n,s))}function H(s){let n=p(s);async function e(t,r,o){let a=o?.retry||{},l=a.maxRetries??0,i=a.initialDelay??1e3,c=a.maxDelay??3e4,g=a.backoffMultiplier??2,y=a.retryOnStatus??[429,500,502,503,504],h=a.retryOnNetworkError??true,S=null,P=i;for(let A=0;A<=l;A++)try{let f={};o?.version!==void 0&&(f.version=o.version),o?.includeLogs&&(f.includeLogs=!0);let T=v(f),O=await n(`/functions/${t}/invoke${T}`,{method:"POST",body:JSON.stringify(r??{}),headers:o?.headers});if(y.includes(O.status)&&A<l){S=new Error(`Function returned status ${O.status}`),await K(P),P=Math.min(P*g,c);continue}return O}catch(f){S=f;let T=f instanceof TypeError||f.message?.includes("network")||f.message?.includes("fetch");if(h&&T&&A<l){await K(P),P=Math.min(P*g,c);continue}throw f}throw S||new Error("Function invocation failed after retries")}return {invoke:e,async invokeByName(t,r,o){let a={};o?.version!==void 0&&(a.version=o.version),o?.includeLogs&&(a.includeLogs=true);let l=v(a);return n(`/functions/name/${encodeURIComponent(t)}/invoke${l}`,{method:"POST",body:JSON.stringify(r??{}),headers:o?.headers})},async batchInvoke(t,r){let a=(await Promise.allSettled(t.map(l=>this.invoke(l.functionId,l.input,r)))).map((l,i)=>l.status==="fulfilled"?{functionId:t[i].functionId,success:true,result:l.value}:{functionId:t[i].functionId,success:false,error:l.reason?.message||"Unknown error"});return {results:a,successCount:a.filter(l=>l.success).length,errorCount:a.filter(l=>!l.success).length}},rpc(t,r){let o=this,a=async(l,i)=>{let c={...r,...i};return (await e(t,{body:l},c)).data};return Object.defineProperty(a,"id",{value:t,writable:false}),a.getInfo=()=>o.get(t),a.getInvocations=l=>o.getInvocations({...l,functionId:t}),a},async list(t){let r={envId:t.envId,enabled:t.enabled,limit:t.limit,offset:t.offset},o=v(r);return n(`/functions/project/${t.projectId}${o}`)},async get(t){return n(`/functions/${t}`)},async getByName(t,r){return n(`/functions/project/${r}/name/${encodeURIComponent(t)}`)},async create(t){return n("/functions",{method:"POST",body:JSON.stringify(t)})},async update(t,r){return n(`/functions/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(t){return n(`/functions/${t}`,{method:"DELETE"})},async enable(t){return this.update(t,{enabled:true})},async disable(t){return this.update(t,{enabled:false})},async deploy(t,r,o){return n(`/functions/${t}/source`,{method:"PUT",body:JSON.stringify({sourceCode:r})})},async getSource(t,r){return {sourceCode:(await n(`/functions/${t}`)).sourceCode||"",version:1}},async listVersions(t){return (await n(`/functions/${t}/versions`)).versions},async rollback(t,r){return n(`/functions/${t}/rollback`,{method:"POST",body:JSON.stringify({version:r})})},async getEnvVars(t){return (await n(`/functions/${t}/env`)).envVars},async setEnvVars(t,r){return n(`/functions/${t}/env`,{method:"PUT",body:JSON.stringify({envVars:r})})},async deleteEnvVar(t,r){return n(`/functions/${t}/env/${encodeURIComponent(r)}`,{method:"DELETE"})},async bindSecrets(t,r){return n(`/functions/${t}/secrets`,{method:"PUT",body:JSON.stringify({secrets:r})})},async setSchedule(t,r){return n(`/functions/${t}/schedule`,{method:"PUT",body:JSON.stringify(r)})},async removeSchedule(t){return n(`/functions/${t}/schedule`,{method:"DELETE"})},async getInvocations(t){let r={functionId:t.functionId,projectId:t.projectId,status:t.status,since:t.since,until:t.until,limit:t.limit,offset:t.offset},o=v(r);return (await n(`/functions/invocations${o}`)).invocations},async getInvocation(t){return n(`/functions/invocations/${t}`)},async getLogs(t,r){let o={since:r?.since,until:r?.until,level:r?.level,limit:r?.limit},a=v(o);return (await n(`/functions/${t}/logs${a}`)).logs}}}function G(s){let n=p(s),e="default";return {async getUploadUrl(t,r){return n("/storage/upload-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,sizeBytes:r?.sizeBytes,metadata:r?.metadata,isPublic:r?.isPublic,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,upsert:r?.upsert})})},async getDownloadUrl(t,r){return n("/storage/download-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,expiresIn:r?.expiresIn,download:r?.download,transform:r?.transform})})},async createSignedUrl(t,r=3600,o){return (await this.getDownloadUrl(t,{...o,expiresIn:r})).url},async createSignedUrls(t,r=3600,o){return await Promise.all(t.map(async l=>({key:l,url:await this.createSignedUrl(l,r,o)})))},async upload(t,r,o){let a=r instanceof Blob?r:new Blob([r]),l=a.size,i=o?.contentType||(r instanceof File?r.type:void 0)||"application/octet-stream",c=await this.getUploadUrl(t,{...o,contentType:i,sizeBytes:l}),g=await s.fetch(c.url,{method:"PUT",body:a,headers:{"Content-Type":i,...o?.cacheControl&&{"Cache-Control":o.cacheControl},...o?.contentDisposition&&{"Content-Disposition":o.contentDisposition}}});if(!g.ok)throw new k(`Upload failed: ${g.statusText}`,{code:"UPLOAD_ERROR",statusCode:g.status});let y=o?.bucket||e,h=c.url.split("?")[0];return {ok:true,key:t,bucket:y,url:h,publicUrl:o?.isPublic?this.getPublicUrl(t,{bucket:y}):void 0,size:l,contentType:i}},async uploadFromUrl(t,r,o){return n("/storage/upload-from-url",{method:"POST",body:JSON.stringify({key:t,url:r,bucket:o?.bucket||e,contentType:o?.contentType,metadata:o?.metadata,isPublic:o?.isPublic,timeout:o?.timeout})})},async download(t,r){let o=await this.getDownloadUrl(t,r),a=await s.fetch(o.url);if(!a.ok)throw new k(`Download failed: ${a.statusText}`,{code:"DOWNLOAD_ERROR",statusCode:a.status});return a.blob()},async list(t){let r={bucket:t?.bucket||e,prefix:t?.prefix,delimiter:t?.delimiter,limit:t?.limit,cursor:t?.cursor,includeUrls:t?.includeUrls},o=v(r);return n(`/storage/files${o}`)},async getMetadata(t,r){let o=r?.bucket||e;return n(`/storage/files/${encodeURIComponent(o)}/${encodeURIComponent(t)}/metadata`)},async updateMetadata(t,r,o){let a=o?.bucket||e;return n(`/storage/files/${encodeURIComponent(a)}/${encodeURIComponent(t)}/metadata`,{method:"PATCH",body:JSON.stringify(r)})},async exists(t,r){try{return await this.getMetadata(t,r),!0}catch{return false}},async copy(t,r,o){return n("/storage/files/copy",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:o?.sourceBucket||e,destinationKey:r,destinationBucket:o?.destinationBucket||o?.sourceBucket||e,metadata:o?.metadata})})},async move(t,r,o){return n("/storage/files/move",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:o?.sourceBucket||e,destinationKey:r,destinationBucket:o?.destinationBucket||o?.sourceBucket||e,metadata:o?.metadata})})},async delete(t,r){let o=r?.bucket||e;await n(`/storage/files/${encodeURIComponent(o)}/${encodeURIComponent(t)}`,{method:"DELETE"});},async deleteMany(t,r){return n("/storage/files/delete-batch",{method:"POST",body:JSON.stringify({keys:t,bucket:r?.bucket||e})})},getPublicUrl(t,r){let o=r?.bucket||e;return `${s.baseUrl.replace("/api","")}/storage/${encodeURIComponent(o)}/${encodeURIComponent(t)}`},async createBucket(t,r){return n("/storage/buckets",{method:"POST",body:JSON.stringify({name:t,isPublic:r?.isPublic,allowedMimeTypes:r?.allowedMimeTypes,maxFileSize:r?.maxFileSize,fileSizeLimit:r?.fileSizeLimit})})},async getBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}`)},async updateBucket(t,r){return n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})},async listBuckets(){return (await n("/storage/buckets")).buckets},async deleteBucket(t){await n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"DELETE"});},async emptyBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}/empty`,{method:"POST"})},async createMultipartUpload(t,r){return n("/storage/multipart/create",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,metadata:r?.metadata,partSize:r?.partSize})})},async uploadPart(t,r,o){let a=o instanceof Blob?o:new Blob([o]),{url:l}=await n(`/storage/multipart/${t}/part-url`,{method:"POST",body:JSON.stringify({partNumber:r})}),i=await s.fetch(l,{method:"PUT",body:a});if(!i.ok)throw new k(`Part upload failed: ${i.statusText}`,{code:"UPLOAD_PART_ERROR",statusCode:i.status});let c=i.headers.get("etag")||"";return {partNumber:r,etag:c}},async completeMultipartUpload(t,r){return n(`/storage/multipart/${t}/complete`,{method:"POST",body:JSON.stringify({parts:r})})},async abortMultipartUpload(t){await n(`/storage/multipart/${t}/abort`,{method:"POST"});}}}function z(s){let n=p(s);return {async list(e){let t=new URLSearchParams;e?.orgId&&t.set("orgId",e.orgId);let r=t.toString();return n(`/projects${r?`?${r}`:""}`)},async get(e){return n(`/projects/${e}`)},async create(e){return n("/projects",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async delete(e){return n(`/projects/${e}`,{method:"DELETE"})},async getComputeSettings(e){return n(`/projects/${e}/settings/compute`)},async updateComputeSettings(e,t){return n(`/projects/${e}/settings/compute`,{method:"PATCH",body:JSON.stringify(t)})},async getApiSettings(e){return n(`/projects/${e}/settings/api`)},async updateApiSettings(e,t){return n(`/projects/${e}/settings/api`,{method:"PATCH",body:JSON.stringify(t)})},async getJwtSettings(e){return n(`/projects/${e}/settings/jwt`)},async updateJwtSettings(e,t){return n(`/projects/${e}/settings/jwt`,{method:"PATCH",body:JSON.stringify(t)})},async rotateJwtSecret(e){return n(`/projects/${e}/settings/jwt/rotate`,{method:"POST"})},async getAddons(e){return n(`/projects/${e}/settings/addons`)},async updateAddons(e,t){return n(`/projects/${e}/settings/addons`,{method:"PATCH",body:JSON.stringify({enabledAddons:t})})},async getApiKeys(e){return n(`/projects/${e}/api-keys`)},async createApiKey(e,t){return n(`/projects/${e}/api-keys`,{method:"POST",body:JSON.stringify(t??{})})},async revokeApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/revoke`,{method:"POST"})},async rotateApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/rotate`,{method:"POST"})},async setCustomDomain(e,t,r){return n(`/projects/${e}/environments/${t}`,{method:"PATCH",body:JSON.stringify({customDomain:r})})},async getDomainVerificationInstructions(e,t){return n(`/projects/${e}/environments/${t}/domain-verification`)},async verifyDomainTxt(e,t){return n(`/projects/${e}/environments/${t}/verify-domain`,{method:"POST"})},async verifyDomainCname(e,t){return n(`/projects/${e}/environments/${t}/verify-cname`,{method:"POST"})},async getDomainStatus(e,t){return n(`/projects/${e}/environments/${t}/domain-status`)},async provisionSsl(e,t){return n(`/projects/${e}/environments/${t}/provision-ssl`,{method:"POST"})},async removeCustomDomain(e,t){return n(`/projects/${e}/environments/${t}`,{method:"PATCH",body:JSON.stringify({customDomain:null})})},async listApiKeys(e){return (await n(`/projects/${e}/api-keys`)).keys}}}function Q(s){let n=p(s);return {async list(){return n("/orgs")},async create(e){return n("/orgs",{method:"POST",body:JSON.stringify(e)})},async getProfile(e){return (await n(`/orgs/${e}/profile`)).profile||{}},async updateProfile(e,t){return (await n(`/orgs/${e}/profile`,{method:"PATCH",body:JSON.stringify(t)})).profile},async listBillingContacts(e){return (await n(`/orgs/${e}/billing-contacts`)).contacts},async addBillingContact(e,t){return n(`/orgs/${e}/billing-contacts`,{method:"POST",body:JSON.stringify(t)})},async removeBillingContact(e,t){return n(`/orgs/${e}/billing-contacts/${t}`,{method:"DELETE"})},async listMembers(e){return (await n(`/orgs/${e}/members`)).members},async inviteMember(e,t){return n(`/orgs/${e}/members/invite`,{method:"POST",body:JSON.stringify(t)})},async listInvites(e){return (await n(`/orgs/${e}/invites`)).invites},async cancelInvite(e,t){return n(`/orgs/${e}/invites/${t}`,{method:"DELETE"})},async removeMember(e,t){return n(`/orgs/${e}/members/${t}`,{method:"DELETE"})},async updateMemberRole(e,t,r){return n(`/orgs/${e}/members/${t}/role`,{method:"PATCH",body:JSON.stringify({role:r})})},async getMyMembership(e){try{return (await n(`/orgs/${e}/membership`)).membership}catch{return null}}}}function X(s){let n=p(s);return {async preview(e){return n("/schema-engine/preview",{method:"POST",body:JSON.stringify(e)})},async apply(e){return n("/schema-engine/apply",{method:"POST",body:JSON.stringify(e)})},async getMigrations(e,t){let r=t?`/schema-engine/migrations/project/${e}?limit=${t}`:`/schema-engine/migrations/project/${e}`;return n(r)},async saveSchema(e){return n("/schemas/",{method:"POST",body:JSON.stringify(e)})},async getSchemas(e){return n(`/schemas/project/${e}`)}}}function Y(s){let n=p(s);return {async create(e){return n("/functions/secrets",{method:"POST",body:JSON.stringify(e)})},async list(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/functions/secrets/project/${e}${o?`?${o}`:""}`;return n(a)},async reveal(e){return n(`/functions/secrets/${e}/value`)},async update(e,t){return n(`/functions/secrets/${e}`,{method:"PUT",body:JSON.stringify({value:t})})},async delete(e){return n(`/functions/secrets/${e}`,{method:"DELETE"})}}}function Z(s){let n=p(s);return {async list(e,t){let r=new URLSearchParams;t&&r.set("env",t);let o=r.toString(),a=`/deployments/project/${e}${o?`?${o}`:""}`;return (await n(a)).deployments},async get(e){let t=await n(`/deployments/${e}`);return {...t.deployment,steps:t.steps}},async getSteps(e){return (await n(`/deployments/${e}/steps`)).steps},async promote(e){let t={projectId:e.projectId,fromEnv:e.sourceEnv,toEnv:e.targetEnv},r=await n("/deployments/promote",{method:"POST",body:JSON.stringify(t)}),o=await n(`/deployments/${r.deploymentId}`);return {deployment:{...o.deployment,steps:o.steps}}},async rollback(e){return n(`/deployments/${e}/rollback`,{method:"POST"})},async listTokens(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/deployments/tokens/project/${encodeURIComponent(e)}${o?`?${o}`:""}`;return (await n(a)).tokens},async createToken(e){return n("/deployments/tokens",{method:"POST",body:JSON.stringify(e)})},async revokeToken(e){return n(`/deployments/tokens/${encodeURIComponent(e)}/revoke`,{method:"POST"})}}}function ee(s){let n=p(s);return {async getStats(e){return n(`/realtime/stats/project/${e}`)},async getConnections(e){return (await n(`/realtime/connections/project/${e}`)).connections},async getSubscriptions(e){return (await n(`/realtime/subscriptions/project/${e}`)).subscriptions},async getEvents(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.source&&t.source!=="all"&&r.set("source",t.source),t?.level&&t.level!=="all"&&r.set("level",t.level);let o=r.toString(),a=`/realtime/events/project/${e}${o?`?${o}`:""}`;return (await n(a)).events},async getStatus(e){return n(`/realtime/status/project/${e}`)},async install(e){return n("/realtime/install",{method:"POST",body:JSON.stringify(e)})},async enableAll(e){return n("/realtime/enable-all",{method:"POST",body:JSON.stringify(e)})}}}function te(s){let n=p(s);return {async listBuckets(e,t){let r=new URLSearchParams;r.set("projectId",e),t&&r.set("envId",t);let a=`/storage/buckets?${r.toString()}`;return (await n(a)).buckets},async getBucket(e){return (await n(`/buckets/${e}`)).bucket},async createBucket(e){return (await n("/buckets",{method:"POST",body:JSON.stringify(e)})).bucket},async updateBucket(e,t){return (await n(`/buckets/${e}`,{method:"PUT",body:JSON.stringify(t)})).bucket},async deleteBucket(e){return n(`/buckets/${e}`,{method:"DELETE"})},async listFiles(e,t){let r=new URLSearchParams;t?.prefix&&r.set("prefix",t.prefix),t?.maxKeys&&r.set("maxKeys",String(t.maxKeys)),t?.continuationToken&&r.set("continuationToken",t.continuationToken);let o=r.toString(),a=`/buckets/${e}/files${o?`?${o}`:""}`;return n(a)},async deleteFile(e,t){return n(`/buckets/${e}/files?key=${encodeURIComponent(t)}`,{method:"DELETE"})},async getSignedUrl(e,t,r){return n(`/buckets/${e}/signed-url`,{method:"POST",body:JSON.stringify({key:t,expiresIn:r})})},async getUploadUrl(e,t,r){return n(`/buckets/${e}/upload-url`,{method:"POST",body:JSON.stringify({key:t,...r})})},async uploadFile(e,t,r,o){let a=o?.prefix?`${o.prefix}${t}`:t,l=o?.contentType??(r instanceof Blob?r.type:"application/octet-stream"),i=new URLSearchParams;return i.set("key",a),l&&i.set("contentType",l),n(`/buckets/${e}/upload?${i.toString()}`,{method:"POST",body:r,headers:{"Content-Type":l||"application/octet-stream"}})}}}function ne(s){let n=p(s);return {async list(e,t){let r={type:t?.type,enabled:t?.enabled},o=v(r);return (await n(`/integrations/subscriptions/project/${e}${o}`)).subscriptions},async get(e){return n(`/integrations/subscriptions/${e}`)},async create(e){return (await n("/integrations/subscriptions",{method:"POST",body:JSON.stringify(e)})).subscription},async update(e,t){return (await n(`/integrations/subscriptions/${e}`,{method:"PATCH",body:JSON.stringify(t)})).subscription},async delete(e){return n(`/integrations/subscriptions/${e}`,{method:"DELETE"})},async enable(e){return this.update(e,{enabled:true})},async disable(e){return this.update(e,{enabled:false})},async test(e){return n(`/integrations/subscriptions/${e}/test`,{method:"POST"})},async publish(e){return n("/integrations/events/publish",{method:"POST",body:JSON.stringify(e)})},async publishBatch(e){return (await n("/integrations/events/publish-batch",{method:"POST",body:JSON.stringify({events:e})})).results},async listEvents(e){let t={envId:e.envId,source:e.source,name:e.name,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/events/project/${e.projectId}${r}`)).events},async getEvent(e){return n(`/integrations/events/${e}`)},async getDeliveries(e){let t={subscriptionId:e.subscriptionId,eventId:e.eventId,status:e.status,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/deliveries${r}`)).deliveries},async getDelivery(e){return n(`/integrations/deliveries/${e}`)},async retryDelivery(e){return n(`/integrations/deliveries/${e}/retry`,{method:"POST"})},async retryAllFailed(e){return n(`/integrations/subscriptions/${e}/retry-failed`,{method:"POST"})},async getDlq(e,t){let r={limit:t?.limit,offset:t?.offset},o=v(r);return (await n(`/integrations/dlq/project/${e}${o}`)).deliveries},async purgeDlq(e,t){return n(`/integrations/dlq/project/${e}/purge`,{method:"POST",body:JSON.stringify({olderThan:t.olderThan})})},async replayDlq(e,t){return n(`/integrations/dlq/project/${e}/replay`,{method:"POST",body:JSON.stringify(t)})},verifySignature(e){let t=e.tolerance??300;try{let r=e.signature.split(","),o=r.find(f=>f.startsWith("t=")),a=r.find(f=>f.startsWith("v1="));if(!o||!a)return !1;let l=parseInt(o.slice(2),10),i=a.slice(3),c=Math.floor(Date.now()/1e3);if(Math.abs(c-l)>t)return !1;let g=`${l}.${e.payload}`,y=new TextEncoder,h=y.encode(e.secret),S=y.encode(g),P=Array.from(h).concat(Array.from(S)).reduce((f,T)=>f+T,0).toString(16);if(i.length!==P.length)return !1;let A=0;for(let f=0;f<i.length;f++)A|=i.charCodeAt(f)^P.charCodeAt(f);return A===0}catch{return false}},generateSecret(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="whsec_";for(let r=0;r<32;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}}}function re(s){let n=p(s);return {async getSummary(e){return n(`/billing/org/${e}/summary`)},async getEntitlements(e){return n(`/entitlements/org/${e}`)},async checkEntitlement(e,t){return n(`/entitlements/org/${e}/check`,{method:"POST",body:JSON.stringify(t)})},async getPlans(){return (await n("/pricing/plans")).plans},async createCheckout(e){return n("/billing/checkout",{method:"POST",body:JSON.stringify(e)})},async verifyCheckoutSession(e){return n(`/billing/checkout/verify/${e}`)},async openPortal(e){return n(`/billing/org/${e.orgId}/portal`,{method:"POST",body:JSON.stringify({returnUrl:e.returnUrl})})},async getAIUsageSummary(e){return n(`/ai-usage/org/${e}/summary`)},async getAIUsageHistory(e,t=30){return n(`/ai-usage/org/${e}/history?days=${t}`)},async getAIUsageBreakdown(e){return n(`/ai-usage/org/${e}/breakdown`)},async getRecentAIRequests(e,t=50,r=0){return n(`/ai-usage/org/${e}/recent?limit=${t}&offset=${r}`)}}}function oe(s){let n=p(s);return {async getOverview(){return n("/admin/overview")},async listUsers(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/users${r?`?${r}`:""}`)},async getUser(e){return n(`/admin/users/${e}`)},async updateUserStatus(e,t){return n(`/admin/users/${e}/status`,{method:"PATCH",body:JSON.stringify({status:t})})},async updateUserAdmin(e,t){return n(`/admin/users/${e}/admin`,{method:"PATCH",body:JSON.stringify({isAdmin:t})})},async listOrganizations(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.plan&&t.set("plan",e.plan),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/organizations${r?`?${r}`:""}`)},async getOrganization(e){return n(`/admin/organizations/${e}`)},async updateOrganization(e,t){return n(`/admin/organizations/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async listProjects(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.orgId&&t.set("orgId",e.orgId),e?.region&&t.set("region",e.region),e?.tenancy&&t.set("tenancy",e.tenancy),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/projects${r?`?${r}`:""}`)},async getProject(e){return n(`/admin/projects/${e}`)},async updateProject(e,t){return n(`/admin/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getProjectResources(e){return n(`/admin/resources/project/${e}`)},async setDedicatedDb(e){return n(`/admin/resources/project/${e.projectId}/db`,{method:"POST",body:JSON.stringify({connectionString:e.connectionString})})},async listIncidents(e="open"){return (await n(`/admin/incidents?status=${e}`)).incidents},async createIncident(e){return n("/admin/incidents",{method:"POST",body:JSON.stringify(e)})},async acknowledgeIncident(e){return n(`/admin/incidents/${e}/ack`,{method:"POST"})},async resolveIncident(e){return n(`/admin/incidents/${e}/resolve`,{method:"POST"})},async listRegions(){return n("/admin/regions")},async updateRegion(e,t){return n(`/admin/regions/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getHealthComponents(){return n("/admin/health/components")},async updateHealthComponent(e,t){return n(`/admin/health/components/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getSystemInfo(){return n("/admin/system/info")},async listQueues(){return n("/admin/queues")},async listDlqMessages(e){let t=new URLSearchParams;e?.queue&&t.set("queue",e.queue),e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/dlq${r?`?${r}`:""}`)},async retryDlqMessage(e){return n(`/admin/dlq/${e}/retry`,{method:"POST"})},async archiveDlqMessage(e){return n(`/admin/dlq/${e}`,{method:"DELETE"})},async listFeatureFlags(){return (await n("/flags")).flags},async createFeatureFlag(e,t){return n("/flags",{method:"POST",body:JSON.stringify({key:e,enabled:t})})},async updateFeatureFlag(e,t){return n(`/flags/${e}`,{method:"PUT",body:JSON.stringify({enabled:t})})},async deleteFeatureFlag(e){return n(`/flags/${e}`,{method:"DELETE"})},async listAdmins(){return (await n("/admin/admins")).admins||[]},async addAdmin(e,t,r){return n("/admin/admins",{method:"POST",body:JSON.stringify({userId:e,role:t,notes:r})})},async updateAdmin(e,t){return n(`/admin/admins/${e}`,{method:"PUT",body:JSON.stringify(t)})},async removeAdmin(e){return n(`/admin/admins/${e}`,{method:"DELETE"})},async getSettings(e){let t=e?`?category=${e}`:"";return n(`/admin/settings${t}`)},async updateSetting(e,t){return n(`/admin/settings/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({value:t})})},async listAIModels(){return n("/admin/ai/models")},async getAIModel(e){return n(`/admin/ai/models/${e}`)},async createAIModel(e){return n("/admin/ai/models",{method:"POST",body:JSON.stringify(e)})},async updateAIModel(e,t){return n(`/admin/ai/models/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteAIModel(e){return n(`/admin/ai/models/${e}`,{method:"DELETE"})},async toggleAIModel(e,t,r){return n(`/admin/ai/models/${e}/toggle`,{method:"POST",body:JSON.stringify({enabled:t,disabledMessage:r})})},async listAISessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/workspace/sessions${r?`?${r}`:""}`)},async getAISession(e){return n(`/admin/ai/workspace/sessions/${e}`)},async deleteAISession(e){return n(`/admin/ai/workspace/sessions/${e}`,{method:"DELETE"})},async listGeneratedBackends(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/backends${r?`?${r}`:""}`)},async getGeneratedBackend(e){return n(`/admin/ai/backends/${e}`)},async deleteGeneratedBackend(e){return n(`/admin/ai/backends/${e}`,{method:"DELETE"})},async listPromptTemplates(e){let t=new URLSearchParams;e?.category&&t.set("category",e.category),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/prompt-templates${r?`?${r}`:""}`)},async createPromptTemplate(e){return n("/admin/ai/prompt-templates",{method:"POST",body:JSON.stringify(e)})},async updatePromptTemplate(e,t){return n(`/admin/ai/prompt-templates/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deletePromptTemplate(e){return n(`/admin/ai/prompt-templates/${e}`,{method:"DELETE"})},async listContextSnapshots(e){let t=new URLSearchParams;e?.projectId&&t.set("projectId",e.projectId),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai/context-snapshots${r?`?${r}`:""}`)},async invalidateContextSnapshot(e){return n(`/admin/ai/context-snapshots/${e}/invalidate`,{method:"POST"})},async deleteContextSnapshot(e){return n(`/admin/ai/context-snapshots/${e}`,{method:"DELETE"})},async getCopilotOverview(){return n("/admin/copilot/overview")},async listCopilotSessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/sessions${r?`?${r}`:""}`)},async getCopilotSession(e){return n(`/admin/copilot/sessions/${e}`)},async deleteCopilotSession(e){return n(`/admin/copilot/sessions/${e}`,{method:"DELETE"})},async listCopilotMemories(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.projectId&&t.set("projectId",e.projectId),e?.memoryType&&t.set("memoryType",e.memoryType),e?.importance&&t.set("importance",e.importance),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/memories${r?`?${r}`:""}`)},async getCopilotMemoryStats(){return n("/admin/copilot/memories/stats")},async getCopilotMemory(e){return n(`/admin/copilot/memories/${e}`)},async updateCopilotMemory(e,t){return n(`/admin/copilot/memories/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteCopilotMemory(e){return n(`/admin/copilot/memories/${e}`,{method:"DELETE"})},async cleanupExpiredMemories(){return n("/admin/copilot/memories/cleanup",{method:"POST"})},async listClassificationFeedback(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.feedbackType&&t.set("feedbackType",e.feedbackType),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/copilot/classification-feedback${r?`?${r}`:""}`)},async exportTrainingData(e){let t=new URLSearchParams;e?.format&&t.set("format",e.format),e?.dataType&&t.set("dataType",e.dataType),e?.minConfidence!==void 0&&t.set("minConfidence",String(e.minConfidence)),e?.limit&&t.set("limit",String(e.limit)),e?.includeExecuted!==void 0&&t.set("includeExecuted",String(e.includeExecuted)),e?.includeSuccessful!==void 0&&t.set("includeSuccessful",String(e.includeSuccessful));let r=t.toString();return n(`/admin/copilot/training-data/export${r?`?${r}`:""}`)},async getTrainingDataStats(){return n("/admin/copilot/training-data/stats")},async listErrors(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.path&&t.set("path",e.path),e?.errorCode&&t.set("errorCode",e.errorCode),e?.status&&t.set("status",e.status),e?.environment&&t.set("environment",e.environment),e?.startDate&&t.set("startDate",e.startDate),e?.endDate&&t.set("endDate",e.endDate),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/errors${r?`?${r}`:""}`)},async getErrorStats(){return n("/admin/errors/stats")},async getError(e){return n(`/admin/errors/${e}`)},async resolveError(e,t){return n(`/admin/errors/${e}/resolve`,{method:"PUT",body:JSON.stringify({notes:t})})},async deleteError(e){return n(`/admin/errors/${e}`,{method:"DELETE"})},async bulkDeleteErrors(e){let t=e?`?olderThanDays=${e}`:"";return n(`/admin/errors${t}`,{method:"DELETE"})},async getAIWorkspaceOverview(){return n("/admin/ai-workspace/overview")},async listAIWorkspaceSessions(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.taskType&&t.set("taskType",e.taskType),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/ai-workspace/sessions${r?`?${r}`:""}`)},async getAIWorkspaceSession(e){return n(`/admin/ai-workspace/sessions/${e}`)},async deleteAIWorkspaceSession(e){return n(`/admin/ai-workspace/sessions/${e}`,{method:"DELETE"})}}}function se(s){let n=p(s);return {async list(){return (await n("/flags")).flags},async create(e){return n("/flags",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/flags/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)})},async delete(e){return n(`/flags/${encodeURIComponent(e)}`,{method:"DELETE"})}}}function ie(s){let n=p(s);return {async getOverview(e){return (await n(`/security/overview/${encodeURIComponent(e)}`)).overview},async getAuditLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));let o=r.toString(),a=`/security/audit/${encodeURIComponent(e)}${o?`?${o}`:""}`;return n(a)},async listEnvVars(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let o=r.toString(),a=`/projects/${encodeURIComponent(e)}/env-vars${o?`?${o}`:""}`;return (await n(a)).envVars},async createEnvVar(e,t){return (await n(`/projects/${encodeURIComponent(e)}/env-vars`,{method:"POST",body:JSON.stringify(t)})).envVar},async updateEnvVar(e,t,r){return (await n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})).envVar},async deleteEnvVar(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"DELETE"})},async getEnvVarValue(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}/value`)}}}function ae(s){let n=p(s);return {async generatePlan(e){return n("/ai/plan",{method:"POST",body:JSON.stringify({projectId:e.projectId,prompt:e.prompt,context:e.context,taskType:e.taskType,mode:e.mode})})},async explainPlan(e){return n("/ai/explain",{method:"POST",body:JSON.stringify({plan:e.plan,projectId:e.projectId,taskType:e.taskType,mode:e.mode})})},async getOrgSettings(e){return n(`/ai/settings/org/${encodeURIComponent(e)}`)},async updateOrgSettings(e,t){return n(`/ai/settings/org/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getProjectOverrides(e){return n(`/ai/settings/project/${encodeURIComponent(e)}`)},async updateProjectOverrides(e,t){return n(`/ai/settings/project/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getUsage(e,t){let r=new URLSearchParams;t&&r.set("month",t);let o=r.toString(),a=`/ai/usage/org/${encodeURIComponent(e)}${o?`?${o}`:""}`;return n(a)},async getBudgetStatus(e){let[t,r]=await Promise.all([this.getOrgSettings(e),this.getUsage(e)]),o=t?.monthlyBudgetCents??1e4,a=r.costCents,l=Math.max(0,o-a),i=o>0?Math.round(a/o*100):0;return {spent:a,budget:o,remaining:l,hardStop:t?.hardStopEnabled??false,percentUsed:i}},async generateFunction(e){return n("/ai/generate-function",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,language:e.language??"typescript",mode:e.mode})})},async generateEndpoint(e){return n("/ai/generate-endpoint",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,method:e.method??"GET",authRequired:e.authRequired??true,mode:e.mode})})},async exportCode(e){return n("/ai/export-code",{method:"POST",body:JSON.stringify({projectId:e.projectId,targetLanguage:e.targetLanguage,includeSchema:e.includeSchema??true,includeFunctions:e.includeFunctions??true,includeEndpoints:e.includeEndpoints??true})})},async createConversation(e,t){return n("/ai/conversations",{method:"POST",body:JSON.stringify({projectId:e,title:t?.title,context:t?.context})})},async sendMessage(e,t){return n(`/ai/conversations/${encodeURIComponent(e)}/messages`,{method:"POST",body:JSON.stringify({content:t.content,taskType:t.taskType})})},async getConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`)},async listConversations(e){return (await n(`/ai/conversations/project/${encodeURIComponent(e)}`)).conversations},async deleteConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`,{method:"DELETE"})},async getAvailableModels(){return n("/ai/models/available")},async getModel(e){return n(`/ai/models/${encodeURIComponent(e)}`)},async getProjectContext(e){return n(`/ai/context/${encodeURIComponent(e)}`)},async estimateTokens(e,t){return n("/ai/context/estimate",{method:"POST",body:JSON.stringify({prompt:e,projectId:t})})},async analyzeForClarification(e){return n("/ai/clarify",{method:"POST",body:JSON.stringify(e)})},async getSuggestions(e){return n("/ai/suggestions",{method:"POST",body:JSON.stringify(e)})},workspace:{async create(e){return n("/ai/workspace/create",{method:"POST",body:JSON.stringify(e)})},async get(e){return n(`/ai/workspace/${encodeURIComponent(e)}`)},async list(e){return n(`/ai/workspace/list/${encodeURIComponent(e)}`)},async submitPrompt(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/prompt`,{method:"POST",body:JSON.stringify(t),timeout:12e4})},async submitClarification(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/clarify`,{method:"POST",body:JSON.stringify({responses:t}),timeout:9e4})},async generate(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/generate`,{method:"POST",body:JSON.stringify(t),timeout:18e4})},async submitModification(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/modify`,{method:"POST",body:JSON.stringify(t),timeout:18e4})},async submitFeedback(e,t){return n(`/ai/workspace/${encodeURIComponent(e)}/feedback`,{method:"POST",body:JSON.stringify(t)})}},backends:{async get(e){return n(`/ai/backends/${encodeURIComponent(e)}`)},async list(e){return n(`/ai/backends/list/${encodeURIComponent(e)}`)},async delete(e){return n(`/ai/backends/${encodeURIComponent(e)}`,{method:"DELETE"})},async deploy(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/deploy`,{method:"POST",body:JSON.stringify(t)})},async apply(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify(t)})},async deployLive(e,t){return n(`/ai/backends/${encodeURIComponent(e)}/deploy-live`,{method:"POST",body:JSON.stringify(t),timeout:3e5})},async getDeployments(e){return n(`/ai/backends/${encodeURIComponent(e)}/deployments`)}},deployments:{async getLimits(e){return n(`/ai/deployments/limits/${encodeURIComponent(e)}`)},async getStatus(e){return n(`/ai/deployments/${encodeURIComponent(e)}/status`)},async getLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.severity&&r.set("severity",t.severity);let o=r.toString();return n(`/ai/deployments/${encodeURIComponent(e)}/logs${o?`?${o}`:""}`)},async terminate(e){return n(`/ai/deployments/${encodeURIComponent(e)}`,{method:"DELETE"})},async redeploy(e){return n(`/ai/deployments/${encodeURIComponent(e)}/redeploy`,{method:"POST",timeout:3e5})}},async getUserOrganizations(){return n("/ai/user/organizations")},async getProjectLimits(e){return n(`/ai/org/${encodeURIComponent(e)}/project-limits`)},async createProjectWithSchema(e){return n("/ai/schema/create-project",{method:"POST",body:JSON.stringify(e)})}}}function le(s){let n=p(s);return {async load(){return n("/bootstrap")}}}function ce(s){let n=p(s);return {async list(e){let t=new URLSearchParams;e?.visibility&&t.set("visibility",e.visibility),e?.category&&t.set("category",e.category),e?.orgId&&t.set("orgId",e.orgId);let r=t.toString(),o=`/templates${r?`?${r}`:""}`;return (await n(o)).templates},async get(e){return n(`/templates/${e}`)},async create(e){return n("/templates",{method:"POST",body:JSON.stringify(e)})},async previewInstall(e){return n("/templates/install/preview",{method:"POST",body:JSON.stringify(e)})},async applyInstall(e){return n("/templates/install/apply",{method:"POST",body:JSON.stringify(e)})},async rollback(e){return n(`/templates/install/${e}/rollback`,{method:"POST"})},async createProject(e){return n("/templates/create-project",{method:"POST",body:JSON.stringify(e)})}}}function de(s){let n=p(s);return {async list(e){return (await n(`/oauth/org/${e}`)).connections},async configure(e,t){return n(`/oauth/org/${e}/configure`,{method:"POST",body:JSON.stringify(t)})},async update(e,t,r){return n(`/oauth/org/${e}/provider/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(e,t){return n(`/oauth/org/${e}/provider/${t}`,{method:"DELETE"})}}}function ue(s){let n=p(s);return {async listPages(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/pages${t}`)).pages},async getPage(e){return (await n(`/docs/pages/${encodeURIComponent(e)}`)).page},async createPage(e){return (await n("/docs/pages",{method:"POST",body:JSON.stringify(e)})).page},async updatePage(e,t){return (await n(`/docs/pages/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).page},async deletePage(e){return n(`/docs/pages/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdks(){return (await n("/docs/sdks")).sdks},async getSdk(e){return (await n(`/docs/sdks/${encodeURIComponent(e)}`)).sdk},async createSdk(e){return (await n("/docs/sdks",{method:"POST",body:JSON.stringify(e)})).sdk},async updateSdk(e,t){return (await n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).sdk},async deleteSdk(e){return n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdkExamples(e,t){let r=t?`?topic=${encodeURIComponent(t)}`:"";return (await n(`/docs/sdks/${encodeURIComponent(e)}/examples${r}`)).examples},async createSdkExample(e){return (await n("/docs/sdk-examples",{method:"POST",body:JSON.stringify(e)})).example},async deleteSdkExample(e){return n(`/docs/sdk-examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listEndpoints(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/api-endpoints${t}`)).endpoints},async getEndpoint(e){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`)).endpoint},async createEndpoint(e){return (await n("/docs/api-endpoints",{method:"POST",body:JSON.stringify(e)})).endpoint},async updateEndpoint(e,t){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).endpoint},async deleteEndpoint(e){return n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},async listExamples(e){let t=e!==void 0?`?featured=${e}`:"";return (await n(`/docs/examples${t}`)).examples},async getExample(e){return (await n(`/docs/examples/${encodeURIComponent(e)}`)).example},async createExample(e){return (await n("/docs/examples",{method:"POST",body:JSON.stringify(e)})).example},async updateExample(e,t){return (await n(`/docs/examples/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).example},async deleteExample(e){return n(`/docs/examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listChangelog(){return (await n("/docs/changelog")).entries},async getChangelogEntry(e){return (await n(`/docs/changelog/${encodeURIComponent(e)}`)).entry},async createChangelogEntry(e){return (await n("/docs/changelog",{method:"POST",body:JSON.stringify(e)})).entry},async updateChangelogEntry(e,t){return (await n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).entry},async deleteChangelogEntry(e){return n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"DELETE"})},async search(e){return (await n(`/docs/search?q=${encodeURIComponent(e)}`)).results}}}function J(s,n,e,t){let r=[...n],o=0,a=false,l=false,i=async()=>{if(l||a)return;let c=await e(`/mongodb/${t}/cursor/${s}/next`,{method:"POST"});r=c.batch,o=0,a=c.exhausted;};return {id:s,async hasNext(){return l?false:o<r.length?true:a?false:(await i(),r.length>0)},async next(){return l?null:o<r.length?r[o++]:a||(await i(),r.length===0)?null:r[o++]},async toArray(){if(l)return [];let c=[];for(;o<r.length;)c.push(r[o++]);for(;!a;)await i(),c.push(...r),o=r.length;return c},async forEach(c){if(!l){for(;o<r.length;)await c(r[o++]);for(;!a;){await i();for(let g of r)await c(g);o=r.length;}}},map(c){let g=r.slice(o).map(c);return J(s,g,e,t)},async close(){if(!l){l=true;try{await e(`/mongodb/${t}/cursor/${s}/close`,{method:"POST"});}catch{}}},isClosed(){return l}}}function Oe(s,n){let e=`/mongodb/${encodeURIComponent(s)}`;return {collectionName:s,async find(t,r){return n(`${e}/find`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async findCursor(t,r){let o=await n(`${e}/find/cursor`,{method:"POST",body:JSON.stringify({filter:t,options:r})});return J(o.cursorId,o.batch,n,s)},async findOne(t,r){return n(`${e}/findOne`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async findById(t,r){return n(`${e}/findById/${encodeURIComponent(t)}`,{method:"GET",...r&&{body:JSON.stringify({options:r})}})},async countDocuments(t){return (await n(`${e}/count`,{method:"POST",body:JSON.stringify({filter:t})})).count},async estimatedDocumentCount(){return (await n(`${e}/estimatedCount`)).count},async distinct(t,r){return n(`${e}/distinct`,{method:"POST",body:JSON.stringify({field:t,...r})})},async insertOne(t){return n(`${e}/insertOne`,{method:"POST",body:JSON.stringify({document:t})})},async insertMany(t,r){return n(`${e}/insertMany`,{method:"POST",body:JSON.stringify({documents:t,options:r})})},async updateOne(t,r,o){return n(`${e}/updateOne`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async updateMany(t,r,o){return n(`${e}/updateMany`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async replaceOne(t,r,o){return n(`${e}/replaceOne`,{method:"POST",body:JSON.stringify({filter:t,replacement:r,options:o})})},async findOneAndUpdate(t,r,o){return n(`${e}/findOneAndUpdate`,{method:"POST",body:JSON.stringify({filter:t,update:r,options:o})})},async findOneAndReplace(t,r,o){return n(`${e}/findOneAndReplace`,{method:"POST",body:JSON.stringify({filter:t,replacement:r,options:o})})},async deleteOne(t){return n(`${e}/deleteOne`,{method:"POST",body:JSON.stringify({filter:t})})},async deleteMany(t){return n(`${e}/deleteMany`,{method:"POST",body:JSON.stringify({filter:t})})},async findOneAndDelete(t,r){return n(`${e}/findOneAndDelete`,{method:"POST",body:JSON.stringify({filter:t,options:r})})},async aggregate(t,r){return n(`${e}/aggregate`,{method:"POST",body:JSON.stringify({pipeline:t,options:r})})},async aggregateCursor(t,r){let o=await n(`${e}/aggregate/cursor`,{method:"POST",body:JSON.stringify({pipeline:t,options:r})});return J(o.cursorId,o.batch,n,s)},async createIndex(t,r){return (await n(`${e}/indexes`,{method:"POST",body:JSON.stringify({keys:t,options:r})})).indexName},async dropIndex(t){await n(`${e}/indexes/${encodeURIComponent(t)}`,{method:"DELETE"});},async listIndexes(){return n(`${e}/indexes`)},async bulkWrite(t,r){return n(`${e}/bulkWrite`,{method:"POST",body:JSON.stringify({operations:t,options:r})})}}}function ge(s){let n=p(s);return {collection(e){return Oe(e,n)},async listCollections(){return n("/mongodb/collections")},async createCollection(e,t){await n("/mongodb/collections",{method:"POST",body:JSON.stringify({name:e,options:t})});},async dropCollection(e){await n(`/mongodb/collections/${encodeURIComponent(e)}`,{method:"DELETE"});},async renameCollection(e,t){await n(`/mongodb/collections/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({newName:t})});},async command(e){return n("/mongodb/command",{method:"POST",body:JSON.stringify(e)})}}}function pe(s){let n=p(s);return {async chat(e){return n("/ai/copilot/chat",{method:"POST",body:JSON.stringify(e),timeout:12e4})},getStreamUrl(){return `${s.baseUrl}/ai/copilot/chat/stream`},async getModels(e){return n(`/ai/copilot/models/${encodeURIComponent(e)}`)},async getCreditStatus(e){return n(`/ai/copilot/credit-status/${encodeURIComponent(e)}`)},async listSessions(e){return n(`/ai/copilot/sessions/${encodeURIComponent(e)}`)},async getSession(e){return n(`/ai/copilot/session/${encodeURIComponent(e)}`)},async updateSession(e,t){return n(`/ai/copilot/session/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async deleteSession(e){return n(`/ai/copilot/session/${encodeURIComponent(e)}`,{method:"DELETE"})},async executePlan(e){return n("/ai/copilot/execute",{method:"POST",body:JSON.stringify(e),timeout:18e4})},async submitFeedback(e){return n("/ai/copilot/feedback",{method:"POST",body:JSON.stringify(e)})},async getClassificationStats(){return n("/ai/copilot/stats")},async getUsage(e){return n(`/ai/copilot/usage-org/${encodeURIComponent(e)}`)}}}function xe(s,n,e,t){let r=n.type||"public",o="unsubscribed",a=new Map,l=[],i={},c=null,g=null,y=new Set,h=new Set,S=new Set,P=d=>{if(d.event){let b=a.get(d.event);b&&b.forEach(R=>R(d.payload));}},A=d=>{i=d.state||{},y.forEach(b=>b(i));},f=d=>{let b=d.key||"",R=d.currentPresences||[],u=d.joinedPresences||[],m=d.leftPresences||[];u.length>0&&(i[b]=R,h.forEach(I=>I(b,R,u))),m.length>0&&(R.length===0?delete i[b]:i[b]=R,S.forEach(I=>I(b,R,m))),y.forEach(I=>I(i));},T=d=>{let b={type:"db_change",projectId:d.projectId||"",schema:d.schema||"",table:d.table||"",operation:d.op,new:d.record,old:d.old_record,timestamp:d.ts||new Date().toISOString(),partial:d.partial};l.forEach(({options:R,handler:u})=>{if(R.table===b.table){let m=R.event||"*";(m==="*"||(Array.isArray(m)?m.includes(b.operation):m===b.operation))&&u(b);}});},C={get name(){return s},get type(){return r},get status(){return o},_handleMessage:d=>{switch(d.type){case "broadcast":P(d);break;case "presence_state":A(d);break;case "presence":f(d);break;case "db_change":T(d);break;case "subscribed":o="subscribed";break;case "error":o="error";break}},onDbChange(d,b){return l.push({options:d,handler:b}),o==="subscribed"&&e({type:"subscribe",channel:s,options:{table:d.table,filter:d.filter,event:d.event,columns:d.columns}}),C},on(d,b){return a.has(d)||a.set(d,new Set),a.get(d).add(b),C},off(d,b){return b?a.get(d)?.delete(b):a.delete(d),C},async broadcast(d){if(o!=="subscribed")throw new k("Channel must be subscribed before broadcasting",{code:"CHANNEL_NOT_SUBSCRIBED"});e({type:"broadcast",channel:s,event:d.event,payload:d.payload,includeSelf:d.includeSelf});},presence:{async track(d){if(r!=="presence")throw new k("Presence tracking is only available on presence channels",{code:"INVALID_CHANNEL_TYPE"});c=d.key||t()||"anonymous",g=d.state,e({type:"presence_track",channel:s,key:c,state:g});},async update(d){if(!g)throw new k("Must call track() before update()",{code:"PRESENCE_NOT_TRACKED"});g={...g,...d},e({type:"presence_update",channel:s,key:c??void 0,state:g});},async untrack(){c&&(e({type:"presence_untrack",channel:s,key:c}),c=null,g=null);},state(){return {...i}},onSync(d){return y.add(d),C},onJoin(d){return h.add(d),C},onLeave(d){return S.add(d),C}},async subscribe(){return o==="subscribed"||(o="subscribing",e({type:"subscribe",channel:s}),l.forEach(({options:d})=>{e({type:"subscribe",channel:s,options:{table:d.table,filter:d.filter,event:d.event,columns:d.columns}});}),n.presenceState&&r==="presence"&&await C.presence.track({state:n.presenceState})),C},async unsubscribe(){o!=="unsubscribed"&&(c&&await C.presence.untrack(),e({type:"unsubscribe",channel:s}),o="unsubscribed",i={},a.clear(),l.length=0);}};return C}function me(s,n){let{wsUrl:e=s.baseUrl.replace(/^http/,"ws")+"/realtime/ws",autoReconnect:t=true,reconnectDelay:r=1e3,maxReconnectAttempts:o=10}=n??{},a=null,l="disconnected",i=null,c=null,g=0,y=null,h=null,S=new Map,P=new Map,A=new Set,f={connect:new Set,disconnect:new Set,error:new Set,reconnect:new Set},T=u=>{f[u].forEach(m=>m());},O=u=>{let m=`table:${u.table}`;if(u.filter){let M=(Array.isArray(u.filter)?u.filter:[u.filter]).map(w=>`${w.field}${w.operator||"eq"}${w.value}`).join("&");m+=`?${M}`;}return m},C=u=>{a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(u));},d=u=>{if(u.channel){let m=S.get(u.channel);if(m){m._handleMessage(u);return}}switch(u.type){case "db_change":{let m={type:"db_change",projectId:u.projectId??"",schema:u.schema??"",table:u.table??"",operation:u.op,new:u.record,old:u.old_record,timestamp:u.ts??new Date().toISOString(),partial:u.partial},I=`table:${u.table}`;P.forEach((M,w)=>{(w===I||w.startsWith(I+"?"))&&M.forEach(N=>N(m));});break}case "presence":{let m={type:"presence",event:u.event,key:u.key||u.connectionId||"",connectionId:u.connectionId??"",projectId:u.projectId??"",currentPresences:u.currentPresences||[],leftPresences:u.leftPresences||[],joinedPresences:u.joinedPresences||[]};A.forEach(I=>I(m));break}case "welcome":i=u.connectionId||null;break;case "error":{T("error");break}}},b=()=>new Promise((u,m)=>{try{a=new WebSocket(e);}catch{m(new x("Failed to create WebSocket connection"));return}let I=()=>{l="connected",g=0;let D={type:"auth"};s.apiKey&&(D[s.apiKeyHeader]=s.apiKey),c&&(D.token=c),C(D),T("connect"),S.forEach(B=>{(B.status==="subscribed"||B.status==="subscribing")&&B.subscribe();}),P.forEach((B,ye)=>{C({type:"subscribe",channel:ye});}),h=setInterval(()=>{C({type:"ping"});},3e4),u();},M=D=>{try{let B=JSON.parse(D.data);d(B);}catch{}},w=()=>{if(l="disconnected",i=null,a=null,h&&(clearInterval(h),h=null),T("disconnect"),t&&g<o){l="reconnecting";let D=r*Math.pow(2,g);y=setTimeout(()=>{g++,T("reconnect"),b().catch(()=>{});},Math.min(D,3e4));}},N=()=>{T("error"),m(new x("WebSocket connection error"));};a.addEventListener("open",I),a.addEventListener("message",M),a.addEventListener("close",w),a.addEventListener("error",N);}),R=()=>{y&&(clearTimeout(y),y=null),h&&(clearInterval(h),h=null),g=o;};return {channel(u,m={}){let I=S.get(u);if(I)return I;let M=xe(u,m,C,()=>i);return S.set(u,M),M},async removeChannel(u){let m=S.get(u.name);m&&(await m.unsubscribe(),S.delete(u.name));},getChannels(){return Array.from(S.values())},subscribe(u,m){let I=O(u);return P.has(I)||P.set(I,new Set),P.get(I).add(m),a?.readyState===WebSocket.OPEN&&C({type:"subscribe",channel:I}),()=>{let M=P.get(I);M&&(M.delete(m),M.size===0&&(P.delete(I),a?.readyState===WebSocket.OPEN&&C({type:"unsubscribe",channel:I})));}},subscribeToPresence(u){return A.add(u),()=>{A.delete(u);}},async connect(){if(l!=="connected"){if(!s.apiKey)throw new E("API key is required for realtime connections");l="connecting",await b();}},disconnect(){R(),S.forEach(u=>{u.unsubscribe();}),S.clear(),a&&(a.close(),a=null),l="disconnected",i=null;},get isConnected(){return l==="connected"},get connectionState(){return l},get connectionId(){return i},on(u,m){f[u].add(m);},off(u,m){f[u].delete(m);},setAuth(u){c=u;}}}var F={apiKeyHeader:"x-vaif-key",timeout:3e4,retry:{maxRetries:3,retryDelay:1e3,maxRetryDelay:3e4,backoffMultiplier:2,retryOn:[429,500,502,503,504],retryOnNetworkError:true}};function Me(s){return {baseUrl:s.baseUrl.replace(/\/$/,""),apiKey:s.apiKey,apiKeyHeader:s.apiKeyHeader??F.apiKeyHeader,accessToken:s.accessToken,fetch:s.fetch??globalThis.fetch.bind(globalThis),timeout:s.timeout??F.timeout,retry:{maxRetries:s.retry?.maxRetries??F.retry.maxRetries,retryDelay:s.retry?.retryDelay??F.retry.retryDelay,maxRetryDelay:s.retry?.maxRetryDelay??F.retry.maxRetryDelay,backoffMultiplier:s.retry?.backoffMultiplier??F.retry.backoffMultiplier,retryOn:s.retry?.retryOn??[...F.retry.retryOn],retryOnNetworkError:s.retry?.retryOnNetworkError??F.retry.retryOnNetworkError},interceptors:s.interceptors??{}}}function Ee(s){let n=Me(s),e=W(n),t=_(n),r=H(n),o=G(n),a=z(n),l=Q(n),i=X(n),c=Y(n),g=Z(n),y=ee(n),h=te(n),S=ne(n),P=re(n),A=oe(n),f=se(n),T=ie(n),O=ae(n),C=le(n),d=ce(n),b=de(n),R=ue(n),u=ge(n),m=pe(n);return {from:e.from,auth:t,functions:r,storage:o,projects:a,orgs:l,schema:i,secrets:c,deployments:g,realtimeMonitoring:y,storageDashboard:h,integrations:S,billing:P,admin:A,flags:f,security:T,ai:O,bootstrap:C,templates:d,oauth:b,docs:R,mongodb:u,copilot:m,realtime:I=>me(n,I)}}export{E as VaifAuthError,L as VaifConflictError,k as VaifError,x as VaifNetworkError,$ as VaifNotFoundError,U as VaifRateLimitError,V as VaifTimeoutError,j as VaifValidationError,Ee as createVaifClient,Pe as isVaifAuthError,be as isVaifError,he as isVaifNetworkError,fe as isVaifNotFoundError,ke as isVaifRateLimitError,Ie as isVaifValidationError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vaiftech/client",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "TypeScript SDK for VAIF Studio BaaS",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -15,15 +15,8 @@
15
15
  "files": [
16
16
  "dist"
17
17
  ],
18
- "scripts": {
19
- "build": "tsup",
20
- "dev": "tsup --watch",
21
- "lint": "tsc --noEmit",
22
- "typecheck": "tsc --noEmit",
23
- "test": "vitest run"
24
- },
25
18
  "dependencies": {
26
- "@vaiftech/auth": "workspace:*"
19
+ "@vaiftech/auth": "1.1.1"
27
20
  },
28
21
  "devDependencies": {
29
22
  "tsup": "^8.0.0",
@@ -63,5 +56,12 @@
63
56
  "bugs": {
64
57
  "url": "https://github.com/vaif-technologies/vaif-studio/issues"
65
58
  },
66
- "homepage": "https://vaif.studio"
67
- }
59
+ "homepage": "https://vaif.studio",
60
+ "scripts": {
61
+ "build": "tsup",
62
+ "dev": "tsup --watch",
63
+ "lint": "tsc --noEmit",
64
+ "typecheck": "tsc --noEmit",
65
+ "test": "vitest run"
66
+ }
67
+ }