@protobase/server 0.49.1 → 0.49.2
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/files/store-file.d.ts +14 -2
- package/dist/files/store-file.js +8 -1
- package/dist/index.d.ts +2 -2
- package/dist/internal.js +1 -1
- package/dist/jobs/declared-job.d.ts +37 -2
- package/dist/jobs/declared-job.js +2 -1
- package/dist/jobs/job-types.d.ts +1 -1
- package/dist/package.js +1 -1
- package/package.json +4 -4
|
@@ -1,13 +1,25 @@
|
|
|
1
|
+
import { FileProvider } from "./store.js";
|
|
1
2
|
import { FilesOptions } from "./options.js";
|
|
3
|
+
import { FileProviderSettings } from "./provider-settings.js";
|
|
2
4
|
//#region src/files/store-file.d.ts
|
|
5
|
+
/** A provider in `files.providers`: as the config writes it, or made. */
|
|
6
|
+
type ProviderEntry = FileProvider | FileProviderSettings | {
|
|
7
|
+
kind: 'custom';
|
|
8
|
+
};
|
|
3
9
|
export type StoreFileInput = {
|
|
4
10
|
/** The provider's name, as a stored value starts with it: `public` in `public:listings/house-1.png`. */
|
|
5
11
|
provider: string;
|
|
6
12
|
/** The path in the provider, such as `listings/house-1.png`. */
|
|
7
13
|
path: string;
|
|
8
14
|
body: Uint8Array | ReadableStream<Uint8Array>;
|
|
9
|
-
/**
|
|
10
|
-
|
|
15
|
+
/**
|
|
16
|
+
* `files` from `protobase.config.ts`, when it configures providers, as the config writes it (`{ kind: 'local', dir }`,
|
|
17
|
+
* `{ kind: 's3', bucket }`) or with its providers made; the environment's apply on top, as for the server.
|
|
18
|
+
*/
|
|
19
|
+
files?: Omit<FilesOptions, 'providers'> & {
|
|
20
|
+
providers?: Record<string, ProviderEntry>;
|
|
21
|
+
images?: string;
|
|
22
|
+
};
|
|
11
23
|
/** Where `PROTOBASE_FILES_<NAME>` and the credentials are read from, usually `process.env`. */
|
|
12
24
|
env: Record<string, string | undefined>;
|
|
13
25
|
};
|
package/dist/files/store-file.js
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
import { resolveProviders } from "./providers.js";
|
|
2
|
+
import { fileProviderOf } from "./provider-settings.js";
|
|
2
3
|
//#region src/files/store-file.ts
|
|
4
|
+
const providerOf = (name, entry) => {
|
|
5
|
+
if (!("kind" in entry)) return entry;
|
|
6
|
+
if (entry.kind === "custom") throw new Error(`files.providers.${name} is the default export of files/${name}.ts: import it and pass it in place of { kind: 'custom' }`);
|
|
7
|
+
return fileProviderOf(name, entry);
|
|
8
|
+
};
|
|
3
9
|
/**
|
|
4
10
|
* Writes a file into one of the app's providers outside a request, such as from a seed: the folder of a `file:`
|
|
5
11
|
* provider, the bucket of an `s3:` one, resolved as the server resolves them (`PROTOBASE_FILES_<NAME>`, else the
|
|
6
12
|
* config's, else `data/files/<name>` for `private` and `public`). A relative folder is taken from the working directory.
|
|
7
13
|
*/
|
|
8
14
|
const storeFile = async ({ provider, path, body, files = {}, env }) => {
|
|
9
|
-
const
|
|
15
|
+
const entry = files.providers?.[provider];
|
|
16
|
+
const providers = resolveProviders(entry ? { providers: { [provider]: providerOf(provider, entry) } } : {}, env, [provider]);
|
|
10
17
|
const stream = body instanceof ReadableStream ? body : new Blob([body]).stream();
|
|
11
18
|
return providers[provider].store.put(path, stream);
|
|
12
19
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -154,7 +154,7 @@ import { FileRef, formatUri, variantPath } from "./files/uri.js";
|
|
|
154
154
|
import { aspectRatio, fileSize, fileType, imageSize, processor } from "./files/processors.js";
|
|
155
155
|
import { defineJob, isJobDefinition, jobDefinitions } from "./jobs/define-job.js";
|
|
156
156
|
import { FatalJobError } from "./jobs/run-job.js";
|
|
157
|
-
import { JobDeclaration, JobRun, enqueueJob } from "./jobs/declared-job.js";
|
|
157
|
+
import { ArgumentsPayload, EnqueueJob, JobDeclaration, JobName, JobPayload, JobRun, enqueueJob } from "./jobs/declared-job.js";
|
|
158
158
|
import { isSchedule } from "./jobs/schedule.js";
|
|
159
159
|
import { EmailComponent, EmailOptions, EmailTemplate, RenderedEmail, defineEmail } from "./mail/define-email.js";
|
|
160
160
|
import { DrainResult, JobsRuntime, StartJobsOptions, startJobs } from "./jobs/runtime.js";
|
|
@@ -164,4 +164,4 @@ import { MobileRelease, ReleaseFile, ServedReleaseFile, composeRelease, releaseM
|
|
|
164
164
|
import { MobileReleaseAppInput, OfferedRelease, mobileReleaseApp } from "./mobile-release/release-app.js";
|
|
165
165
|
import { mobileSigningKeyVariable, readSigningKey } from "./mobile-release/signing-key.js";
|
|
166
166
|
import { AdminAuth, CreateAuthOptions, UserCreatedHook, normalizeRoles } from "./better-auth/create-auth.js";
|
|
167
|
-
export { type Admin, type AdminAuth, type AdminOptions, type ApiFunction, type ApiKeys, type ApiKeysOptions, type ApnsEnvironment, type AppIcons, type AppIdentity, type AppPoolConfig, type ApplyOptions, type ApplyResult, type ApprovalAnswer, type ApprovalRequest, type AssistantBackend, type AssistantOptions, type AssistantSettings, type AssistantTool, type AuditEvent, type AuditQueue, type AuthHooks, type AuthSettings, type AuthenticateSettings, type Authenticator, type BatchOperation, type BatchResult, type BetterAuthAuthenticator, type BetterAuthAuthenticatorOptions, type Caller, type CallerOptions, type CapturedRow, type CascadingKey, type ChatMessage, type ChatTextPart, type CheckAiInput, type CleanupEntry, type CleanupReport, type CleanupSchedule, type CoalescedChange, type CommentItem, type CommentUsers, type Completion, type CompletionOptions, ConnectionsBusy, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CorsOptions, type CorsOrigins, type CreateAdminInput, type CreateAuthOptions, type Device, type DeviceColumn, type DeviceKind, type DeviceStore, DeviceStoreError, type DrainResult, type EmailComponent, type EmailOptions, type EmailTemplate, type EncryptionStatus, type EncryptionTools, type EncryptionToolsInput, type EnqueueOptions, type ErrorReporter, type ErrorReportingOptions, type ErrorReportingSettings, type EventData, type EventsOptions, FatalJobError, type FieldApplied, 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 JobOptions, type JobRun, type JobsRuntime, type JsonObject, type JsonValue, type JwtOptions, type JwtVerifyOptions, type KeyFunctionContext, type LinkedAccount, type ListParams, type LocalFilesOptions, type MailMessage, 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 MobileRelease, type MobileReleaseAppInput, ModelError, type ModelSettings, type NewDevice, type NewNotification, type NewOrganization, type NewUser, type NotificationRecipients, NotificationSendError, type NotificationsOptions, type OfferedRelease, type OperatorProvider, type OrganizationRole, type OrganizationsOptions, 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 ReasoningDetail, type ReasoningEffort, type RebindOption, type RecordKeyInput, type RecordPage, type ReleaseFile, type RenderedEmail, 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, type ServedReleaseFile, 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 StoreFileInput, type StoredMember, type StoredNotification, type StoredObject, type StoredOrganization, type StoredUser, type StrayValues, type SubscriptionDefinition, type SubscriptionEvent, type SubscriptionOptions, type TenantValue, type ToolAnnotations, type ToolCall, type ToolContext, type ToolRecord, type ToolRecords, type ToolSpec, type TrustedApp, type TurnOptions, type UnreadableEntry, type Urgency, type User, type UserCreatedHook, type VapidSettings, type ViewSource, type WebPushFields, type WebPushOptions, type WebhooksOptions, type WidgetOptions, type WriteEvent, type WriteOperation, type WriteRecordToolsInput, addAppRoleToOwners, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, appNameOver, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, capSocketMessages, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentsMigration, composeRelease, computedMigration, configExports, consoleAuditQueue, conversationKey, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultSignInPolicy, defineEmail, defineFunction, defineJob, defineTool, deleteRecordTool, deleteUser, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, goTruePath, handleDroppedConnections, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, mobileReleaseApp, mobileSigningKeyVariable, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readDbConnections, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readRecordTools, readSigningKey, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, recordOf, releaseManifest, 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, startErrorReporting, startJobs, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, thumbHash, unauthorized, updateRecordTool, urgencies, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, writeRecordTools };
|
|
167
|
+
export { type Admin, type AdminAuth, type AdminOptions, type ApiFunction, type ApiKeys, type ApiKeysOptions, type ApnsEnvironment, 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 BatchOperation, type BatchResult, type BetterAuthAuthenticator, type BetterAuthAuthenticatorOptions, type Caller, type CallerOptions, type CapturedRow, type CascadingKey, type ChatMessage, type ChatTextPart, type CheckAiInput, type CleanupEntry, type CleanupReport, type CleanupSchedule, type CoalescedChange, type CommentItem, type CommentUsers, type Completion, type CompletionOptions, ConnectionsBusy, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CorsOptions, type CorsOrigins, type CreateAdminInput, type CreateAuthOptions, 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 FieldApplied, 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 JsonObject, type JsonValue, type JwtOptions, type JwtVerifyOptions, type KeyFunctionContext, type LinkedAccount, type ListParams, type LocalFilesOptions, type MailMessage, 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 MobileRelease, type MobileReleaseAppInput, ModelError, type ModelSettings, type NewDevice, type NewNotification, type NewOrganization, type NewUser, type NotificationRecipients, NotificationSendError, type NotificationsOptions, type OfferedRelease, type OperatorProvider, type OrganizationRole, type OrganizationsOptions, 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 ReasoningDetail, type ReasoningEffort, type RebindOption, type RecordKeyInput, type RecordPage, type ReleaseFile, type RenderedEmail, 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, type ServedReleaseFile, 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 StoreFileInput, type StoredMember, type StoredNotification, type StoredObject, type StoredOrganization, type StoredUser, type StrayValues, type SubscriptionDefinition, type SubscriptionEvent, type SubscriptionOptions, type TenantValue, type ToolAnnotations, type ToolCall, type ToolContext, type ToolRecord, type ToolRecords, type ToolSpec, type TrustedApp, type TurnOptions, type UnreadableEntry, type Urgency, type User, type UserCreatedHook, type VapidSettings, type ViewSource, type WebPushFields, type WebPushOptions, type WebhooksOptions, type WidgetOptions, type WriteEvent, type WriteOperation, type WriteRecordToolsInput, addAppRoleToOwners, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, appNameOver, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, capSocketMessages, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentsMigration, composeRelease, computedMigration, configExports, consoleAuditQueue, conversationKey, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultSignInPolicy, defineEmail, defineFunction, defineJob, defineTool, deleteRecordTool, deleteUser, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, goTruePath, handleDroppedConnections, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, mobileReleaseApp, mobileSigningKeyVariable, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readDbConnections, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readRecordTools, readSigningKey, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, recordOf, releaseManifest, 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, startErrorReporting, startJobs, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, thumbHash, unauthorized, updateRecordTool, urgencies, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, writeRecordTools };
|
package/dist/internal.js
CHANGED
|
@@ -5,9 +5,9 @@ import { localFiles } from "./files/local-files.js";
|
|
|
5
5
|
import { s3Files } from "./files/s3-files.js";
|
|
6
6
|
import { appPool, longQueryPool } from "./app-pool.js";
|
|
7
7
|
import { betterAuthAuthenticator } from "./better-auth/authenticator.js";
|
|
8
|
+
import { fileProviderOf } from "./files/provider-settings.js";
|
|
8
9
|
import { declaredJob } from "./jobs/declared-job.js";
|
|
9
10
|
import { appAuthOptions, buildAppAuth } from "./better-auth/auth-settings.js";
|
|
10
11
|
import { buildAuthenticator } from "./better-auth/authenticate-settings.js";
|
|
11
|
-
import { fileProviderOf } from "./files/provider-settings.js";
|
|
12
12
|
import { webhooksModule } from "./webhooks/table/webhooks-module.js";
|
|
13
13
|
export { appAuthOptions, appPool, betterAuthAuthenticator, buildAppAuth, buildAuth, buildAuthenticator, checkNotificationsOptions, createAuth, declaredJob, fileProviderOf, isSubscription, loadAuthPlugins, localFiles, longQueryPool, s3Files, webhooksModule };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EnqueueOptions, JobContext, JobDefinition, JobOptions } from "./job-types.js";
|
|
2
|
-
import { ArgumentsSpec } from "@protobase/schema";
|
|
2
|
+
import { ArgumentType, ArgumentsSpec } from "@protobase/schema";
|
|
3
3
|
import { Db } from "@protobase/query";
|
|
4
4
|
//#region src/jobs/declared-job.d.ts
|
|
5
5
|
/**
|
|
@@ -18,7 +18,42 @@ export type JobRun<Payload = Record<string, unknown>> = (payload: Payload, conte
|
|
|
18
18
|
export declare const declaredJob: (name: string, { description: _, arguments: args, ...options }: JobDeclaration, load: () => Promise<JobRun>) => JobDefinition;
|
|
19
19
|
/**
|
|
20
20
|
* Enqueues the job named `name`, which the config declares, in `db`'s own transaction when it is one, and returns its
|
|
21
|
-
* id: what a write hook calls, so the job commits with the write or not at all.
|
|
21
|
+
* id: what a write hook calls, so the job commits with the write or not at all. `EnqueueJob<typeof config>` types it
|
|
22
|
+
* with the config's job names and arguments.
|
|
22
23
|
*/
|
|
23
24
|
export declare const enqueueJob: (db: Db, name: string, payload?: Record<string, unknown>, options?: EnqueueOptions) => Promise<string>;
|
|
25
|
+
type TypeValue<Type> = Type extends 'integer' ? number : Type extends 'boolean' ? boolean : Type extends 'json' ? unknown : string;
|
|
26
|
+
type ArgumentValue<Spec> = Spec extends ArgumentType ? TypeValue<Spec> : Spec extends {
|
|
27
|
+
type: 'enum';
|
|
28
|
+
values: readonly (infer Value)[];
|
|
29
|
+
} ? Value : Spec extends {
|
|
30
|
+
type: infer Type extends ArgumentType;
|
|
31
|
+
} ? TypeValue<Type> : unknown;
|
|
32
|
+
type Optional<Spec> = Spec extends {
|
|
33
|
+
optional: true;
|
|
34
|
+
} ? true : false;
|
|
35
|
+
type Flat<Type> = { [Key in keyof Type]: Type[Key]; };
|
|
36
|
+
/**
|
|
37
|
+
* The payload of a job with these arguments, as it is enqueued with it and its run gets it: `{ invoiceId: string }` for
|
|
38
|
+
* `{ invoiceId: 'bigint' }`, an argument with `optional: true` left out at will.
|
|
39
|
+
*/
|
|
40
|
+
export type ArgumentsPayload<Spec extends ArgumentsSpec> = Flat<{ -readonly [Name in keyof Spec as Optional<Spec[Name]> extends true ? never : Name]: ArgumentValue<Spec[Name]>; } & { -readonly [Name in keyof Spec as Optional<Spec[Name]> extends true ? Name : never]?: ArgumentValue<Spec[Name]>; }>;
|
|
41
|
+
type DeclaredJobs<Config> = (Config extends ((...args: never[]) => infer Returned) ? Awaited<Returned> : Config) extends {
|
|
42
|
+
jobs?: infer Jobs;
|
|
43
|
+
} ? NonNullable<Jobs> : never;
|
|
44
|
+
/** The names of the jobs a config declares, from `typeof config` of its `protobase.config.ts`. */
|
|
45
|
+
export type JobName<Config> = keyof DeclaredJobs<Config> & string;
|
|
46
|
+
/**
|
|
47
|
+
* The payload of the job `Name` a config declares, from its `arguments` (see `ArgumentsPayload`): what the job is
|
|
48
|
+
* enqueued with and what its `JobRun` gets. A job without `arguments` takes any payload, unchecked.
|
|
49
|
+
*/
|
|
50
|
+
export type JobPayload<Config, Name extends JobName<Config>> = DeclaredJobs<Config>[Name] extends {
|
|
51
|
+
arguments: infer Spec extends ArgumentsSpec;
|
|
52
|
+
} ? ArgumentsPayload<Spec> : Record<string, unknown>;
|
|
53
|
+
/**
|
|
54
|
+
* `enqueueJob`, typed with the jobs of a config, so a name it does not declare or a payload that does not fit its
|
|
55
|
+
* arguments fails to compile: `const enqueue: EnqueueJob<typeof config> = enqueueJob`. The payload may be left out when
|
|
56
|
+
* no argument is required.
|
|
57
|
+
*/
|
|
58
|
+
export type EnqueueJob<Config> = <Name extends JobName<Config>>(db: Db, name: Name, ...rest: {} extends JobPayload<Config, Name> ? [payload?: JobPayload<Config, Name>, options?: EnqueueOptions] : [payload: JobPayload<Config, Name>, options?: EnqueueOptions]) => Promise<string>;
|
|
24
59
|
//#endregion
|
|
@@ -14,7 +14,8 @@ const declaredJob = (name, { description: _, arguments: args, ...options }, load
|
|
|
14
14
|
};
|
|
15
15
|
/**
|
|
16
16
|
* Enqueues the job named `name`, which the config declares, in `db`'s own transaction when it is one, and returns its
|
|
17
|
-
* id: what a write hook calls, so the job commits with the write or not at all.
|
|
17
|
+
* id: what a write hook calls, so the job commits with the write or not at all. `EnqueueJob<typeof config>` types it
|
|
18
|
+
* with the config's job names and arguments.
|
|
18
19
|
*/
|
|
19
20
|
const enqueueJob = (db, name, payload, options) => {
|
|
20
21
|
const runtime = currentJobs();
|
package/dist/jobs/job-types.d.ts
CHANGED
|
@@ -17,7 +17,7 @@ export type JobContext = {
|
|
|
17
17
|
};
|
|
18
18
|
/** Aborted when the job's timeout passes, or when the worker shuts down and its grace period ends. */
|
|
19
19
|
signal: AbortSignal;
|
|
20
|
-
/** Sends mail
|
|
20
|
+
/** Sends mail with the app's mailer: its auth/mailer.ts, else the SMTP server of `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM`; `undefined` when the app has no mail. */
|
|
21
21
|
mail?: Mailer;
|
|
22
22
|
/** Sends a notification as `sendNotification` does; `undefined` when the app has no `notifications`. */
|
|
23
23
|
sendNotification?: SendNotification;
|
package/dist/package.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/server",
|
|
3
|
-
"version": "0.49.
|
|
3
|
+
"version": "0.49.2",
|
|
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": {
|
|
@@ -40,9 +40,9 @@
|
|
|
40
40
|
"@better-auth/passkey": "^1.7.12",
|
|
41
41
|
"@better-auth/sso": "^1.7.12",
|
|
42
42
|
"@modelcontextprotocol/server": "^2.3.1",
|
|
43
|
-
"@protobase/layout": "0.49.
|
|
44
|
-
"@protobase/query": "0.49.
|
|
45
|
-
"@protobase/schema": "0.49.
|
|
43
|
+
"@protobase/layout": "0.49.2",
|
|
44
|
+
"@protobase/query": "0.49.2",
|
|
45
|
+
"@protobase/schema": "0.49.2",
|
|
46
46
|
"@react-email/render": "^2.1.0",
|
|
47
47
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
48
48
|
"@sentry/core": "^11.7.0",
|