@protobase/server 0.126.0 → 0.126.1
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/create-admin.js +10 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/package.js +1 -1
- package/dist/relay/change-commands.js +34 -4
- package/dist/relay/client-events.d.ts +2 -2
- package/dist/relay/members-sql.js +30 -7
- package/dist/relay/realtime-channels.d.ts +25 -0
- package/dist/relay/realtime-channels.js +39 -0
- package/dist/relay/realtime-members-reads.js +16 -0
- package/dist/relay/realtime-members-schema.js +67 -0
- package/dist/relay/realtime-members-sql.js +120 -0
- package/dist/relay/relay-jobs.js +9 -1
- package/dist/relay/relay-models.js +27 -3
- package/dist/relay/relay-options.d.ts +16 -4
- package/dist/relay/relay-options.js +7 -2
- package/dist/relay/relay-runtime.js +3 -3
- package/dist/relay/relay-schema.d.ts +8 -5
- package/dist/relay/relay-schema.js +17 -5
- package/dist/relay/relay-switch.d.ts +1 -0
- package/dist/relay/relay-switch.js +12 -6
- package/dist/relay/ticket-route.js +2 -1
- package/dist/relay/typing-views.js +1 -1
- package/package.json +6 -6
package/dist/create-admin.js
CHANGED
|
@@ -87,7 +87,9 @@ import { pushJob } from "./notifications/push-job.js";
|
|
|
87
87
|
import { onDoNotDisturb } from "./status/do-not-disturb.js";
|
|
88
88
|
import { checkStatusAuth, statusNames } from "./status/options.js";
|
|
89
89
|
import { statusRoutes } from "./status/routes.js";
|
|
90
|
+
import { appRelayChannels } from "./relay/realtime-channels.js";
|
|
90
91
|
import { appRelaySettings } from "./relay/relay-switch.js";
|
|
92
|
+
import { idleRelayJobs } from "./relay/relay-jobs.js";
|
|
91
93
|
import { relayPresencePath } from "./relay/presence-route.js";
|
|
92
94
|
import { relayTicketPath } from "./relay/ticket-route.js";
|
|
93
95
|
import { relayRuntime } from "./relay/relay-runtime.js";
|
|
@@ -343,8 +345,14 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
343
345
|
...statusTables && { doNotDisturb: (ringDb, userIds) => onDoNotDisturb(ringDb, statusTables.statuses, userIds) }
|
|
344
346
|
}) }
|
|
345
347
|
};
|
|
346
|
-
const
|
|
348
|
+
const relayApp = {
|
|
349
|
+
views: viewModels,
|
|
350
|
+
models: appModels,
|
|
351
|
+
signIn: Boolean(auth)
|
|
352
|
+
};
|
|
353
|
+
const relaySettings = appRelaySettings(realtime?.relay, globalThis.process?.env ?? {}, relayApp);
|
|
347
354
|
const relay = relaySettings && relayRuntime(relaySettings, auth, deps);
|
|
355
|
+
const relayJobList = relay ? relay.jobs : appRelayChannels(realtime?.relay, relayApp) ? idleRelayJobs() : [];
|
|
348
356
|
const typingErrors = typingViewErrors(viewModels, relaySettings && new Set(Object.keys(relaySettings.channels)));
|
|
349
357
|
if (typingErrors.length > 0) throw new Error(typingErrors.join("\n"));
|
|
350
358
|
if (auth) auth.mailSenderUse.set(mailSenderUse(db, registry.entries));
|
|
@@ -685,7 +693,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
|
|
|
685
693
|
jobs: [
|
|
686
694
|
...webhooks.jobs,
|
|
687
695
|
...auth ? auth.senderVerificationJobs : [],
|
|
688
|
-
...
|
|
696
|
+
...relayJobList,
|
|
689
697
|
...engine ? engine.jobs : [],
|
|
690
698
|
...derived ? derived.jobs : [],
|
|
691
699
|
...withHistory && days !== void 0 ? [pruneHistoryJob(changes, days)] : [],
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { MobileConfig, MobileSplash, MobileSplashLook } from "./mobile-config.js";
|
|
2
2
|
import { AppIdentity } from "./app-identity.js";
|
|
3
3
|
import { AppIcons, PngIcon, pngIcons } from "./web-app/app-icons.js";
|
|
4
|
-
import { RealtimeRelayOptions, RealtimeRelaySettings, RelayChannelOptions, RelayClientEvent, RelayMembers, RelayPresence, checkRelayOptions, realtimeVariables, relaySettings } from "./relay/relay-options.js";
|
|
4
|
+
import { RealtimeRelayOptions, RealtimeRelaySettings, RelayChannelOptions, RelayClientEvent, RelayListedMembers, RelayMembers, RelayPresence, checkRelayOptions, realtimeVariables, relaySettings } from "./relay/relay-options.js";
|
|
5
5
|
import { RealtimeOptions, relayed, sqlSends } from "./realtime/relay/realtime-options.js";
|
|
6
6
|
import { StaffSignIn } from "./better-auth/staff-log.js";
|
|
7
7
|
import { OrganizationRole, StoredMember, StoredOrganization } from "./better-auth/organizations/store.js";
|
|
@@ -162,6 +162,7 @@ import { mailFeedbackResource } from "./mail/feedback/mail-feedback-resource.js"
|
|
|
162
162
|
import { mailFeedbackHeaders, mailFeedbackSecret } from "./mail/feedback/feedback-signing.js";
|
|
163
163
|
import { MailFeedback } from "./mail/feedback/feedback-record.js";
|
|
164
164
|
import { onDoNotDisturb } from "./status/do-not-disturb.js";
|
|
165
|
+
import { appRelayChannels, defaultRelayChannels } from "./relay/realtime-channels.js";
|
|
165
166
|
import { readRelaySwitch, realtimeSwitchVariable } from "./relay/relay-switch.js";
|
|
166
167
|
import { relayPresencePath } from "./relay/presence-route.js";
|
|
167
168
|
import { relayClientEvents, typingResources } from "./relay/client-events.js";
|
|
@@ -237,4 +238,4 @@ import { DrainResult, JobsRuntime, StartJobsOptions, startJobs } from "./jobs/ru
|
|
|
237
238
|
import { jobsDrainApp } from "./jobs/drain-route.js";
|
|
238
239
|
import { checkJobsSchema, jobsSchema, jobsSchemaMigration } from "./jobs/schema.js";
|
|
239
240
|
import { ResourceSource, configExports } from "./resource-source.js";
|
|
240
|
-
export { type AddVerifier, type Admin, type AdminAuth, type AdminOptions, type AggregateParams, type ApiFunction, type ApiKeys, type ApiKeysOptions, type ApnsEnvironment, type ApnsOptions, type ApnsSettings, type AppIcons, type AppIdentity, type AppPoolConfig, type ApplyOptions, type ApplyResult, type ApprovalAnswer, type ApprovalRequest, type ArgumentsPayload, type AssistantBackend, type AssistantOptions, type AssistantSettings, type AssistantTool, type AuditEvent, type AuditQueue, type AuthHooks, type AuthSettings, type AuthenticateSettings, type Authenticator, type BaseToolContext, type BatchOperation, type BatchResult, type BetterAuthAuthenticator, type BetterAuthAuthenticatorOptions, type BridgeClosing, type BridgeRule, type BridgeTarget, BulkMailError, type CallBackend, type CallMember, type Caller, type CallerOptions, type CallsAccess, type CallsOptions, type CapturedRow, type CascadingKey, type ChannelBroadcast, type ChannelSender, type ChatMessage, type ChatTextPart, type CheckAiInput, type CleanupEntry, type CleanupReport, type CleanupSchedule, type CoalescedChange, type CommentItem, type CommentToolsInput, type CommentUsers, type Completion, type CompletionOptions, type ConnectionListing, ConnectionsBusy, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CorsOptions, type CorsOrigins, type CreateAdminInput, type CreateAuthOptions, type DecryptField, type DerivedClock, type DerivedCompute, type DerivedContext, type Device, type DeviceColumn, type DeviceKind, type DeviceStore, DeviceStoreError, type DrainResult, type EmailComponent, type EmailOptions, type EmailTemplate, type EncryptionStatus, type EncryptionTools, type EncryptionToolsInput, type EnqueueJob, type EnqueueOptions, type ErrorReporter, type ErrorReportingOptions, type ErrorReportingSettings, type EventData, type EventsOptions, FatalJobError, type FcmOptions, type FcmSettings, type FieldApplied, type FieldDecrypter, type FieldReader, type FieldStatus, type FileCleanupInput, type FileLimits, type FileObject, type FileProvider, type FileProviderSettings, type FileRef, type FileStore, type FileVariantObject, type FilesOptions, type FunctionApp, type FunctionCaller, type FunctionContext, type FunctionEnv, type FunctionHandler, type FunctionOptions, type FunctionRecords, type FunctionSocket, type FunctionSource, type HistoryColumn, type HistoryOptions, type HistoryPosition, type HistoryStore, HistoryStoreError, type HookContext, HttpProblem, type IssueTokenOptions, type JobContext, type JobDeclaration, type JobDefinition, type JobName, type JobOptions, type JobPayload, type JobRun, type JobsRuntime, type JoinedUser, type JsonObject, type JsonValue, type JwtOptions, type JwtVerifyOptions, type KeyFunctionContext, type LinkedAccount, type ListParams, type ListedOrganization, type LiveKitBackend, type LocalFilesOptions, type MailAttachment, type MailFeedback, type MailMessage, type MailSender, MailSenderRefusedError, MailServerTimeoutError, type MailTemplate, type Mailer, type MapLayer, type MapOptions, type MapSettings, type McpApprovals, type McpGateInput, type McpHandlerInput, type McpRoutesInput, type McpServerInput, type McpToolsInput, type McpWrites, type MemberInput, type Membership, MissingCredentials, type MobileConfig, type MobileSplash, type MobileSplashLook, ModelError, type ModelSettings, type NewDevice, type NewNotification, type NewOrganization, type NewUser, type NotificationRecipients, NotificationSendError, type NotificationsOptions, type OperatorProvider, type OrganizationRole, type OrganizationsCursor, type OrganizationsOptions, type OrganizationsPage, type OverSignIn, type PdfComponent, type PdfOptions, type PdfTemplate, type PersonalMail, type PersonalMailEntry, PersonalMailError, type PersonalMailErrorCode, type PersonalMailMessage, type PersonalMailProviderId, type PgModule, type PipelineHook, type PlatformSignIn, type PluginOption, type PluginRef, type PngIcon, type ProtectedFunctionOptions, type PublicFunctionContext, type PublicFunctionEnv, type PublicFunctionHandler, type PublicFunctionOptions, type PushAnswer, type PushMessage, PushMessageError, type PushSender, type QueryOptions, type QueryResult, type ReadableResources, type RealtimeOptions, type RealtimePrune, type RealtimeRelayOptions, type RealtimeRelaySettings, type ReasoningDetail, type ReasoningEffort, type RebindOption, type RecordGroups, type RecordKey, type RecordKeyInput, type RecordPage, type RelayChannelOptions, type RelayClientEvent, type RelayDevice, type RelayMembers, type RelayPresence, type RelayResult, type RelaySendAnswer, type RelaySendRequest, type RelaySettings, type RenderedEmail, type RenderedTemplate, type ResourceChange, type ResourceSource, type RoleDefinition, type RolesInput, type RunContext, type RuntimeOptions, type S3Bucket, type S3FilesOptions, type S3ListPage, type S3Object, type ScanGuardMode, type ScheduledDelete, type SendNotification, SenderAddressError, type SenderAddressErrorCode, SenderAddressNotFoundError, type SenderAddressState, type SenderAddressVerifier, type SentMail, type Session, type SessionOrganization, type Sharp, type SignInPolicy, type SignInRule, type SignatureOptions, type SocketEvents, type SourceOption, type SourceRef, type StaffAccessRule, type StaffSignIn, type StandardSchema, type StandardWebhookOptions, type StartJobsOptions, type StartWorkflowOptions, type StatusOptions, type StoreFileInput, type StoredMember, type StoredNotification, type StoredObject, type StoredOrganization, type StoredUser, type StrayValues, type SubscriptionDefinition, type SubscriptionEvent, type SubscriptionOptions, type TcpBridge, type TcpBridgeOptions, TemplateDataError, type TemplateOptions, type TemplateSchema, type TemplateScope, type TemplateSendOptions, type TemplateText, type TenantValue, type ToolAnnotations, type ToolCall, type ToolComment, type ToolCommentPage, type ToolComments, type ToolContext, type ToolRecord, type ToolRecords, type ToolSpec, type TrustedApp, type TurnOptions, type UnreadableEntry, type UnsubscribeLinks, type Urgency, type User, type UserCreatedHook, type UserTables, type UsersCursor, type UsersPage, type VapidSettings, type VerificationInput, type VerificationMessage, type VerificationOutcome, type VerifyInput, type VerifyTools, type ViewSource, type WebPushFields, type WebPushOptions, type WebhooksOptions, type WidgetOptions, type WorkflowCatalog, type WorkflowTypes, type WorkflowsOptions, type WriteEvent, type WriteOperation, type WriteRecordToolsInput, addAppRoleToOwners, addCommentTool, addEveryUser, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, apnsKeyIdVariable, apnsKeyVariable, apnsSender, apnsTeamIdVariable, appNameOver, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, bridgeClosings, callsMigration, capSocketMessages, capturedBy, changesMigration, channelSendsMigration, checkAi, checkAuthSchema, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkJobsSchema, checkMailFeedbackSchema, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkRelayOptions, checkRelaySchema, checkResourcesOutsideAuthStore, checkSourceNames, checkStatusSchema, checkUnsubscribesSchema, checkUserTablesSchema, checkViewQueries, checkWebhooksSchema, checkWorkflowsSchema, coalesce, commentTools, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, countRecordsTool, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultSignInPolicy, defineEmail, defineFunction, defineJob, definePdf, defineTemplate, defineTool, deleteRecordTool, deleteUser, derivedMigration, describeResourceTool, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fcmSender, fcmServiceAccountVariable, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, gmailSettingsScope, goTruePath, handleDroppedConnections, hasBuckets, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, hookPath, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isMailTemplate, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listCommentsTool, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mailFeedbackHeaders, mailFeedbackMigration, mailFeedbackResource, mailFeedbackSecret, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxRelayDevices, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpIcons, mcpInstructions, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, onDoNotDisturb, organizationsPageSize, overSignIn, ownedDefinitionsMigration, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readApnsSettings, readDbConnections, readDefinitionsVersion, readFcmSettings, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIns, readRecordTools, readRelaySettings, readRelaySwitch, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, realtimeRelayMigration, realtimeSwitchVariable, realtimeVariables, recordBlocksOf, recordOf, redactHookKeys, refusalOf, refused, relayClientEvents, relayCredentialVariable, relayHandle, relayMigration, relayPresencePath, relayResults, relaySendAnswer, relaySendPath, relaySendRequest, relaySender, relaySettings, relayUrlVariable, relayed, releaseConnectionsWithUsers, reloadingAdmin, removeDevicesWithUsers, removeHistoryWithUsers, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, seesAssistant, seesRuntime, sendNotification, sessionOf, setMemberRoles, setUserBanned, setUserRole, shownAppName, signInPolicyMethods, socketMessageCapOf, sourceOptions, sourcesFor, sourcesVariable, sqlSends, startErrorReporting, startJobs, startWorkflow, statusMigration, statusNames, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, tcpBridge, thumbHash, typingResources, unauthorized, unsubscribesMigration, updateRecordTool, urgencies, userTableResources, userTablesMigration, usersPageSize, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhookIssuePath, webhookParams, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, workflowInstructions, workflowReadTools, workflowTypes, workflowWriteTools, workflowsMigration, writeRecordTools };
|
|
241
|
+
export { type AddVerifier, type Admin, type AdminAuth, type AdminOptions, type AggregateParams, type ApiFunction, type ApiKeys, type ApiKeysOptions, type ApnsEnvironment, type ApnsOptions, type ApnsSettings, type AppIcons, type AppIdentity, type AppPoolConfig, type ApplyOptions, type ApplyResult, type ApprovalAnswer, type ApprovalRequest, type ArgumentsPayload, type AssistantBackend, type AssistantOptions, type AssistantSettings, type AssistantTool, type AuditEvent, type AuditQueue, type AuthHooks, type AuthSettings, type AuthenticateSettings, type Authenticator, type BaseToolContext, type BatchOperation, type BatchResult, type BetterAuthAuthenticator, type BetterAuthAuthenticatorOptions, type BridgeClosing, type BridgeRule, type BridgeTarget, BulkMailError, type CallBackend, type CallMember, type Caller, type CallerOptions, type CallsAccess, type CallsOptions, type CapturedRow, type CascadingKey, type ChannelBroadcast, type ChannelSender, type ChatMessage, type ChatTextPart, type CheckAiInput, type CleanupEntry, type CleanupReport, type CleanupSchedule, type CoalescedChange, type CommentItem, type CommentToolsInput, type CommentUsers, type Completion, type CompletionOptions, type ConnectionListing, ConnectionsBusy, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CorsOptions, type CorsOrigins, type CreateAdminInput, type CreateAuthOptions, type DecryptField, type DerivedClock, type DerivedCompute, type DerivedContext, type Device, type DeviceColumn, type DeviceKind, type DeviceStore, DeviceStoreError, type DrainResult, type EmailComponent, type EmailOptions, type EmailTemplate, type EncryptionStatus, type EncryptionTools, type EncryptionToolsInput, type EnqueueJob, type EnqueueOptions, type ErrorReporter, type ErrorReportingOptions, type ErrorReportingSettings, type EventData, type EventsOptions, FatalJobError, type FcmOptions, type FcmSettings, type FieldApplied, type FieldDecrypter, type FieldReader, type FieldStatus, type FileCleanupInput, type FileLimits, type FileObject, type FileProvider, type FileProviderSettings, type FileRef, type FileStore, type FileVariantObject, type FilesOptions, type FunctionApp, type FunctionCaller, type FunctionContext, type FunctionEnv, type FunctionHandler, type FunctionOptions, type FunctionRecords, type FunctionSocket, type FunctionSource, type HistoryColumn, type HistoryOptions, type HistoryPosition, type HistoryStore, HistoryStoreError, type HookContext, HttpProblem, type IssueTokenOptions, type JobContext, type JobDeclaration, type JobDefinition, type JobName, type JobOptions, type JobPayload, type JobRun, type JobsRuntime, type JoinedUser, type JsonObject, type JsonValue, type JwtOptions, type JwtVerifyOptions, type KeyFunctionContext, type LinkedAccount, type ListParams, type ListedOrganization, type LiveKitBackend, type LocalFilesOptions, type MailAttachment, type MailFeedback, type MailMessage, type MailSender, MailSenderRefusedError, MailServerTimeoutError, type MailTemplate, type Mailer, type MapLayer, type MapOptions, type MapSettings, type McpApprovals, type McpGateInput, type McpHandlerInput, type McpRoutesInput, type McpServerInput, type McpToolsInput, type McpWrites, type MemberInput, type Membership, MissingCredentials, type MobileConfig, type MobileSplash, type MobileSplashLook, ModelError, type ModelSettings, type NewDevice, type NewNotification, type NewOrganization, type NewUser, type NotificationRecipients, NotificationSendError, type NotificationsOptions, type OperatorProvider, type OrganizationRole, type OrganizationsCursor, type OrganizationsOptions, type OrganizationsPage, type OverSignIn, type PdfComponent, type PdfOptions, type PdfTemplate, type PersonalMail, type PersonalMailEntry, PersonalMailError, type PersonalMailErrorCode, type PersonalMailMessage, type PersonalMailProviderId, type PgModule, type PipelineHook, type PlatformSignIn, type PluginOption, type PluginRef, type PngIcon, type ProtectedFunctionOptions, type PublicFunctionContext, type PublicFunctionEnv, type PublicFunctionHandler, type PublicFunctionOptions, type PushAnswer, type PushMessage, PushMessageError, type PushSender, type QueryOptions, type QueryResult, type ReadableResources, type RealtimeOptions, type RealtimePrune, type RealtimeRelayOptions, type RealtimeRelaySettings, type ReasoningDetail, type ReasoningEffort, type RebindOption, type RecordGroups, type RecordKey, type RecordKeyInput, type RecordPage, type RelayChannelOptions, type RelayClientEvent, type RelayDevice, type RelayListedMembers, type RelayMembers, type RelayPresence, type RelayResult, type RelaySendAnswer, type RelaySendRequest, type RelaySettings, type RenderedEmail, type RenderedTemplate, type ResourceChange, type ResourceSource, type RoleDefinition, type RolesInput, type RunContext, type RuntimeOptions, type S3Bucket, type S3FilesOptions, type S3ListPage, type S3Object, type ScanGuardMode, type ScheduledDelete, type SendNotification, SenderAddressError, type SenderAddressErrorCode, SenderAddressNotFoundError, type SenderAddressState, type SenderAddressVerifier, type SentMail, type Session, type SessionOrganization, type Sharp, type SignInPolicy, type SignInRule, type SignatureOptions, type SocketEvents, type SourceOption, type SourceRef, type StaffAccessRule, type StaffSignIn, type StandardSchema, type StandardWebhookOptions, type StartJobsOptions, type StartWorkflowOptions, type StatusOptions, type StoreFileInput, type StoredMember, type StoredNotification, type StoredObject, type StoredOrganization, type StoredUser, type StrayValues, type SubscriptionDefinition, type SubscriptionEvent, type SubscriptionOptions, type TcpBridge, type TcpBridgeOptions, TemplateDataError, type TemplateOptions, type TemplateSchema, type TemplateScope, type TemplateSendOptions, type TemplateText, type TenantValue, type ToolAnnotations, type ToolCall, type ToolComment, type ToolCommentPage, type ToolComments, type ToolContext, type ToolRecord, type ToolRecords, type ToolSpec, type TrustedApp, type TurnOptions, type UnreadableEntry, type UnsubscribeLinks, type Urgency, type User, type UserCreatedHook, type UserTables, type UsersCursor, type UsersPage, type VapidSettings, type VerificationInput, type VerificationMessage, type VerificationOutcome, type VerifyInput, type VerifyTools, type ViewSource, type WebPushFields, type WebPushOptions, type WebhooksOptions, type WidgetOptions, type WorkflowCatalog, type WorkflowTypes, type WorkflowsOptions, type WriteEvent, type WriteOperation, type WriteRecordToolsInput, addAppRoleToOwners, addCommentTool, addEveryUser, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, apnsKeyIdVariable, apnsKeyVariable, apnsSender, apnsTeamIdVariable, appNameOver, appRelayChannels, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, bridgeClosings, callsMigration, capSocketMessages, capturedBy, changesMigration, channelSendsMigration, checkAi, checkAuthSchema, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkJobsSchema, checkMailFeedbackSchema, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkRelayOptions, checkRelaySchema, checkResourcesOutsideAuthStore, checkSourceNames, checkStatusSchema, checkUnsubscribesSchema, checkUserTablesSchema, checkViewQueries, checkWebhooksSchema, checkWorkflowsSchema, coalesce, commentTools, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, countRecordsTool, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultRelayChannels, defaultSignInPolicy, defineEmail, defineFunction, defineJob, definePdf, defineTemplate, defineTool, deleteRecordTool, deleteUser, derivedMigration, describeResourceTool, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fcmSender, fcmServiceAccountVariable, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, gmailSettingsScope, goTruePath, handleDroppedConnections, hasBuckets, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, hookPath, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isMailTemplate, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listCommentsTool, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mailFeedbackHeaders, mailFeedbackMigration, mailFeedbackResource, mailFeedbackSecret, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxRelayDevices, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpIcons, mcpInstructions, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, onDoNotDisturb, organizationsPageSize, overSignIn, ownedDefinitionsMigration, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readApnsSettings, readDbConnections, readDefinitionsVersion, readFcmSettings, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIns, readRecordTools, readRelaySettings, readRelaySwitch, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, realtimeRelayMigration, realtimeSwitchVariable, realtimeVariables, recordBlocksOf, recordOf, redactHookKeys, refusalOf, refused, relayClientEvents, relayCredentialVariable, relayHandle, relayMigration, relayPresencePath, relayResults, relaySendAnswer, relaySendPath, relaySendRequest, relaySender, relaySettings, relayUrlVariable, relayed, releaseConnectionsWithUsers, reloadingAdmin, removeDevicesWithUsers, removeHistoryWithUsers, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, seesAssistant, seesRuntime, sendNotification, sessionOf, setMemberRoles, setUserBanned, setUserRole, shownAppName, signInPolicyMethods, socketMessageCapOf, sourceOptions, sourcesFor, sourcesVariable, sqlSends, startErrorReporting, startJobs, startWorkflow, statusMigration, statusNames, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, tcpBridge, thumbHash, typingResources, unauthorized, unsubscribesMigration, updateRecordTool, urgencies, userTableResources, userTablesMigration, usersPageSize, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhookIssuePath, webhookParams, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, workflowInstructions, workflowReadTools, workflowTypes, workflowWriteTools, workflowsMigration, writeRecordTools };
|
package/dist/index.js
CHANGED
|
@@ -107,6 +107,7 @@ import { webPushSender } from "./notifications/web-push/web-push-sender.js";
|
|
|
107
107
|
import { notificationSenders } from "./notifications/senders-of.js";
|
|
108
108
|
import { onDoNotDisturb } from "./status/do-not-disturb.js";
|
|
109
109
|
import { statusNames } from "./status/options.js";
|
|
110
|
+
import { appRelayChannels, defaultRelayChannels } from "./relay/realtime-channels.js";
|
|
110
111
|
import { checkRelayOptions, realtimeVariables, relaySettings } from "./relay/relay-options.js";
|
|
111
112
|
import { readRelaySwitch, realtimeSwitchVariable } from "./relay/relay-switch.js";
|
|
112
113
|
import { relayPresencePath } from "./relay/presence-route.js";
|
|
@@ -176,4 +177,4 @@ import { defineEmail } from "./mail/define-email.js";
|
|
|
176
177
|
import { definePdf } from "./pdf/define-pdf.js";
|
|
177
178
|
import { startJobs } from "./jobs/runtime.js";
|
|
178
179
|
import { jobsDrainApp } from "./jobs/drain-route.js";
|
|
179
|
-
export { BulkMailError, ConnectionsBusy, DeviceStoreError, FatalJobError, HistoryStoreError, HttpProblem, MailSenderRefusedError, MailServerTimeoutError, MissingCredentials, ModelError, NotificationSendError, PersonalMailError, PushMessageError, SenderAddressError, SenderAddressNotFoundError, TemplateDataError, addAppRoleToOwners, addCommentTool, addEveryUser, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, apnsKeyIdVariable, apnsKeyVariable, apnsSender, apnsTeamIdVariable, appNameOver, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, bridgeClosings, callsMigration, capSocketMessages, capturedBy, changesMigration, channelSendsMigration, checkAi, checkAuthSchema, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkJobsSchema, checkMailFeedbackSchema, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkRelayOptions, checkRelaySchema, checkResourcesOutsideAuthStore, checkSourceNames, checkStatusSchema, checkUnsubscribesSchema, checkUserTablesSchema, checkViewQueries, checkWebhooksSchema, checkWorkflowsSchema, coalesce, commentTools, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, countRecordsTool, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultSignInPolicy, defineEmail, defineFunction, defineJob, definePdf, defineTemplate, defineTool, deleteRecordTool, deleteUser, derivedMigration, describeResourceTool, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fcmSender, fcmServiceAccountVariable, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, gmailSettingsScope, goTruePath, handleDroppedConnections, hasBuckets, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, hookPath, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isMailTemplate, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listCommentsTool, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mailFeedbackHeaders, mailFeedbackMigration, mailFeedbackResource, mailFeedbackSecret, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxRelayDevices, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpIcons, mcpInstructions, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, onDoNotDisturb, organizationsPageSize, overSignIn, ownedDefinitionsMigration, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readApnsSettings, readDbConnections, readDefinitionsVersion, readFcmSettings, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIns, readRecordTools, readRelaySettings, readRelaySwitch, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, realtimeRelayMigration, realtimeSwitchVariable, realtimeVariables, recordBlocksOf, recordOf, redactHookKeys, refusalOf, refused, relayClientEvents, relayCredentialVariable, relayHandle, relayMigration, relayPresencePath, relayResults, relaySendAnswer, relaySendPath, relaySendRequest, relaySender, relaySettings, relayUrlVariable, relayed, releaseConnectionsWithUsers, reloadingAdmin, removeDevicesWithUsers, removeHistoryWithUsers, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, seesAssistant, seesRuntime, sendNotification, sessionOf, setMemberRoles, setUserBanned, setUserRole, shownAppName, signInPolicyMethods, socketMessageCapOf, sourceOptions, sourcesFor, sourcesVariable, sqlSends, startErrorReporting, startJobs, startWorkflow, statusMigration, statusNames, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, tcpBridge, thumbHash, typingResources, unauthorized, unsubscribesMigration, updateRecordTool, urgencies, userTableResources, userTablesMigration, usersPageSize, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhookIssuePath, webhookParams, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, workflowInstructions, workflowReadTools, workflowTypes, workflowWriteTools, workflowsMigration, writeRecordTools };
|
|
180
|
+
export { BulkMailError, ConnectionsBusy, DeviceStoreError, FatalJobError, HistoryStoreError, HttpProblem, MailSenderRefusedError, MailServerTimeoutError, MissingCredentials, ModelError, NotificationSendError, PersonalMailError, PushMessageError, SenderAddressError, SenderAddressNotFoundError, TemplateDataError, addAppRoleToOwners, addCommentTool, addEveryUser, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, apnsKeyIdVariable, apnsKeyVariable, apnsSender, apnsTeamIdVariable, appNameOver, appRelayChannels, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, bridgeClosings, callsMigration, capSocketMessages, capturedBy, changesMigration, channelSendsMigration, checkAi, checkAuthSchema, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkJobsSchema, checkMailFeedbackSchema, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkRelayOptions, checkRelaySchema, checkResourcesOutsideAuthStore, checkSourceNames, checkStatusSchema, checkUnsubscribesSchema, checkUserTablesSchema, checkViewQueries, checkWebhooksSchema, checkWorkflowsSchema, coalesce, commentTools, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, countRecordsTool, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultRelayChannels, defaultSignInPolicy, defineEmail, defineFunction, defineJob, definePdf, defineTemplate, defineTool, deleteRecordTool, deleteUser, derivedMigration, describeResourceTool, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fcmSender, fcmServiceAccountVariable, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, gmailSettingsScope, goTruePath, handleDroppedConnections, hasBuckets, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, hookPath, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isMailTemplate, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listCommentsTool, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mailFeedbackHeaders, mailFeedbackMigration, mailFeedbackResource, mailFeedbackSecret, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxRelayDevices, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpIcons, mcpInstructions, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, onDoNotDisturb, organizationsPageSize, overSignIn, ownedDefinitionsMigration, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readApnsSettings, readDbConnections, readDefinitionsVersion, readFcmSettings, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIns, readRecordTools, readRelaySettings, readRelaySwitch, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, realtimeRelayMigration, realtimeSwitchVariable, realtimeVariables, recordBlocksOf, recordOf, redactHookKeys, refusalOf, refused, relayClientEvents, relayCredentialVariable, relayHandle, relayMigration, relayPresencePath, relayResults, relaySendAnswer, relaySendPath, relaySendRequest, relaySender, relaySettings, relayUrlVariable, relayed, releaseConnectionsWithUsers, reloadingAdmin, removeDevicesWithUsers, removeHistoryWithUsers, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, seesAssistant, seesRuntime, sendNotification, sessionOf, setMemberRoles, setUserBanned, setUserRole, shownAppName, signInPolicyMethods, socketMessageCapOf, sourceOptions, sourcesFor, sourcesVariable, sqlSends, startErrorReporting, startJobs, startWorkflow, statusMigration, statusNames, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, tcpBridge, thumbHash, typingResources, unauthorized, unsubscribesMigration, updateRecordTool, urgencies, userTableResources, userTablesMigration, usersPageSize, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhookIssuePath, webhookParams, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, workflowInstructions, workflowReadTools, workflowTypes, workflowWriteTools, workflowsMigration, writeRecordTools };
|
package/dist/package.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { hasMembers } from "./relay-models.js";
|
|
1
2
|
import { peopleChannel } from "./presence-commands.js";
|
|
2
3
|
//#region src/relay/change-commands.ts
|
|
3
4
|
/** The event every notice of a change is published as. */
|
|
@@ -11,9 +12,9 @@ const channelsOf = (models, resource, record) => (models.placements.get(resource
|
|
|
11
12
|
/** The channels a change is noticed on: where the record was and where it is, each once. */
|
|
12
13
|
const noticedChannels = (models, change) => [.../* @__PURE__ */ new Set([...channelsOf(models, change.resource, change.before), ...channelsOf(models, change.resource, change.after)])];
|
|
13
14
|
/** The channels with members whose people a batch's notices go to, which `channelMembers` reads. */
|
|
14
|
-
const audienceChannels = (models, changes) => [...new Set(changes.flatMap((change) => noticedChannels(models, change)))].filter((channel) => models.channels.get(channel.slice(0, channel.indexOf("/")))
|
|
15
|
+
const audienceChannels = (models, changes) => [...new Set(changes.flatMap((change) => noticedChannels(models, change)))].filter((channel) => hasMembers(models.channels.get(channel.slice(0, channel.indexOf("/")))));
|
|
15
16
|
/** The open channels, without members, that a batch's notices go to everyone joined to, whose records `publicChannels` reads. */
|
|
16
|
-
const openChannels = (models, changes) => [...new Set(changes.flatMap((change) => noticedChannels(models, change)))].filter((channel) => !models.channels.get(channel.slice(0, channel.indexOf("/")))
|
|
17
|
+
const openChannels = (models, changes) => [...new Set(changes.flatMap((change) => noticedChannels(models, change)))].filter((channel) => !hasMembers(models.channels.get(channel.slice(0, channel.indexOf("/")))));
|
|
17
18
|
const membership = (members, record) => {
|
|
18
19
|
if (!record || !present(record[members.field]) || !present(record[members.user])) return;
|
|
19
20
|
if (members.model.softDelete !== void 0 && present(record[members.model.softDelete])) return;
|
|
@@ -37,6 +38,35 @@ const membersCommands = (models, change) => (models.members.get(change.resource)
|
|
|
37
38
|
users: [before.user]
|
|
38
39
|
}] : []];
|
|
39
40
|
});
|
|
41
|
+
const listedIn = (listed, record) => {
|
|
42
|
+
if (!record) return;
|
|
43
|
+
const value = record[listed.field];
|
|
44
|
+
const deleted = listed.model.softDelete !== void 0 && present(record[listed.model.softDelete]);
|
|
45
|
+
const users = Array.isArray(value) && !deleted ? value.filter(present).map(String) : [];
|
|
46
|
+
return {
|
|
47
|
+
channel: channelName(listed.model.name, record[listed.model.primaryKey[0]]),
|
|
48
|
+
users: new Set(users)
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
const missing = (from, other) => [...from ?? []].filter((user) => !other?.has(user));
|
|
52
|
+
const listedCommands = (models, change) => {
|
|
53
|
+
const listed = models.channels.get(change.resource)?.listed;
|
|
54
|
+
if (!listed) return [];
|
|
55
|
+
const before = change.operation === "create" || change.operation === "undelete" ? void 0 : listedIn(listed, change.before);
|
|
56
|
+
const after = change.operation === "delete" ? void 0 : listedIn(listed, change.after);
|
|
57
|
+
const moved = before && after && before.channel !== after.channel;
|
|
58
|
+
const added = after ? missing(after.users, moved ? void 0 : before?.users) : [];
|
|
59
|
+
const removed = before ? missing(before.users, moved ? void 0 : after?.users) : [];
|
|
60
|
+
return [...added.length > 0 ? [{
|
|
61
|
+
kind: "add",
|
|
62
|
+
channel: after.channel,
|
|
63
|
+
users: added
|
|
64
|
+
}] : [], ...removed.length > 0 ? [{
|
|
65
|
+
kind: "remove",
|
|
66
|
+
channel: before.channel,
|
|
67
|
+
users: removed
|
|
68
|
+
}] : []];
|
|
69
|
+
};
|
|
40
70
|
const mentionsOf = (record, field) => {
|
|
41
71
|
if (field === void 0 || !record) return;
|
|
42
72
|
const value = record[field];
|
|
@@ -47,7 +77,7 @@ const notice = (models, change, channel, members, moved) => {
|
|
|
47
77
|
const options = models.channels.get(channel.slice(0, channel.indexOf("/")));
|
|
48
78
|
const mentions = mentionsOf(change.after ?? change.before, options.mentions);
|
|
49
79
|
const extra = moved.filter((command) => command.channel === channel).flatMap((command) => command.users);
|
|
50
|
-
const users = options
|
|
80
|
+
const users = hasMembers(options) ? [.../* @__PURE__ */ new Set([...members.get(channel) ?? [], ...extra])] : void 0;
|
|
51
81
|
return {
|
|
52
82
|
kind: "publish",
|
|
53
83
|
id: `${change.sequence}:${channel}`,
|
|
@@ -80,7 +110,7 @@ const reaches = (command, open) => command.users === void 0 ? open.has(command.c
|
|
|
80
110
|
* it before hear nothing once it is not. A notice of a channel with no one to reach is left out.
|
|
81
111
|
*/
|
|
82
112
|
const changeCommands = (models, changes, members, open) => changes.flatMap((change) => {
|
|
83
|
-
const moved = membersCommands(models, change);
|
|
113
|
+
const moved = [...membersCommands(models, change), ...listedCommands(models, change)];
|
|
84
114
|
const notices = noticedChannels(models, change).map((channel) => notice(models, change, channel, members, moved)).filter((command) => reaches(command, open));
|
|
85
115
|
return [
|
|
86
116
|
...moved.filter((command) => command.kind === "add").flatMap((add) => [add, joinedCommand(change.sequence, add)]),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RelayChannelOptions } from "./relay-options.js";
|
|
2
2
|
import { ViewModel } from "@protobase/schema";
|
|
3
3
|
//#region src/relay/client-events.d.ts
|
|
4
4
|
/** The resources whose conversation page has `typing`, so their channels carry the typing event. */
|
|
@@ -8,7 +8,7 @@ export declare const typingResources: (views: readonly ViewModel[]) => Set<strin
|
|
|
8
8
|
* conversation page types unless the resource declares a `typing` of its own, in the relay's field names. Undefined
|
|
9
9
|
* when no channel has an event, so clients send nothing.
|
|
10
10
|
*/
|
|
11
|
-
export declare const relayClientEvents: (channels:
|
|
11
|
+
export declare const relayClientEvents: (channels: Record<string, RelayChannelOptions>, typing: ReadonlySet<string>) => {
|
|
12
12
|
channels: {
|
|
13
13
|
[k: string]: {
|
|
14
14
|
readonly events: {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { quoteIdent, tableSql } from "../changes/capture-sql.js";
|
|
2
2
|
import { channelName } from "./change-commands.js";
|
|
3
|
+
import { listedAudience, listedCoMembers, listedMemberships, listedResources } from "./realtime-members-reads.js";
|
|
3
4
|
import { sql } from "kysely";
|
|
4
5
|
//#region src/relay/members-sql.ts
|
|
5
6
|
const column = (members, field) => sql.raw(quoteIdent(members.model.fields[field].column));
|
|
@@ -8,8 +9,9 @@ const live = (members) => {
|
|
|
8
9
|
return field === void 0 ? sql`true` : sql`${column(members, field)} is null`;
|
|
9
10
|
};
|
|
10
11
|
/**
|
|
11
|
-
* The members of the named channels as the members tables hold them now, one query for each
|
|
12
|
-
*
|
|
12
|
+
* The members of the named channels as the members tables and `realtime.members` hold them now, one query for each
|
|
13
|
+
* channel resource with a members resource and one for those whose records list their members, in the caller's
|
|
14
|
+
* transaction: what the dispatch's notices go to. A members resource's relation column needs an index.
|
|
13
15
|
*/
|
|
14
16
|
const channelMembers = async (db, models, channels) => {
|
|
15
17
|
const found = /* @__PURE__ */ new Map();
|
|
@@ -18,6 +20,17 @@ const channelMembers = async (db, models, channels) => {
|
|
|
18
20
|
const resource = channel.slice(0, channel.indexOf("/"));
|
|
19
21
|
byResource.set(resource, [...byResource.get(resource) ?? [], channel]);
|
|
20
22
|
}
|
|
23
|
+
const listed = [...byResource].filter(([resource]) => models.channels.get(resource)?.listed);
|
|
24
|
+
if (listed.length > 0) {
|
|
25
|
+
const { rows } = await listedAudience(listed.map(([resource, named]) => ({
|
|
26
|
+
resource,
|
|
27
|
+
keys: named.map((channel) => channel.slice(resource.length + 1))
|
|
28
|
+
}))).execute(db);
|
|
29
|
+
for (const row of rows) {
|
|
30
|
+
const channel = channelName(row.resource, row.channel);
|
|
31
|
+
found.set(channel, [...found.get(channel) ?? [], row.user]);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
21
34
|
for (const [resource, named] of byResource) {
|
|
22
35
|
const members = models.channels.get(resource)?.members;
|
|
23
36
|
if (!members) continue;
|
|
@@ -31,9 +44,17 @@ const channelMembers = async (db, models, channels) => {
|
|
|
31
44
|
}
|
|
32
45
|
return found;
|
|
33
46
|
};
|
|
34
|
-
/**
|
|
47
|
+
/**
|
|
48
|
+
* The channels with members that the person is in: one query for each channel resource with a members resource, whose
|
|
49
|
+
* user column needs an index, and one of `realtime.members` for those whose records list their members.
|
|
50
|
+
*/
|
|
35
51
|
const memberships = async (db, models, user) => {
|
|
36
52
|
const channels = [];
|
|
53
|
+
const listed = listedResources(models);
|
|
54
|
+
if (listed.length > 0) {
|
|
55
|
+
const { rows } = await listedMemberships(listed, user).execute(db);
|
|
56
|
+
channels.push(...rows.map((row) => channelName(row.resource, row.channel)));
|
|
57
|
+
}
|
|
37
58
|
for (const [resource, { members }] of models.channels) {
|
|
38
59
|
if (!members) continue;
|
|
39
60
|
const { rows } = await sql`select distinct ${column(members, members.field)} as channel
|
|
@@ -49,15 +70,17 @@ const liveAs = (alias, members) => {
|
|
|
49
70
|
};
|
|
50
71
|
/**
|
|
51
72
|
* By person, everyone who shares a channel with members with them, themselves included, in one query over every
|
|
52
|
-
* members table
|
|
73
|
+
* members table and `realtime.members`, in the caller's transaction: who hears of their presence. Its user and
|
|
74
|
+
* relation columns need indexes.
|
|
53
75
|
*/
|
|
54
76
|
const coMembers = async (db, models, people) => {
|
|
55
77
|
const found = /* @__PURE__ */ new Map();
|
|
56
78
|
const tables = [...models.channels.values()].flatMap(({ members }) => members ? [members] : []);
|
|
57
|
-
|
|
58
|
-
|
|
79
|
+
const listed = listedResources(models);
|
|
80
|
+
if (people.length === 0 || tables.length === 0 && listed.length === 0) return found;
|
|
81
|
+
const pairs = [...listed.length > 0 ? [listedCoMembers(listed, people)] : [], ...tables.map((members) => sql`select ${aliased("a", members, members.user)}::text as person, ${aliased("b", members, members.user)}::text as other
|
|
59
82
|
from ${sql.raw(tableSql(members.model))} a join ${sql.raw(tableSql(members.model))} b on ${aliased("b", members, members.field)} = ${aliased("a", members, members.field)}
|
|
60
|
-
where ${aliased("a", members, members.user)} = any(${people}) and ${liveAs("a", members)} and ${liveAs("b", members)}`);
|
|
83
|
+
where ${aliased("a", members, members.user)} = any(${people}) and ${liveAs("a", members)} and ${liveAs("b", members)}`)];
|
|
61
84
|
const { rows } = await sql`${sql.join(pairs, sql` union `)}`.execute(db);
|
|
62
85
|
for (const row of rows) found.set(row.person, [...found.get(row.person) ?? [], row.other]);
|
|
63
86
|
return found;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { RealtimeRelayOptions, RelayChannelOptions } from "./relay-options.js";
|
|
2
|
+
import { ResourceModel, ViewModel } from "@protobase/schema";
|
|
3
|
+
//#region src/relay/realtime-channels.d.ts
|
|
4
|
+
/** What the relay's channels are derived from: the app's views and resources, and whether it has its own sign-in. */
|
|
5
|
+
export type RelayApp = {
|
|
6
|
+
views: readonly ViewModel[];
|
|
7
|
+
models: readonly ResourceModel[];
|
|
8
|
+
signIn: boolean;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* The relay's channels an app gets without declaring them: one for each resource whose conversation page has
|
|
12
|
+
* `members`, a JSON field of user ids on the record, with that field as its members, when its changes are captured,
|
|
13
|
+
* such as with `.live()`, so the relay hears who joins and leaves, its key is one field and the field's changes are
|
|
14
|
+
* captured (`listedFieldProblem`). A page without `members` gives none, as a channel without members would be open.
|
|
15
|
+
* Views of one resource that list members in different fields stop it: the channel takes one.
|
|
16
|
+
*/
|
|
17
|
+
export declare const defaultRelayChannels: ({ views, models }: Pick<RelayApp, "views" | "models">) => Record<string, RelayChannelOptions>;
|
|
18
|
+
/**
|
|
19
|
+
* The channels of the relay the app uses or can be moved to: `realtime.relay`'s, else the defaults. Undefined when the
|
|
20
|
+
* app cannot use the relay: no `realtime.relay`, and no sign-in, whose sessions tickets name, or no default channel.
|
|
21
|
+
* It decides whether `protobase migration` writes the relay's part, the build's manifest entry, and what the
|
|
22
|
+
* platform's switch turns on.
|
|
23
|
+
*/
|
|
24
|
+
export declare const appRelayChannels: (declared: RealtimeRelayOptions | undefined, app: RelayApp) => Record<string, RelayChannelOptions> | undefined;
|
|
25
|
+
//#endregion
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { capturedBy } from "../changes/capture-sql.js";
|
|
2
|
+
import { listedFieldProblem } from "./relay-models.js";
|
|
3
|
+
//#region src/relay/realtime-channels.ts
|
|
4
|
+
/**
|
|
5
|
+
* The relay's channels an app gets without declaring them: one for each resource whose conversation page has
|
|
6
|
+
* `members`, a JSON field of user ids on the record, with that field as its members, when its changes are captured,
|
|
7
|
+
* such as with `.live()`, so the relay hears who joins and leaves, its key is one field and the field's changes are
|
|
8
|
+
* captured (`listedFieldProblem`). A page without `members` gives none, as a channel without members would be open.
|
|
9
|
+
* Views of one resource that list members in different fields stop it: the channel takes one.
|
|
10
|
+
*/
|
|
11
|
+
const defaultRelayChannels = ({ views, models }) => {
|
|
12
|
+
const captured = capturedBy(models);
|
|
13
|
+
const byName = new Map(models.map((model) => [model.name, model]));
|
|
14
|
+
const fields = /* @__PURE__ */ new Map();
|
|
15
|
+
for (const view of views) {
|
|
16
|
+
const page = view.record;
|
|
17
|
+
if (!page || !("conversation" in page) || page.conversation.members === void 0) continue;
|
|
18
|
+
const model = byName.get(view.resource);
|
|
19
|
+
if (!model || !captured(model) || model.primaryKey.length !== 1 || listedFieldProblem(model, page.conversation.members)) continue;
|
|
20
|
+
const other = fields.get(view.resource);
|
|
21
|
+
if (other !== void 0 && other !== page.conversation.members) throw new Error(`Views of "${view.resource}": their conversation pages list members in "${other}" and "${page.conversation.members}", but the relay's channel on "${view.resource}" takes one members field`);
|
|
22
|
+
fields.set(view.resource, page.conversation.members);
|
|
23
|
+
}
|
|
24
|
+
return Object.fromEntries([...fields].map(([resource, field]) => [resource, { members: { field } }]));
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The channels of the relay the app uses or can be moved to: `realtime.relay`'s, else the defaults. Undefined when the
|
|
28
|
+
* app cannot use the relay: no `realtime.relay`, and no sign-in, whose sessions tickets name, or no default channel.
|
|
29
|
+
* It decides whether `protobase migration` writes the relay's part, the build's manifest entry, and what the
|
|
30
|
+
* platform's switch turns on.
|
|
31
|
+
*/
|
|
32
|
+
const appRelayChannels = (declared, app) => {
|
|
33
|
+
if (declared) return declared.channels ?? defaultRelayChannels(app);
|
|
34
|
+
if (!app.signIn) return;
|
|
35
|
+
const derived = defaultRelayChannels(app);
|
|
36
|
+
return Object.keys(derived).length > 0 ? derived : void 0;
|
|
37
|
+
};
|
|
38
|
+
//#endregion
|
|
39
|
+
export { appRelayChannels, defaultRelayChannels };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { realtimeMembersTable } from "./realtime-members-sql.js";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
//#region src/relay/realtime-members-reads.ts
|
|
4
|
+
const members = sql.raw(realtimeMembersTable);
|
|
5
|
+
/** The channel resources whose records list their members, which `realtime.members` holds. */
|
|
6
|
+
const listedResources = (models) => [...models.channels].flatMap(([resource, channel]) => channel.listed ? [resource] : []);
|
|
7
|
+
/** Who is in the named channels of each resource, by the table's key. */
|
|
8
|
+
const listedAudience = (named) => sql`${sql.join(named.map(({ resource, keys }) => sql`select resource, channel_key as channel, user_id as "user" from ${members} where resource = ${resource} and channel_key = any(${keys}::text[])`), sql` union all `)}`;
|
|
9
|
+
/** The channels of these resources the person is in, by the index by person. */
|
|
10
|
+
const listedMemberships = (resources, user) => sql`select resource, channel_key as channel from ${members} where user_id = ${user} and resource = any(${resources}::text[])`;
|
|
11
|
+
/** Each of these people with everyone who shares a channel of these resources with them, themselves included. */
|
|
12
|
+
const listedCoMembers = (resources, people) => sql`select a.user_id as person, b.user_id as other from ${members} a
|
|
13
|
+
join ${members} b on b.resource = a.resource and b.channel_key = a.channel_key
|
|
14
|
+
where a.user_id = any(${people}::text[]) and a.resource = any(${resources}::text[])`;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { listedAudience, listedCoMembers, listedMemberships, listedResources };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { argsOf, membersComment, membersSql, realtimeMembersTable, realtimeSchema, rowTrigger, truncateTrigger } from "./realtime-members-sql.js";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
//#region src/relay/realtime-members-schema.ts
|
|
4
|
+
const storedArgs = (args) => Buffer.from(args.map((arg) => `${arg}\0`).join(""), "utf8").toString("hex");
|
|
5
|
+
/**
|
|
6
|
+
* Refuses channel tables that are partitions, or that inherit or are inherited from other than by partitioning: their
|
|
7
|
+
* rows are written through a table the triggers do not stand on. A partitioned channel table is kept (see `membersSql`).
|
|
8
|
+
*/
|
|
9
|
+
const refuseInherited = (tables) => {
|
|
10
|
+
if (tables.length === 0) return;
|
|
11
|
+
throw new Error(`realtime.members cannot keep the members of ${tables.join(", ")}: a partition or a table in an inheritance tree is not supported as a channel resource whose records list their members; use the partitioned table itself`);
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The listed tables as the database has them: each one and its partitions as SQL names them, and whether
|
|
15
|
+
* it is refused (`refuseInherited`); and whether the members table exists.
|
|
16
|
+
*/
|
|
17
|
+
const listedTables = async (db, listed) => {
|
|
18
|
+
const { rows } = await sql`select name,
|
|
19
|
+
to_regclass(name)::text as rel, to_regclass(${realtimeMembersTable}) is not null as members,
|
|
20
|
+
exists (select from pg_class c where c.oid = to_regclass(name) and (c.relispartition or (c.relkind <> 'p' and exists (select from pg_inherits i where i.inhrelid = c.oid or i.inhparent = c.oid)))) as inherited,
|
|
21
|
+
array(select tree.relid::regclass::text from pg_partition_tree(to_regclass(name)) as tree where tree.relid <> to_regclass(name) order by tree.relid::regclass::text) as partitions
|
|
22
|
+
from unnest(${listed.map(({ table }) => table)}::text[]) with ordinality as listed(name, place) order by place`.execute(db);
|
|
23
|
+
refuseInherited(rows.filter((row) => row.inherited).map((row) => row.name));
|
|
24
|
+
return rows;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Whether the triggers of this version stand on exactly the listed tables with their args, a truncate trigger on each
|
|
28
|
+
* of their partitions too, each firing on every write (enabled, not only for replicas), as must the clones of the row
|
|
29
|
+
* trigger Postgres keeps on the partitions, and the members table exists; the tables, as SQL names them, with any of
|
|
30
|
+
* them but clones; and the partitions of each listed table. A partition attached later lacks its truncate trigger, so
|
|
31
|
+
* startup asks for the migration that writes them all again.
|
|
32
|
+
*/
|
|
33
|
+
const standingTriggers = async (db, listed) => {
|
|
34
|
+
const tables = await listedTables(db, listed);
|
|
35
|
+
const { rows } = await sql`select t.tgname as name,
|
|
36
|
+
encode(t.tgargs, 'hex') as args, coalesce(obj_description(p.oid, 'pg_proc') = ${membersComment}, false) as current, t.tgenabled in ('O', 'A') as enabled,
|
|
37
|
+
t.tgparentid <> 0 as clone, t.tgrelid::regclass::text as "table"
|
|
38
|
+
from pg_trigger t join pg_proc p on p.oid = t.tgfoid join pg_namespace n on n.oid = p.pronamespace
|
|
39
|
+
where n.nspname = ${realtimeSchema} and p.proname = 'members_kept'`.execute(db);
|
|
40
|
+
const roots = rows.filter((row) => !row.clone);
|
|
41
|
+
const expected = listed.flatMap((table, i) => {
|
|
42
|
+
const { rel, partitions } = tables[i];
|
|
43
|
+
const args = storedArgs(argsOf(table));
|
|
44
|
+
return [`${rel}|${rowTrigger}|${args}`, ...[rel, ...partitions].map((on) => `${on}|${truncateTrigger}|${args}`)];
|
|
45
|
+
});
|
|
46
|
+
const found = roots.map((row) => `${row.table}|${row.name}|${row.args}`);
|
|
47
|
+
const exact = expected.length === found.length && expected.every((entry) => found.includes(entry)) && rows.every((row) => row.current && row.enabled);
|
|
48
|
+
const membersTable = listed.length === 0 || tables.every((row) => row.members && row.rel !== null);
|
|
49
|
+
return {
|
|
50
|
+
current: exact && membersTable,
|
|
51
|
+
standing: [...new Set(roots.map((row) => row.table))],
|
|
52
|
+
partitions: tables.map((row) => row.partitions)
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
/** The SQL that keeps `realtime.members` for the listed tables (`membersSql`); `undefined` when it is current. */
|
|
56
|
+
const realtimeMembersMigration = async (db, listed) => {
|
|
57
|
+
const { current, standing, partitions } = await standingTriggers(db, listed);
|
|
58
|
+
if (current) return;
|
|
59
|
+
return `${membersSql(listed, standing, partitions).join(";\n\n")};`;
|
|
60
|
+
};
|
|
61
|
+
/** Refuses to start while `realtime.members` would not follow the listed tables' members. */
|
|
62
|
+
const checkRealtimeMembers = async (db, listed, command) => {
|
|
63
|
+
if ((await standingTriggers(db, listed)).current) return;
|
|
64
|
+
throw new Error(`The realtime.members table, or the triggers that keep it on ${listed.map(({ table }) => table).join(", ")} and their partitions, is missing or out of date. Write it as a migration with \`${command}\`, apply it with the project's migrations, then start again.`);
|
|
65
|
+
};
|
|
66
|
+
//#endregion
|
|
67
|
+
export { checkRealtimeMembers, realtimeMembersMigration, refuseInherited };
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { tableSql } from "../changes/capture-sql.js";
|
|
2
|
+
//#region src/relay/realtime-members-sql.ts
|
|
3
|
+
/** The schema of the framework's realtime tables. */
|
|
4
|
+
const realtimeSchema = "realtime";
|
|
5
|
+
/** Who is in each channel whose record lists its members, one row for each person in each channel. */
|
|
6
|
+
const realtimeMembersTable = `${realtimeSchema}.members`;
|
|
7
|
+
const membersComment = `Protobase realtime members 3`;
|
|
8
|
+
const rowTrigger = "realtime_members";
|
|
9
|
+
const truncateTrigger = "realtime_members_truncated";
|
|
10
|
+
/** The table of a channel resource whose records list their members. */
|
|
11
|
+
const listedTable = ({ model, field }) => ({
|
|
12
|
+
resource: model.name,
|
|
13
|
+
table: tableSql(model),
|
|
14
|
+
key: model.fields[model.primaryKey[0]].column,
|
|
15
|
+
members: model.fields[field].column,
|
|
16
|
+
deleted: model.softDelete === void 0 ? "" : model.fields[model.softDelete].column
|
|
17
|
+
});
|
|
18
|
+
const literal = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
19
|
+
/**
|
|
20
|
+
* The members table, keyed by channel so a notice's audience is read by its key, with an index by person for their
|
|
21
|
+
* tickets and co-members; `listed_members`, the user ids one state of a record lists, none once soft-deleted; and the
|
|
22
|
+
* trigger function. A truncate, of the table or of one of its partitions, writes the resource's members again from the
|
|
23
|
+
* table as it stands, so a truncated partition's siblings keep theirs. After each write that changes a record's key, members or soft
|
|
24
|
+
* delete, as it stands after every trigger before it, it writes the members of the record's old and new keys again
|
|
25
|
+
* from the table: row triggers that run after the write fire once the statement wrote every row, so a statement that
|
|
26
|
+
* swaps two records' keys leaves each key with the members its record lists.
|
|
27
|
+
*/
|
|
28
|
+
const baseSql = [
|
|
29
|
+
`create schema if not exists ${realtimeSchema}`,
|
|
30
|
+
`create table if not exists ${realtimeMembersTable} (
|
|
31
|
+
resource text not null,
|
|
32
|
+
channel_key text not null,
|
|
33
|
+
user_id text not null,
|
|
34
|
+
primary key (resource, channel_key, user_id)
|
|
35
|
+
)`,
|
|
36
|
+
`create index if not exists members_by_user on ${realtimeMembersTable} (user_id, resource)`,
|
|
37
|
+
`create or replace function ${realtimeSchema}.listed_members(entry jsonb, members_column text, deleted_column text) returns setof text
|
|
38
|
+
language sql immutable as $$
|
|
39
|
+
select distinct member from jsonb_array_elements_text(
|
|
40
|
+
case when (deleted_column = '' or entry ->> deleted_column is null) and jsonb_typeof(entry -> members_column) = 'array' then entry -> members_column else '[]'::jsonb end
|
|
41
|
+
) as member where member is not null
|
|
42
|
+
$$`,
|
|
43
|
+
`create or replace function ${realtimeSchema}.members_kept() returns trigger
|
|
44
|
+
language plpgsql as $$
|
|
45
|
+
declare
|
|
46
|
+
channel_resource text := tg_argv[0];
|
|
47
|
+
key_column text := tg_argv[1];
|
|
48
|
+
members_column text := tg_argv[2];
|
|
49
|
+
deleted_column text := tg_argv[3];
|
|
50
|
+
old_entry jsonb;
|
|
51
|
+
new_entry jsonb;
|
|
52
|
+
keys text[];
|
|
53
|
+
key_type text;
|
|
54
|
+
-- The table the trigger stands on: the partitioned one for a partition's clone or truncate trigger.
|
|
55
|
+
source regclass := coalesce(pg_partition_root(tg_relid), tg_relid);
|
|
56
|
+
begin
|
|
57
|
+
if tg_op = 'TRUNCATE' then
|
|
58
|
+
delete from ${realtimeMembersTable} m where m.resource = channel_resource;
|
|
59
|
+
execute format('insert into ${realtimeMembersTable} (resource, channel_key, user_id)
|
|
60
|
+
select $1, to_jsonb(t) ->> $2, member from %s t cross join lateral ${realtimeSchema}.listed_members(to_jsonb(t), $3, $4) as member
|
|
61
|
+
on conflict do nothing', source)
|
|
62
|
+
using channel_resource, key_column, members_column, deleted_column;
|
|
63
|
+
return null;
|
|
64
|
+
end if;
|
|
65
|
+
if tg_op <> 'INSERT' then old_entry := to_jsonb(old); end if;
|
|
66
|
+
if tg_op <> 'DELETE' then new_entry := to_jsonb(new); end if;
|
|
67
|
+
if tg_op = 'UPDATE' and old_entry -> key_column is not distinct from new_entry -> key_column
|
|
68
|
+
and old_entry -> members_column is not distinct from new_entry -> members_column
|
|
69
|
+
and (deleted_column = '' or old_entry -> deleted_column is not distinct from new_entry -> deleted_column) then
|
|
70
|
+
return null;
|
|
71
|
+
end if;
|
|
72
|
+
keys := array(select distinct k from unnest(array[old_entry ->> key_column, new_entry ->> key_column]) as k where k is not null);
|
|
73
|
+
delete from ${realtimeMembersTable} m where m.resource = channel_resource and m.channel_key = any(keys);
|
|
74
|
+
select format_type(a.atttypid, a.atttypmod) into key_type from pg_attribute a where a.attrelid = source and a.attname = key_column;
|
|
75
|
+
execute format('insert into ${realtimeMembersTable} (resource, channel_key, user_id)
|
|
76
|
+
select $1, to_jsonb(t) ->> $2, member from %s t cross join lateral ${realtimeSchema}.listed_members(to_jsonb(t), $3, $4) as member
|
|
77
|
+
where t.%I = any($5::%s[]) on conflict do nothing', source, key_column, key_type)
|
|
78
|
+
using channel_resource, key_column, members_column, deleted_column, keys;
|
|
79
|
+
return null;
|
|
80
|
+
end
|
|
81
|
+
$$`,
|
|
82
|
+
`comment on function ${realtimeSchema}.members_kept() is '${membersComment}'`
|
|
83
|
+
];
|
|
84
|
+
/** The args of a listed table's row trigger, as `members_kept` reads them. */
|
|
85
|
+
const argsOf = ({ resource, key, members, deleted }) => [
|
|
86
|
+
resource,
|
|
87
|
+
key,
|
|
88
|
+
members,
|
|
89
|
+
deleted
|
|
90
|
+
];
|
|
91
|
+
/** A truncate trigger's SQL on a channel table or one of its partitions, as SQL names it. */
|
|
92
|
+
const truncateSql = (listed, on) => `create trigger ${truncateTrigger} after truncate on ${on} for each statement execute function ${realtimeSchema}.members_kept(${argsOf(listed).map(literal).join(", ")})`;
|
|
93
|
+
const listedTableSql = (listed, partitions) => {
|
|
94
|
+
const { resource, table, key, members, deleted } = listed;
|
|
95
|
+
return [
|
|
96
|
+
`create trigger ${rowTrigger} after insert or delete or update on ${table} for each row execute function ${realtimeSchema}.members_kept(${argsOf(listed).map(literal).join(", ")})`,
|
|
97
|
+
truncateSql(listed, table),
|
|
98
|
+
...partitions.map((partition) => truncateSql(listed, partition)),
|
|
99
|
+
`delete from ${realtimeMembersTable} where resource = ${literal(resource)}`,
|
|
100
|
+
`insert into ${realtimeMembersTable} (resource, channel_key, user_id)
|
|
101
|
+
select ${literal(resource)}, to_jsonb(t) ->> ${literal(key)}, member from ${table} t
|
|
102
|
+
cross join lateral ${realtimeSchema}.listed_members(to_jsonb(t), ${literal(members)}, ${literal(deleted)}) as member
|
|
103
|
+
on conflict do nothing`
|
|
104
|
+
];
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* The SQL that keeps `realtime.members` for the listed tables: the table and its functions, the triggers of every
|
|
108
|
+
* table that has them dropped (`standing`, as SQL names each), each listed table's written, a truncate trigger on each
|
|
109
|
+
* of its partitions (`partitions`, by listed table, as SQL names each) included, its rows written again
|
|
110
|
+
* from the table, and the rows of resources no longer listed deleted. Writes made while the triggers are off, such as
|
|
111
|
+
* with `session_replication_role = replica`, are not kept until the next migration that writes it.
|
|
112
|
+
*/
|
|
113
|
+
const membersSql = (listed, standing, partitions) => [
|
|
114
|
+
...baseSql,
|
|
115
|
+
...standing.flatMap((table) => [`drop trigger if exists ${rowTrigger} on ${table}`, `drop trigger if exists ${truncateTrigger} on ${table}`]),
|
|
116
|
+
...listed.flatMap((table, i) => listedTableSql(table, partitions[i] ?? [])),
|
|
117
|
+
`delete from ${realtimeMembersTable} where resource <> all(array[${listed.map(({ resource }) => literal(resource)).join(", ")}]::text[])`
|
|
118
|
+
];
|
|
119
|
+
//#endregion
|
|
120
|
+
export { argsOf, listedTable, membersComment, membersSql, realtimeMembersTable, realtimeSchema, rowTrigger, truncateTrigger };
|
package/dist/relay/relay-jobs.js
CHANGED
|
@@ -68,5 +68,13 @@ const relayJobs = ({ client, sessionEnd, report }) => {
|
|
|
68
68
|
})
|
|
69
69
|
};
|
|
70
70
|
};
|
|
71
|
+
/**
|
|
72
|
+
* The relay's jobs while the app can use the relay but does not: `relay.close-sessions`, which the delete of sign-in
|
|
73
|
+
* sessions queues all the same, completes at once, as no socket is open on the relay.
|
|
74
|
+
*/
|
|
75
|
+
const idleRelayJobs = () => [defineJob({
|
|
76
|
+
name: closeSessionsJob,
|
|
77
|
+
run: async () => {}
|
|
78
|
+
})];
|
|
71
79
|
//#endregion
|
|
72
|
-
export { relayJobs };
|
|
80
|
+
export { idleRelayJobs, relayJobs };
|
|
@@ -2,9 +2,12 @@ import { capturedBy } from "../changes/capture-sql.js";
|
|
|
2
2
|
import { presenceModel } from "./presence-model.js";
|
|
3
3
|
import { relatedTarget } from "@protobase/schema/internal";
|
|
4
4
|
//#region src/relay/relay-models.ts
|
|
5
|
+
/** Whether a channel has members, from a members resource or a field of its own, rather than being open. */
|
|
6
|
+
const hasMembers = (channel) => Boolean(channel?.members ?? channel?.listed);
|
|
5
7
|
/**
|
|
6
8
|
* The options against the models, or an error naming what does not fit: a channel resource needs a key of one field, and
|
|
7
|
-
* its members resource a captured table, such as one with `.live()`, a relation field to it and a user field
|
|
9
|
+
* its members resource a captured table, such as one with `.live()`, a relation field to it and a user field; one whose
|
|
10
|
+
* members are a field of its own is captured itself, and that field is JSON.
|
|
8
11
|
*/
|
|
9
12
|
const relayModels = (options, models) => {
|
|
10
13
|
const byName = new Map(models.map((model) => [model.name, model]));
|
|
@@ -16,7 +19,9 @@ const relayModels = (options, models) => {
|
|
|
16
19
|
const model = byName.get(name);
|
|
17
20
|
if (!model) throw new Error(`${at}: the app has no resource "${name}"`);
|
|
18
21
|
if (model.primaryKey.length !== 1) throw new Error(`${at}: a channel resource needs a key of one field, as a channel is named <resource>/<key>`);
|
|
19
|
-
const
|
|
22
|
+
const listed = channel.members && "field" in channel.members ? listedModel(channel.members.field, model, `${at}.members`) : void 0;
|
|
23
|
+
if (listed && !captured(model)) throw new Error(`${at}.members: the changes of "${name}" are not captured, so the relay would not hear who joins or leaves: declare .live() on it`);
|
|
24
|
+
const own = channel.members && !("field" in channel.members) ? membersModel(channel.members, name, byName, `${at}.members`) : void 0;
|
|
20
25
|
if (own && !captured(own.model)) throw new Error(`${at}.members: the changes of "${own.model.name}" are not captured, so the relay would not hear of them: declare .live() on it`);
|
|
21
26
|
if (own) members.set(own.model.name, [...members.get(own.model.name) ?? [], {
|
|
22
27
|
...own,
|
|
@@ -24,6 +29,7 @@ const relayModels = (options, models) => {
|
|
|
24
29
|
}]);
|
|
25
30
|
channels.set(name, {
|
|
26
31
|
...own && { members: own },
|
|
32
|
+
...listed && { listed },
|
|
27
33
|
...channel.mentions !== void 0 && { mentions: channel.mentions }
|
|
28
34
|
});
|
|
29
35
|
}
|
|
@@ -53,6 +59,24 @@ const relayModels = (options, models) => {
|
|
|
53
59
|
...options.presence && { presence: presenceModel(options.presence, byName, captured) }
|
|
54
60
|
};
|
|
55
61
|
};
|
|
62
|
+
/**
|
|
63
|
+
* Why a field cannot list a channel record's members, or undefined when it can: it is a JSON field of user ids whose
|
|
64
|
+
* every change reaches the relay, so neither sensitive, which capture leaves out of the change, nor ignored by history.
|
|
65
|
+
*/
|
|
66
|
+
const listedFieldProblem = (model, field) => {
|
|
67
|
+
const definition = model.fields[field];
|
|
68
|
+
if (definition?.type !== "json") return `"${field}" of "${model.name}" is no JSON field of user ids`;
|
|
69
|
+
if (definition.sensitive) return `"${field}" of "${model.name}" is sensitive, so its changes never reach the relay`;
|
|
70
|
+
if (model.historyIgnore?.includes(field)) return `"${field}" of "${model.name}" is ignored by its history, so its changes never reach the relay`;
|
|
71
|
+
};
|
|
72
|
+
const listedModel = (field, model, at) => {
|
|
73
|
+
const problem = listedFieldProblem(model, field);
|
|
74
|
+
if (problem) throw new Error(`${at}.field: ${problem}`);
|
|
75
|
+
return {
|
|
76
|
+
model,
|
|
77
|
+
field
|
|
78
|
+
};
|
|
79
|
+
};
|
|
56
80
|
const membersModel = (members, channel, byName, at) => {
|
|
57
81
|
const model = byName.get(members.resource);
|
|
58
82
|
if (!model) throw new Error(`${at}.resource: the app has no resource "${members.resource}"`);
|
|
@@ -66,4 +90,4 @@ const membersModel = (members, channel, byName, at) => {
|
|
|
66
90
|
};
|
|
67
91
|
};
|
|
68
92
|
//#endregion
|
|
69
|
-
export { relayModels };
|
|
93
|
+
export { hasMembers, listedFieldProblem, relayModels };
|
|
@@ -8,13 +8,22 @@ export type RelayMembers = {
|
|
|
8
8
|
/** Its field holding the person's user id, such as `user_id`. */
|
|
9
9
|
user: string;
|
|
10
10
|
};
|
|
11
|
+
/**
|
|
12
|
+
* Where a channel resource's membership comes from: a JSON field of user ids on the channel record itself, as a
|
|
13
|
+
* conversation page's `members`. Who is in each channel is kept in `realtime.members`, which `protobase migration`
|
|
14
|
+
* writes with the triggers that keep it, so tickets and notices read it by index.
|
|
15
|
+
*/
|
|
16
|
+
export type RelayListedMembers = {
|
|
17
|
+
/** The channel resource's JSON field listing its members' user ids, such as `members`. */
|
|
18
|
+
field: string;
|
|
19
|
+
};
|
|
11
20
|
/** A resource whose records are channels on the relay, `<resource>/<key>`. */
|
|
12
21
|
export type RelayChannelOptions = {
|
|
13
22
|
/**
|
|
14
23
|
* Who is in each channel. Without it the channel is open: whoever may read the record gets it in a ticket when they
|
|
15
24
|
* ask for it, a visitor of the anonymous role too.
|
|
16
25
|
*/
|
|
17
|
-
members?: RelayMembers;
|
|
26
|
+
members?: RelayMembers | RelayListedMembers;
|
|
18
27
|
/** A field of the records noticed on the channel that lists the user ids a record mentions, such as a message's `mentions`. */
|
|
19
28
|
mentions?: string;
|
|
20
29
|
/**
|
|
@@ -63,13 +72,16 @@ export type RealtimeRelayOptions = {
|
|
|
63
72
|
apiKey?: string;
|
|
64
73
|
/** One of the app's ticket keys on the relay, which signs the connect tickets. */
|
|
65
74
|
ticketKey?: string;
|
|
66
|
-
/**
|
|
67
|
-
|
|
75
|
+
/**
|
|
76
|
+
* The channel resources by name. Defaults to one for each resource whose conversation page has `members`, with that
|
|
77
|
+
* field as its members (`defaultRelayChannels`).
|
|
78
|
+
*/
|
|
79
|
+
channels?: Record<string, RelayChannelOptions>;
|
|
68
80
|
/** Turns on presence: the relay reports who is online, away or offline, and the app keeps it in this resource. */
|
|
69
81
|
presence?: RelayPresence;
|
|
70
82
|
};
|
|
71
83
|
/** `realtime.relay` with its address, id and keys, the presence key included, from the config or the environment. */
|
|
72
|
-
export type RealtimeRelaySettings = Omit<RealtimeRelayOptions, 'presence'> & Required<Pick<RealtimeRelayOptions, 'url' | 'app' | 'apiKey' | 'ticketKey'>> & {
|
|
84
|
+
export type RealtimeRelaySettings = Omit<RealtimeRelayOptions, 'presence'> & Required<Pick<RealtimeRelayOptions, 'url' | 'app' | 'apiKey' | 'ticketKey' | 'channels'>> & {
|
|
73
85
|
presence?: RelayPresence & {
|
|
74
86
|
key: string;
|
|
75
87
|
};
|
|
@@ -38,6 +38,12 @@ const checkEvents = (where, events) => {
|
|
|
38
38
|
if (!Number.isInteger(burst) || burst < 1) throw new Error(`${where}.${name}.burst must be a positive whole number`);
|
|
39
39
|
}
|
|
40
40
|
};
|
|
41
|
+
const membersShape = (members) => {
|
|
42
|
+
if (members === void 0) return true;
|
|
43
|
+
if (typeof members !== "object" || members === null) return false;
|
|
44
|
+
if ("field" in members) return nonEmpty(members.field) && Object.keys(members).length === 1;
|
|
45
|
+
return nonEmpty(members.resource) && nonEmpty(members.channel) && nonEmpty(members.user);
|
|
46
|
+
};
|
|
41
47
|
/** The options, or an error naming what is wrong with their shape; `relayModels` checks them against the resources. */
|
|
42
48
|
const checkRelayOptions = (options) => {
|
|
43
49
|
if (!nonEmpty(options?.url) || !/^https?:\/\//.test(options.url)) throw new Error(`realtime.relay.url or ${realtimeVariables.url} must start with https:// or http://, not ${JSON.stringify(options?.url)}`);
|
|
@@ -48,8 +54,7 @@ const checkRelayOptions = (options) => {
|
|
|
48
54
|
}
|
|
49
55
|
if (typeof options.channels !== "object" || options.channels === null || Object.keys(options.channels).length === 0) throw new Error("realtime.relay.channels must name at least one channel resource");
|
|
50
56
|
for (const [name, channel] of Object.entries(options.channels)) {
|
|
51
|
-
|
|
52
|
-
if (members !== void 0 && !(nonEmpty(members.resource) && nonEmpty(members.channel) && nonEmpty(members.user))) throw new Error(`realtime.relay.channels.${name}.members must be { resource, channel, user }`);
|
|
57
|
+
if (!membersShape(channel?.members)) throw new Error(`realtime.relay.channels.${name}.members must be { resource, channel, user } or { field }`);
|
|
53
58
|
if (channel?.mentions !== void 0 && !nonEmpty(channel.mentions)) throw new Error(`realtime.relay.channels.${name}.mentions must name a field`);
|
|
54
59
|
if (channel?.events !== void 0) checkEvents(`realtime.relay.channels.${name}.events`, channel.events);
|
|
55
60
|
}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { runningJobs } from "../jobs/current.js";
|
|
2
2
|
import { dispatchJobName } from "../changes/capture-sql.js";
|
|
3
3
|
import { anonymousSession } from "../anonymous.js";
|
|
4
|
+
import { relayModels } from "./relay-models.js";
|
|
5
|
+
import { relayClient } from "./relay-commands.js";
|
|
6
|
+
import { relayJobs } from "./relay-jobs.js";
|
|
4
7
|
import { readableKeys } from "../channels/records-readable.js";
|
|
5
8
|
import { presenceCommands, presencePeople } from "./presence-commands.js";
|
|
6
9
|
import { audienceChannels, changeCommands, openChannels } from "./change-commands.js";
|
|
7
10
|
import { channelMembers, coMembers } from "./members-sql.js";
|
|
8
11
|
import { presenceRoutes } from "./presence-route.js";
|
|
9
12
|
import { presenceWriter } from "./presence-sql.js";
|
|
10
|
-
import { relayClient } from "./relay-commands.js";
|
|
11
|
-
import { relayJobs } from "./relay-jobs.js";
|
|
12
|
-
import { relayModels } from "./relay-models.js";
|
|
13
13
|
import { publicChannels } from "./public-channels.js";
|
|
14
14
|
import { sessionEnd } from "./session-end.js";
|
|
15
15
|
import { ticketRoutes } from "./ticket-route.js";
|
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { RealtimeRelaySettings } from "./relay-options.js";
|
|
1
2
|
import { AdminAuth } from "../better-auth/create-auth.js";
|
|
3
|
+
import { ResourceModel } from "@protobase/schema";
|
|
2
4
|
import { Db } from "@protobase/query";
|
|
3
5
|
//#region src/relay/relay-schema.d.ts
|
|
4
6
|
/**
|
|
5
|
-
* The SQL the relay needs of the app's database: the trigger that closes a
|
|
6
|
-
*
|
|
7
|
+
* The SQL the relay needs of the app's database, for its channels (`appRelayChannels`): the trigger that closes a
|
|
8
|
+
* deleted session's sockets, and `realtime.members` with the triggers that keep it from the channel records that list
|
|
9
|
+
* their members; `undefined` when it is current. `authWritten`: the same migration writes the auth store's steps before it.
|
|
7
10
|
*/
|
|
8
|
-
export declare const relayMigration: (db: Db, auth: AdminAuth | undefined, authWritten: boolean) => Promise<string | undefined>;
|
|
9
|
-
/** Refuses to start while the relay's trigger
|
|
10
|
-
export declare const checkRelaySchema: (db: Db, auth: AdminAuth | undefined) => Promise<void>;
|
|
11
|
+
export declare const relayMigration: (db: Db, auth: AdminAuth | undefined, authWritten: boolean, channels: RealtimeRelaySettings["channels"], models: readonly ResourceModel[]) => Promise<string | undefined>;
|
|
12
|
+
/** Refuses to start while the relay's trigger, or `realtime.members` and its triggers, are missing or out of date. */
|
|
13
|
+
export declare const checkRelaySchema: (db: Db, auth: AdminAuth | undefined, channels: RealtimeRelaySettings["channels"], models: readonly ResourceModel[]) => Promise<void>;
|
|
11
14
|
//#endregion
|
|
@@ -1,16 +1,28 @@
|
|
|
1
|
+
import { migrationCommand } from "../changes/capture-schema.js";
|
|
2
|
+
import { relayModels } from "./relay-models.js";
|
|
1
3
|
import { checkRelaySessions, relaySessionsMigration } from "./sessions-sql.js";
|
|
4
|
+
import { listedTable } from "./realtime-members-sql.js";
|
|
2
5
|
import { sessionsTable } from "./session-end.js";
|
|
6
|
+
import { checkRealtimeMembers, realtimeMembersMigration } from "./realtime-members-schema.js";
|
|
3
7
|
//#region src/relay/relay-schema.ts
|
|
4
8
|
const needsAuth = (auth) => {
|
|
5
9
|
if (!auth) throw new Error("relay needs the app's own sign-in (auth), whose sessions its tickets name and end");
|
|
6
10
|
return auth;
|
|
7
11
|
};
|
|
12
|
+
const listedTables = (channels, models) => [...relayModels({ channels }, models).channels.values()].flatMap((channel) => channel.listed ? [listedTable(channel.listed)] : []);
|
|
8
13
|
/**
|
|
9
|
-
* The SQL the relay needs of the app's database: the trigger that closes a
|
|
10
|
-
*
|
|
14
|
+
* The SQL the relay needs of the app's database, for its channels (`appRelayChannels`): the trigger that closes a
|
|
15
|
+
* deleted session's sockets, and `realtime.members` with the triggers that keep it from the channel records that list
|
|
16
|
+
* their members; `undefined` when it is current. `authWritten`: the same migration writes the auth store's steps before it.
|
|
11
17
|
*/
|
|
12
|
-
const relayMigration = (db, auth, authWritten
|
|
13
|
-
|
|
14
|
-
|
|
18
|
+
const relayMigration = async (db, auth, authWritten, channels, models) => {
|
|
19
|
+
const parts = [await relaySessionsMigration(db, sessionsTable(needsAuth(auth)), authWritten), await realtimeMembersMigration(db, listedTables(channels, models))].filter((part) => part !== void 0);
|
|
20
|
+
return parts.length > 0 ? parts.join("\n\n") : void 0;
|
|
21
|
+
};
|
|
22
|
+
/** Refuses to start while the relay's trigger, or `realtime.members` and its triggers, are missing or out of date. */
|
|
23
|
+
const checkRelaySchema = async (db, auth, channels, models) => {
|
|
24
|
+
await checkRelaySessions(db, sessionsTable(needsAuth(auth)));
|
|
25
|
+
await checkRealtimeMembers(db, listedTables(channels, models), migrationCommand);
|
|
26
|
+
};
|
|
15
27
|
//#endregion
|
|
16
28
|
export { checkRelaySchema, relayMigration };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { appRelayChannels } from "./realtime-channels.js";
|
|
1
2
|
import { relaySettings } from "./relay-options.js";
|
|
2
3
|
//#region src/relay/relay-switch.ts
|
|
3
4
|
/** The variable with which a platform that runs the relay moves an app to it. */
|
|
@@ -11,14 +12,19 @@ const readRelaySwitch = (env) => {
|
|
|
11
12
|
};
|
|
12
13
|
/**
|
|
13
14
|
* The app's relay settings, or undefined without a relay: a config's `realtime.relay` turns it on whatever the switch
|
|
14
|
-
* says,
|
|
15
|
-
*
|
|
15
|
+
* says, and the switch turns it on without one; either way the channels are `appRelayChannels`', and the address and
|
|
16
|
+
* keys default to the platform's variables (`relaySettings`). The switch on for an app with no channels to derive
|
|
17
|
+
* stops the server.
|
|
16
18
|
*/
|
|
17
|
-
const appRelaySettings = (declared, env) => {
|
|
19
|
+
const appRelaySettings = (declared, env, app) => {
|
|
18
20
|
const on = readRelaySwitch(env);
|
|
19
|
-
if (declared) return
|
|
20
|
-
|
|
21
|
-
throw new Error(`${realtimeSwitchVariable} is true, but the
|
|
21
|
+
if (!declared && !on) return;
|
|
22
|
+
const channels = appRelayChannels(declared, app);
|
|
23
|
+
if (!channels) throw new Error(`${realtimeSwitchVariable} is true, but the app has no realtime.relay, and no live conversation resource whose page has members, with sign-in, to derive the relay's channels from`);
|
|
24
|
+
return relaySettings({
|
|
25
|
+
...declared,
|
|
26
|
+
channels
|
|
27
|
+
}, env);
|
|
22
28
|
};
|
|
23
29
|
//#endregion
|
|
24
30
|
export { appRelaySettings, readRelaySwitch, realtimeSwitchVariable };
|
|
@@ -3,6 +3,7 @@ import { channelRecord } from "../channels/channel-name.js";
|
|
|
3
3
|
import { recordReadable } from "../channels/record-readable.js";
|
|
4
4
|
import { anonymousSession } from "../anonymous.js";
|
|
5
5
|
import { jsonBody, jsonOnly } from "../notifications/history-request.js";
|
|
6
|
+
import { hasMembers } from "./relay-models.js";
|
|
6
7
|
import { peopleChannel } from "./presence-commands.js";
|
|
7
8
|
import { memberships } from "./members-sql.js";
|
|
8
9
|
import { signTicket } from "./ticket.js";
|
|
@@ -41,7 +42,7 @@ const ticketRoutes = ({ deps, options, models, jobs, sessionEnd }) => {
|
|
|
41
42
|
const resource = slash < 0 ? "" : name.slice(0, slash);
|
|
42
43
|
const refuse = () => notFound(`There is no channel ${name}`);
|
|
43
44
|
const channel = models.channels.get(resource);
|
|
44
|
-
if (!channel || channel
|
|
45
|
+
if (!channel || hasMembers(channel)) throw refuse();
|
|
45
46
|
const record = channelRecord(deps.registry, resource, name.slice(slash + 1));
|
|
46
47
|
if (record === void 0 || record === "too-long" || record.name !== name) throw refuse();
|
|
47
48
|
if (!await recordReadable(deps, anonymousSession(), record)) throw refuse();
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
const typingViewErrors = (views, channels) => views.flatMap((view) => {
|
|
7
7
|
const page = view.record;
|
|
8
8
|
if (!channels || !page || !("conversation" in page) || !page.conversation.typing) return [];
|
|
9
|
-
return channels.has(view.resource) ? [] : [`View "${view.resource}": record.conversation.typing goes through the record's relay channel, so "${view.resource}" needs to be in realtime.relay.channels`];
|
|
9
|
+
return channels.has(view.resource) ? [] : [`View "${view.resource}": record.conversation.typing goes through the record's relay channel, so "${view.resource}" needs to be in realtime.relay.channels, or its conversation page needs members`];
|
|
10
10
|
});
|
|
11
11
|
//#endregion
|
|
12
12
|
export { typingViewErrors };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/server",
|
|
3
|
-
"version": "0.126.
|
|
3
|
+
"version": "0.126.1",
|
|
4
4
|
"description": "The Protobase REST API as a Hono app, with Better Auth sign-in.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -44,11 +44,11 @@
|
|
|
44
44
|
"@better-auth/sso": "^1.7.12",
|
|
45
45
|
"@livekit/protocol": "1.53.1",
|
|
46
46
|
"@modelcontextprotocol/server": "^2.3.1",
|
|
47
|
-
"@protobase/layout": "0.126.
|
|
48
|
-
"@protobase/query": "0.126.
|
|
49
|
-
"@protobase/schema": "0.126.
|
|
50
|
-
"@protobase/workflow-plugins": "0.126.
|
|
51
|
-
"@protobase/workflows": "0.126.
|
|
47
|
+
"@protobase/layout": "0.126.1",
|
|
48
|
+
"@protobase/query": "0.126.1",
|
|
49
|
+
"@protobase/schema": "0.126.1",
|
|
50
|
+
"@protobase/workflow-plugins": "0.126.1",
|
|
51
|
+
"@protobase/workflows": "0.126.1",
|
|
52
52
|
"@react-email/render": "^2.1.0",
|
|
53
53
|
"@react-pdf/primitives": "^4.4.0",
|
|
54
54
|
"@react-pdf/renderer": "^4.9.0",
|