@lunora/server 1.0.0-alpha.124 → 1.0.0-alpha.125
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +56 -2
- package/dist/index.d.ts +56 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-COBng51i.mjs → ACTION_CACHE_DEFAULT_TTL_MS-BKG-IE-M.mjs} +1 -1
- package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-C8sDYzqZ.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-B77Q3JxB.mjs} +1 -1
- package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-BzZ7xnmQ.mjs → PRESENCE_DEFAULT_TTL_MS-ksidzpHO.mjs} +1 -1
- package/dist/packem_shared/{assertShapesDeclareReadPolicies-DHLO-AVP.mjs → assertShapesDeclareReadPolicies-CjJWccLg.mjs} +1 -1
- package/dist/packem_shared/beginDeferredSchedules-CIhFddA2.mjs +1 -0
- package/dist/packem_shared/compose-middleware-DNvrHMHx.mjs +1 -0
- package/dist/packem_shared/{composePluginMiddleware-CTx6hU3r.mjs → composePluginMiddleware-4He2ow8i.mjs} +1 -1
- package/dist/packem_shared/{defineAggregateIndex-DGuYQrYn.mjs → defineAggregateIndex-BgXQWWQQ.mjs} +1 -1
- package/dist/packem_shared/{defineShape-DtBuu6Yh.mjs → defineShape-Be5u-Whf.mjs} +1 -1
- package/dist/packem_shared/{httpAction-DfKw8ZZt.mjs → httpAction-DFVhrm8u.mjs} +1 -1
- package/dist/packem_shared/initLunora-DAbEYdSo.mjs +1 -0
- package/dist/packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs +1 -0
- package/dist/packem_shared/{mask-rh0M0XlH.mjs → mask-DsL8pZvt.mjs} +1 -1
- package/dist/packem_shared/{middleware-DciZ1Q3A.mjs → middleware-CgYaL-lL.mjs} +1 -1
- package/dist/packem_shared/{plugin-CqXQ2s-i.mjs → plugin-m_rCyKKo.mjs} +1 -1
- package/dist/packem_shared/{protectPublic-C-STrTgA.mjs → protectPublic-BUYCMZZB.mjs} +1 -1
- package/dist/packem_shared/{rls-DCBTL6B2.mjs → rls-JwUA2QIB.mjs} +1 -1
- package/dist/packem_shared/{serveStorageObject-BzZEP-B5.mjs → serveStorageObject-9mdw0nyU.mjs} +1 -1
- package/dist/packem_shared/{storageRules-DvM18uSL.mjs → storageRules-DLH8uzGB.mjs} +1 -1
- package/dist/packem_shared/{wire-codec-CH4vwdFT.mjs → wire-codec-BTOxkE1j.mjs} +1 -1
- package/dist/rls/testing.mjs +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/beginDeferredSchedules-gJlbW6h9.mjs +0 -1
- package/dist/packem_shared/compose-middleware-MCpZZKh7.mjs +0 -1
- package/dist/packem_shared/initLunora-BzC2zEfH.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1131,6 +1131,13 @@ declare const asBucketStorage: (raw: unknown) => unknown;
|
|
|
1131
1131
|
declare const initLunora: {
|
|
1132
1132
|
dataModel: <DataModel>() => DataModelInit<DataModel>;
|
|
1133
1133
|
};
|
|
1134
|
+
/**
|
|
1135
|
+
* Mark a middleware as per-dispatch. Returns the same reference, so a factory
|
|
1136
|
+
* can `return tagPerDispatchMiddleware(async ({ ctx, next }) => …)`.
|
|
1137
|
+
*/
|
|
1138
|
+
declare const tagPerDispatchMiddleware: <M extends object>(middleware: M) => M;
|
|
1139
|
+
/** Whether a middleware carries the per-dispatch mark. `false` for anything else. */
|
|
1140
|
+
declare const isPerDispatchMiddleware: (middleware: unknown) => boolean;
|
|
1134
1141
|
/**
|
|
1135
1142
|
* Build the `ctx.secrets` reader from the worker `env`. `get(name)` resolves
|
|
1136
1143
|
* `env[name].get()` — the `secrets_store_secrets[]` binding of that name. An
|
|
@@ -1197,6 +1204,47 @@ interface DeferredDeleteFlushResult {
|
|
|
1197
1204
|
* @param context the dispatch context; a context with no queued deletes is a no-op
|
|
1198
1205
|
*/
|
|
1199
1206
|
declare const flushDeferredDeletes: (context: unknown) => Promise<DeferredDeleteFlushResult>;
|
|
1207
|
+
/**
|
|
1208
|
+
* Durable custody for a buffered schedule, between the COMMIT and the moment the
|
|
1209
|
+
* scheduler accepts the job.
|
|
1210
|
+
*
|
|
1211
|
+
* A structural mirror of `@lunora/shard-engine`'s `ScheduleOutbox`, for the same
|
|
1212
|
+
* reason {@link SchedulerLike} below mirrors rather than imports: this type
|
|
1213
|
+
* appears in `withDeferredSchedules`'s exported signature, and naming a
|
|
1214
|
+
* `@lunora/shard-engine` type there pulls that package into the declaration
|
|
1215
|
+
* bundle of everything that re-exports this one. `@lunora/do` supplies the real
|
|
1216
|
+
* implementation and the shapes match structurally.
|
|
1217
|
+
*
|
|
1218
|
+
* The two halves land on opposite sides of the COMMIT on purpose. `record` runs
|
|
1219
|
+
* while the handler is still inside its transaction, so the entry is durable
|
|
1220
|
+
* exactly when the writes are and rolls back with them; `forget` runs after the
|
|
1221
|
+
* dispatch settles. What survives is precisely the set of jobs that were promised
|
|
1222
|
+
* and not enqueued.
|
|
1223
|
+
*
|
|
1224
|
+
* Optional throughout: a ctx with no outbox (a unit harness, a host with no
|
|
1225
|
+
* store) keeps the previous best-effort behaviour rather than failing to build.
|
|
1226
|
+
*/
|
|
1227
|
+
interface ScheduleOutbox {
|
|
1228
|
+
/** Release custody — the scheduler has the job, or the window that owned it was dropped. */
|
|
1229
|
+
forget: (id: string) => void;
|
|
1230
|
+
/**
|
|
1231
|
+
* Take custody of one buffered call. Runs INSIDE the transaction, so a throw
|
|
1232
|
+
* here rolls the mutation back — which is the right answer, and the only
|
|
1233
|
+
* moment at which failing is free.
|
|
1234
|
+
*
|
|
1235
|
+
* `when` is always the ABSOLUTE instant, even for a `runAfter`: a delay
|
|
1236
|
+
* replayed after an hour in custody would fire an hour late, and the retry has
|
|
1237
|
+
* to reproduce the fire time the caller asked for, not the wait.
|
|
1238
|
+
*/
|
|
1239
|
+
record: (id: string, envelope: {
|
|
1240
|
+
args: unknown;
|
|
1241
|
+
options: Record<string, unknown> | undefined;
|
|
1242
|
+
target: unknown;
|
|
1243
|
+
when: number;
|
|
1244
|
+
}) => void;
|
|
1245
|
+
/** Ask the host to wake its retry loop — called when a dispatch left entries behind. */
|
|
1246
|
+
wake: () => void;
|
|
1247
|
+
}
|
|
1200
1248
|
/** The slice of a function context the window needs. */
|
|
1201
1249
|
interface DeferredScheduleContext {
|
|
1202
1250
|
scheduler?: unknown;
|
|
@@ -1237,7 +1285,7 @@ interface SchedulerLike {
|
|
|
1237
1285
|
* — could not be type-checked against the contract this docblock describes.
|
|
1238
1286
|
* @param scheduler the `ctx.scheduler` implementation to wrap
|
|
1239
1287
|
*/
|
|
1240
|
-
declare const withDeferredSchedules: <S extends SchedulerLike>(scheduler: S) => S;
|
|
1288
|
+
declare const withDeferredSchedules: <S extends SchedulerLike>(scheduler: S, outbox?: ScheduleOutbox) => S;
|
|
1241
1289
|
/**
|
|
1242
1290
|
* Open a deferral window on `context.scheduler` and return its settle function.
|
|
1243
1291
|
*
|
|
@@ -1258,6 +1306,12 @@ declare const withDeferredSchedules: <S extends SchedulerLike>(scheduler: S) =>
|
|
|
1258
1306
|
* order, and what failed is reported once at the end — as itself when one job
|
|
1259
1307
|
* failed, so its code and status survive, and as an `AggregateError` when several
|
|
1260
1308
|
* did.
|
|
1309
|
+
*
|
|
1310
|
+
* A failure still throws, and that is deliberate: a caller error the scheduler
|
|
1311
|
+
* refuses (`DUPLICATE_SCHEDULE_ID`, `INVALID_INPUT`) must reach the developer who
|
|
1312
|
+
* caused it. What changed is that the throw is no longer the only thing standing
|
|
1313
|
+
* between the job and oblivion — the outbox entry survives it, so the answer to
|
|
1314
|
+
* "the caller swallowed that error" is a retry rather than a lost job.
|
|
1261
1315
|
* The caller's own post-commit work must still run: a settle that throws does not
|
|
1262
1316
|
* excuse skipping the deferred-delete flush behind it.
|
|
1263
1317
|
* @param context the dispatch context whose `scheduler` carries the queue
|
|
@@ -3562,4 +3616,4 @@ interface StorageContextIn {
|
|
|
3562
3616
|
}
|
|
3563
3617
|
declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
|
|
3564
3618
|
declare const VERSION = "0.0.0";
|
|
3565
|
-
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
|
3619
|
+
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isPerDispatchMiddleware, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, tagPerDispatchMiddleware, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
package/dist/index.d.ts
CHANGED
|
@@ -1131,6 +1131,13 @@ declare const asBucketStorage: (raw: unknown) => unknown;
|
|
|
1131
1131
|
declare const initLunora: {
|
|
1132
1132
|
dataModel: <DataModel>() => DataModelInit<DataModel>;
|
|
1133
1133
|
};
|
|
1134
|
+
/**
|
|
1135
|
+
* Mark a middleware as per-dispatch. Returns the same reference, so a factory
|
|
1136
|
+
* can `return tagPerDispatchMiddleware(async ({ ctx, next }) => …)`.
|
|
1137
|
+
*/
|
|
1138
|
+
declare const tagPerDispatchMiddleware: <M extends object>(middleware: M) => M;
|
|
1139
|
+
/** Whether a middleware carries the per-dispatch mark. `false` for anything else. */
|
|
1140
|
+
declare const isPerDispatchMiddleware: (middleware: unknown) => boolean;
|
|
1134
1141
|
/**
|
|
1135
1142
|
* Build the `ctx.secrets` reader from the worker `env`. `get(name)` resolves
|
|
1136
1143
|
* `env[name].get()` — the `secrets_store_secrets[]` binding of that name. An
|
|
@@ -1197,6 +1204,47 @@ interface DeferredDeleteFlushResult {
|
|
|
1197
1204
|
* @param context the dispatch context; a context with no queued deletes is a no-op
|
|
1198
1205
|
*/
|
|
1199
1206
|
declare const flushDeferredDeletes: (context: unknown) => Promise<DeferredDeleteFlushResult>;
|
|
1207
|
+
/**
|
|
1208
|
+
* Durable custody for a buffered schedule, between the COMMIT and the moment the
|
|
1209
|
+
* scheduler accepts the job.
|
|
1210
|
+
*
|
|
1211
|
+
* A structural mirror of `@lunora/shard-engine`'s `ScheduleOutbox`, for the same
|
|
1212
|
+
* reason {@link SchedulerLike} below mirrors rather than imports: this type
|
|
1213
|
+
* appears in `withDeferredSchedules`'s exported signature, and naming a
|
|
1214
|
+
* `@lunora/shard-engine` type there pulls that package into the declaration
|
|
1215
|
+
* bundle of everything that re-exports this one. `@lunora/do` supplies the real
|
|
1216
|
+
* implementation and the shapes match structurally.
|
|
1217
|
+
*
|
|
1218
|
+
* The two halves land on opposite sides of the COMMIT on purpose. `record` runs
|
|
1219
|
+
* while the handler is still inside its transaction, so the entry is durable
|
|
1220
|
+
* exactly when the writes are and rolls back with them; `forget` runs after the
|
|
1221
|
+
* dispatch settles. What survives is precisely the set of jobs that were promised
|
|
1222
|
+
* and not enqueued.
|
|
1223
|
+
*
|
|
1224
|
+
* Optional throughout: a ctx with no outbox (a unit harness, a host with no
|
|
1225
|
+
* store) keeps the previous best-effort behaviour rather than failing to build.
|
|
1226
|
+
*/
|
|
1227
|
+
interface ScheduleOutbox {
|
|
1228
|
+
/** Release custody — the scheduler has the job, or the window that owned it was dropped. */
|
|
1229
|
+
forget: (id: string) => void;
|
|
1230
|
+
/**
|
|
1231
|
+
* Take custody of one buffered call. Runs INSIDE the transaction, so a throw
|
|
1232
|
+
* here rolls the mutation back — which is the right answer, and the only
|
|
1233
|
+
* moment at which failing is free.
|
|
1234
|
+
*
|
|
1235
|
+
* `when` is always the ABSOLUTE instant, even for a `runAfter`: a delay
|
|
1236
|
+
* replayed after an hour in custody would fire an hour late, and the retry has
|
|
1237
|
+
* to reproduce the fire time the caller asked for, not the wait.
|
|
1238
|
+
*/
|
|
1239
|
+
record: (id: string, envelope: {
|
|
1240
|
+
args: unknown;
|
|
1241
|
+
options: Record<string, unknown> | undefined;
|
|
1242
|
+
target: unknown;
|
|
1243
|
+
when: number;
|
|
1244
|
+
}) => void;
|
|
1245
|
+
/** Ask the host to wake its retry loop — called when a dispatch left entries behind. */
|
|
1246
|
+
wake: () => void;
|
|
1247
|
+
}
|
|
1200
1248
|
/** The slice of a function context the window needs. */
|
|
1201
1249
|
interface DeferredScheduleContext {
|
|
1202
1250
|
scheduler?: unknown;
|
|
@@ -1237,7 +1285,7 @@ interface SchedulerLike {
|
|
|
1237
1285
|
* — could not be type-checked against the contract this docblock describes.
|
|
1238
1286
|
* @param scheduler the `ctx.scheduler` implementation to wrap
|
|
1239
1287
|
*/
|
|
1240
|
-
declare const withDeferredSchedules: <S extends SchedulerLike>(scheduler: S) => S;
|
|
1288
|
+
declare const withDeferredSchedules: <S extends SchedulerLike>(scheduler: S, outbox?: ScheduleOutbox) => S;
|
|
1241
1289
|
/**
|
|
1242
1290
|
* Open a deferral window on `context.scheduler` and return its settle function.
|
|
1243
1291
|
*
|
|
@@ -1258,6 +1306,12 @@ declare const withDeferredSchedules: <S extends SchedulerLike>(scheduler: S) =>
|
|
|
1258
1306
|
* order, and what failed is reported once at the end — as itself when one job
|
|
1259
1307
|
* failed, so its code and status survive, and as an `AggregateError` when several
|
|
1260
1308
|
* did.
|
|
1309
|
+
*
|
|
1310
|
+
* A failure still throws, and that is deliberate: a caller error the scheduler
|
|
1311
|
+
* refuses (`DUPLICATE_SCHEDULE_ID`, `INVALID_INPUT`) must reach the developer who
|
|
1312
|
+
* caused it. What changed is that the throw is no longer the only thing standing
|
|
1313
|
+
* between the job and oblivion — the outbox entry survives it, so the answer to
|
|
1314
|
+
* "the caller swallowed that error" is a retry rather than a lost job.
|
|
1261
1315
|
* The caller's own post-commit work must still run: a settle that throws does not
|
|
1262
1316
|
* excuse skipping the deferred-delete flush behind it.
|
|
1263
1317
|
* @param context the dispatch context whose `scheduler` carries the queue
|
|
@@ -3562,4 +3616,4 @@ interface StorageContextIn {
|
|
|
3562
3616
|
}
|
|
3563
3617
|
declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
|
|
3564
3618
|
declare const VERSION = "0.0.0";
|
|
3565
|
-
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
|
3619
|
+
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isPerDispatchMiddleware, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, tagPerDispatchMiddleware, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BKG-IE-M.mjs";import{initLunora as d}from"./packem_shared/initLunora-DAbEYdSo.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as c}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as S,withDeferredDeletes as u}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CIhFddA2.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as L,documentHistoryExtension as C}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-B77Q3JxB.mjs";import{LunoraEnvError as P,defineEnv as M,redactSecrets as b}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-DFVhrm8u.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-9mdw0nyU.mjs";import{defineIdentity as j}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as Y,onDisconnect as J,onShardInit as K}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as X,DEFAULT_MAX_LIMIT as q,clampLimit as z,defineListArgs as G}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as $}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as re}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as te,d as ne,a as ie,b as ae,e as fe,f as se,g as de,h as me,i as pe,j as ce,k as xe,m as le}from"./packem_shared/plugin-m_rCyKKo.mjs";import{PRESENCE_DEFAULT_TTL_MS as he,PRESENCE_TABLE as Se,definePresence as ue,presenceExtension as De}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-ksidzpHO.mjs";import{protectPublic as ge}from"./packem_shared/protectPublic-BUYCMZZB.mjs";import{onQueryChange as Re}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Le}from"./packem_shared/defineShape-Be5u-Whf.mjs";import{anyApi as Ie}from"./types.mjs";import{LunoraError as Me}from"@lunora/errors";import{cronJobs as ye}from"@lunora/scheduler";import{ValidationError as Oe,v as He}from"@lunora/values";import{allowAll as we,deny as Ue,isDeny as ke,toWhereInput as ve}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Ve}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as We,buildRlsReadRegistry as Ye,composeShapeReadWhere as Je}from"./packem_shared/assertShapesDeclareReadPolicies-CjJWccLg.mjs";import{buildMaskRegistry as Qe}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as qe,definePermission as ze,definePolicies as Ge,definePolicy as Ze,defineRole as $e}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as rr,defineStorageRules as or}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as nr}from"./packem_shared/mask-DsL8pZvt.mjs";import{r as ar}from"./packem_shared/middleware-CgYaL-lL.mjs";import{storageRules as sr}from"./packem_shared/storageRules-DLH8uzGB.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,X as DEFAULT_LIMIT,q as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,P as LunoraEnvError,Me as LunoraError,he as PRESENCE_DEFAULT_TTL_MS,Se as PRESENCE_TABLE,e as VERSION,Oe as ValidationError,i as actionCacheExtension,we as allowAll,Ie as anyApi,Ve as asBucketStorage,We as assertShapesDeclareReadPolicies,h as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,Qe as buildMaskRegistry,Ye as buildRlsReadRegistry,a as cacheKeyFor,z as clampLimit,te as composePluginMiddleware,Je as composeShapeReadWhere,qe as createPolicyDsl,l as createSecrets,ye as cronJobs,f as defineActionCache,ne as defineAggregateIndex,ie as defineComponent,L as defineDocumentHistory,M as defineEnv,j as defineIdentity,G as defineListArgs,$ as defineMigration,re as defineMutator,ze as definePermission,ae as definePlugin,Ge as definePolicies,Ze as definePolicy,ue as definePresence,fe as defineRankIndex,$e as defineRole,se as defineSchema,de as defineSchemaExtension,Le as defineShape,rr as defineStorageRule,or as defineStorageRules,me as defineTable,pe as defineVectorIndex,Ue as deny,C as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,ce as indexFieldsFromSchema,d as initLunora,xe as installPlugins,ke as isDeny,p as isPerDispatchMiddleware,k as isSafeHeaderValue,nr as mask,le as mergeSchemaExtension,Y as onConnect,J as onDisconnect,Re as onQueryChange,K as onShardInit,De as presenceExtension,ge as protectPublic,b as redactSecrets,ar as rls,B as serveStorageObject,sr as storageRules,c as tagPerDispatchMiddleware,ve as toWhereInput,He as v,u as withDeferredDeletes,g as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{a as f,d as U}from"./wire-codec-BTOxkE1j.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-DAbEYdSo.mjs";import{g as k,h as q,a as B}from"./plugin-m_rCyKKo.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v as r}from"@lunora/values";import{d as E,
|
|
1
|
+
import{v as r}from"@lunora/values";import{d as E,a as h}from"./wire-codec-BTOxkE1j.mjs";import{initLunora as x}from"./initLunora-DAbEYdSo.mjs";import{g as v,h as R,a as U}from"./plugin-m_rCyKKo.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DAbEYdSo.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-m_rCyKKo.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-CgYaL-lL.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{assertScheduleInstant as b,assertScheduleDelay as w,resolveScheduleId as m}from"@lunora/scheduler";import{e as x}from"./wire-codec-BTOxkE1j.mjs";const g=new WeakMap,y=u=>{if(typeof u=="string")return u;const r=u??{},n=r.__lunoraRef??r.binding;return typeof n=="string"?n:"<unknown>"},p=u=>{let r=u;for(;r!==void 0&&!r.open;)r=r.parent;return r},S=(u,r)=>{const n=u,c={innermost:void 0,outbox:r},l=(e,t,s,o,d)=>n[e].call(n,t,s,o,d),i=(e,t,s,o,d)=>{const a=c.innermost;if(a===void 0)return l(e,t,s,o,d);const h=m(d?.id);return c.outbox?.record(h,{args:x(`ctx.scheduler.${e}`,y(s),o),options:d,target:s,when:e==="runAfter"?Date.now()+t:t}),a.pending.push({id:h,run:async()=>l(e,t,s,o,{...d,id:h})}),Promise.resolve(h)},f={...n,runAfter:(e,t,s,o)=>(w(e,"ctx.scheduler.runAfter"),i("runAfter",e,t,s,o)),runAt:(e,t,s,o)=>(b(e,Date.now(),"ctx.scheduler.runAt"),i("runAt",e,t,s,o))};return Object.setPrototypeOf(f,Object.getPrototypeOf(n)),g.set(f,c),f},D=u=>{const{scheduler:r}=u,n=typeof r=="object"&&r!==null?g.get(r):void 0;if(!n)return async()=>{};const c={open:!0,parent:n.innermost,pending:[]};return n.innermost=c,async l=>{if(!c.open)return;c.open=!1,n.innermost===c&&(n.innermost=p(c.parent));const i=c.pending.splice(0);if(i.length===0)return;if(!l){for(const{id:o}of i)n.outbox?.forget(o);return}const f=p(c.parent);if(f!==void 0){f.pending.push(...i);return}const e=[];for(const{id:o,run:d}of i)try{await d(),n.outbox?.forget(o)}catch(a){e.push(a)}const[t,...s]=e;if(t!==void 0)throw n.outbox?.wake(),s.length===0?t:new AggregateError(e,`ctx.scheduler: ${String(e.length)} of ${String(i.length)} deferred jobs failed to reach the scheduler after the commit`)}};export{D as beginDeferredSchedules,S as withDeferredSchedules};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{unionMaskColumns as d,tagMaskMiddleware as l}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as m,t as n}from"./policy-tag-V0lqFzgS.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as c}from"./isPerDispatchMiddleware-DDQPatSm.mjs";import{r as M}from"./run-middleware-laenw2jQ.mjs";const k=s=>{const a=(async({ctx:r,next:t})=>M(s,r,i=>t({ctx:i}))),e=s.flatMap(r=>m(r));e.length>0&&n(a,e);const o=d(s);return o&&l(a,{columns:o}),s.some(r=>p(r))&&c(a),a};export{k as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./compose-middleware-
|
|
1
|
+
import"./compose-middleware-DNvrHMHx.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-m_rCyKKo.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
|
package/dist/packem_shared/{defineAggregateIndex-DGuYQrYn.mjs → defineAggregateIndex-BgXQWWQQ.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-
|
|
1
|
+
import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-m_rCyKKo.mjs";export{d as defineAggregateIndex,n as defineRankIndex,i as defineSchema,s as defineTable,f as defineVectorIndex,x as indexFieldsFromSchema,r as validateIndexFields};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-CjJWccLg.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(a,l,n)=>{const w=u(e.args??{},l),o=e.where?m(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?n?.ownerField:e.owner;if(t===void 0||t==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const s=p(a);if(s===void 0)return d();const h={[t]:s};return o===void 0?h:{AND:[h,o]}},rlsRegistry:c(e.use??[])}};export{I as defineShape};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as E,toErrorBody as O,isLunoraError as N}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as _}from"@lunora/values";import{Hono as q}from"hono";import{
|
|
1
|
+
import{LunoraError as E,toErrorBody as O,isLunoraError as N}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as _}from"@lunora/values";import{Hono as q}from"hono";import{a as x}from"./wire-codec-BTOxkE1j.mjs";import{a as k}from"./apply-output-C5wZ5EAL.mjs";const U=e=>async r=>e(r.get("lunora"),r.req.raw),J=()=>{const e=new q;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},v=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},C=(e,r,o)=>{const n=v(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const d=n._meta?.inner;return a.map(i=>g(d?.kind??"string",i))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},S=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=C(t,r,n))}return R(e,o,"searchParams")},T=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const d=o[t];n[t]=d===void 0?void 0:g(v(a).kind,d)}return R(e,n,"params")},H=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return R(e,o,"body")},j=e=>{if(e instanceof _)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(N(e)){const{body:r,redacted:o,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},A=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},L=(e,r)=>async o=>{const n=A(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},d=Object.keys(e.params).length>0?T(e.params,o):{},i=Object.keys(e.body).length>0?await H(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?k(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const f=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:f?c:void 0,status:204}):Response.json(s,{headers:f?c:void 0})}catch(t){return j(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,r)=>{const o=JSON.stringify(r===void 0?x(e):e);return`${r?`event: ${r}
|
|
2
2
|
`:""}data: ${o}
|
|
3
3
|
|
|
4
4
|
`},D=(e,r)=>(async o=>{const n=A(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},a=Object.keys(e.params).length>0?T(e.params,o):{}}catch(m){return j(m)}const d=o.get("lunora"),i=o.req.raw,h=new TextEncoder,s=new AbortController;if(i.signal.aborted)return s.abort(),new Response("",{headers:w});const c=()=>{s.abort()};i.signal.addEventListener("abort",c,{once:!0});const f=new ReadableStream({cancel(){i.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const y=r({ctx:d,params:a,request:i,searchParams:t,signal:s.signal});for await(const p of y){if(s.signal.aborted)break;m.enqueue(h.encode(b(e.output?k(e.output,p):p)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(y){const{body:p,redacted:P}=O(y,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});P&&console.error("[lunora] unhandled stream handler error:",y),s.signal.aborted||m.enqueue(h.encode(b({code:p.code,message:p.message},"error")))}finally{i.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(f,{headers:w})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>L(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>D(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),Q={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},W=e=>!(e.includes("\r")||e.includes(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as C}from"./apply-output-C5wZ5EAL.mjs";import{v as h}from"./functions-B2-H4PQT.mjs";import{unionMaskColumns as w}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as M}from"./policy-tag-V0lqFzgS.mjs";import{isPerDispatchMiddleware as b}from"./isPerDispatchMiddleware-DDQPatSm.mjs";import{r as O}from"./run-middleware-laenw2jQ.mjs";const y=(e,r,o,n)=>n===0&&r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{args:Object.freeze({...o}),...r===void 0?{}:{meta:r}}),j=(e,r)=>O(e,r,o=>o),z=(e,r,o,n,s)=>async(c,t)=>{const d=h(e,t),u=await j(r,y(c,s,d,r.length)),m=await o({args:d,ctx:u});return n?C(n,m):m},P=(e,r,o,n)=>(s,c,t)=>{const d=h(e,c);return(async function*(){const m=await j(r,y(s,n,d,r.length)),f=o({args:d,ctx:m,signal:t})[Symbol.asyncIterator]();try{for(;;){if(t.aborted)return;const p=await f.next();if(p.done||t.aborted)return;yield p.value}}finally{await f.return?.()}})()},g=e=>{const r=e.flatMap(o=>M(o));return r.length>0?{tags:r}:void 0},i=e=>e.some(r=>b(r)),x=e=>{for(const r of["add","clear","delete","set"])typeof e[r]=="function"&&Object.defineProperty(e,r,{configurable:!1,enumerable:!1,value:()=>{throw new TypeError(`Cannot mutate a frozen .meta() declaration (${e.constructor.name}.${r})`)},writable:!1})},l=(e,r)=>{if(e===null||typeof e!="object"||r.has(e))return e;if(r.add(e),e instanceof Map){for(const[o,n]of e)l(o,r),l(n,r);x(e)}else if(e instanceof Set){for(const o of e)l(o,r);x(e)}for(const o of Object.values(e))l(o,r);return Object.freeze(e),e},_=e=>l(structuredClone(e),new WeakSet),a=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:n=>a(e,{...r,args:{...r.args,...n}},o),[e]:n=>{const s=g(r.middlewares),c=w(r.middlewares),t=i(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:z(r.args,r.middlewares,n,r.output,r.meta),kind:e,...c?{maskedTables:c}:{},...t?{perDispatch:t}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:n=>a(e,{...r,meta:_({...r.meta,...n})},o),output:n=>a(e,{...r,output:n},o),...e==="query"?{stream:(n,s)=>{const c=g(r.middlewares),t=w(r.middlewares),d=i(r.middlewares),u=s?.durable===!0?{}:s?.durable;return{args:r.args,...u?{durable:u}:{},...r.expose?{expose:r.expose}:{},handler:P(r.args,r.middlewares,n,r.meta),kind:"stream",...t?{maskedTables:t}:{},...d?{perDispatch:d}:{},...c?{rls:c}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:n=>a(e,{...r,middlewares:[...r.middlewares,n]},o),...o?{}:{expose:n=>a(e,{...r,expose:n},o)},...o?{}:{x402:n=>a(e,{...r,x402:n},o)}}),$={dataModel:()=>({create:e=>({action:a("action",{args:{},middlewares:[]}),internalAction:a("action",{args:{},middlewares:[]},"internal"),internalMutation:a("mutation",{args:{},middlewares:[]},"internal"),internalQuery:a("query",{args:{},middlewares:[]},"internal"),mutation:a("mutation",{args:{},middlewares:[]}),query:a("query",{args:{},middlewares:[]})})})};export{$ as initLunora};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=Symbol.for("lunora.middleware.per-dispatch"),r=e=>(Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:!0}),e),n=e=>e===null||typeof e!="function"&&typeof e!="object"?!1:e[t]===!0;export{n as isPerDispatchMiddleware,r as tagPerDispatchMiddleware};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-CgYaL-lL.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-D_hFUjmr.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},d=(e,i,a)=>{const u={...e};for(const[y,g]of Object.entries(i))y in u&&(u[y]=V(g,e[y],{...a,column:y,row:e}));return u},j=(e,i,a)=>({...e,page:e.page.map(u=>d(u,i,a))}),D=(e,i,a,u)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${u}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,u)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>d(o,t,a)):n},k=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},p=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=u?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},l=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield d(o,n,a)},collect:async()=>(await r.collect()).map(s=>d(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=d(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>l(r.filter(s=>o(d(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?d(o,n,a):null},order:o=>l(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>d(c,n,a)),unique:async()=>{const o=await r.unique();return o?d(o,n,a):null},withIndex:(o,s)=>(p(t,o,"withIndex","index"),D(s,n,t,"withIndex"),l(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),l(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(p(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);if(f)return{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,k(n)),o=i.get(r);return t&&o?d(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,k(n)),o=i.get(r);return o?d(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,k(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:d(t,s,a)},related:e.related?async(r,n)=>await e.related(r,k(n)):void 0,async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?d(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?l(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),p(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),p(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),p(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),p(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:d(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),u=L(i.roles),y=async({ctx:w,next:k})=>{const p={auth:await z(w.auth??{},u),ctx:w};if(i.bypass?.(p)===!0)return k();const l=X(w.db,a,p,i.indexFields),O={db:l},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(l)),k({ctx:O})},g=new Map;for(const[w,k]of a)g.set(w,new Set(Object.keys(k)));return Q(y,{columns:g})};export{b as mask};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as W}from"@lunora/errors";import{findRelated as V}from"@lunora/shard-engine";import{i as j}from"./wire-codec-CH4vwdFT.mjs";import{bindTableFacade as ee,bindOrm as te}from"./bindOrm-D_hFUjmr.mjs";import{t as re}from"./policy-tag-V0lqFzgS.mjs";import{deny as ne}from"./allowAll-DkRAgItV.mjs";const se=["every","is","isNot","none","some"],oe=new Set(se),ie=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>oe.has(n))},q=(e,r,n)=>r?{[e]:n(r)}:{},ae=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,b=1,T=e=>e?b:B,p=(e,r)=>e<r?e:r,ce=(e,r)=>e>r?e:r,z=e=>e===v?v:T(e===B),Y=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,M=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},le={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},fe=(e,r,n)=>{let i=b;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(M(e,c,h),!Y(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=le[c];i=p(i,T(Y(r)&&f(r,h)))}}return i},K=(e,r,n)=>{if(!Array.isArray(n))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},Q=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?b:r.some(n=>S(n))?v:B,de=(e,r,n)=>{let i=b;if("in"in n&&(i=p(i,Q(r,K(e,"in",n.in)))),"notIn"in n&&(i=p(i,z(Q(r,K(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;M(e,"contains",c),i=S(r)?p(i,v):p(i,T(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,T(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?T(n===S(e)):S(e)?v:T(n===(e===r)),ue=(e,r,n)=>{let i=b;return"eq"in n&&(M(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(M(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},he=(e,r,n)=>p(ue(e,r,n),p(de(e,r,n),fe(e,r,n))),ye=(e,r,n,i)=>{if(r==="NOT")return z(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?b:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):ce(c,f)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",we=e=>j(e)&&Object.keys(e).every(r=>ae.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return H(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):ie(n)}),G=(e,r)=>{let n=b;for(const i of Object.keys(r)){const c=r[i];if(H(i)){n=p(n,ye(e,i,c,G));continue}const h=e[i];if(we(c)){n=p(n,he(i,h,c));continue}M(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>G(e,r)===b,X=500,I=(e,r,n)=>{const i=r??X;if(e>i)throw new W("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},pe=ne(),ge=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),We=e=>e[J],Oe=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},Re=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const h=c.when(r);if(h!==void 0){if(h===!0){i=!0;break}h!==!1&&n.push(h)}}if(!i)return n.length===0?pe:n.length===1?n[0]:{OR:n}},be=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return L(n,i)},Ae=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||be(e,r,n);if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!L(r.row,i)?!1:n===void 0||L(n,i)},Ee=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!Ae(h,n,i)))return!1;return c},Be=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),ve=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),Se=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>Be.has(n)&&ve(n,e[n]))},_e=e=>e===void 0?{}:j(e)&&Se(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,ke=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},R=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,Ie=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Te=(e,r,n)=>{const[i]=n,c=n.length===1&&i!==void 0?i.perTable:new Set(n.flatMap(t=>[...t.perTable.keys()])),h=new Map,f=t=>{const s=h.get(t);if(s)return s;const o=[];let a=!1;for(const y of n){const u=y.perTable.get(t);if(!u||u.length===0||!u.some(m=>m.on==="read"))continue;a=!0;const d=Re(u,y.context);d!==void 0&&o.push(d)}const l={baseWhere:ke(o),restricts:a};return h.set(t,l),l},_=(t,s,o,a)=>{for(const l of n){const y=l.perTable.get(t);if(y&&!Ee(y,s,{...l.context,row:o},a))return!1}return!0},w=t=>f(t).restricts?r:e,g=t=>f(t).baseWhere,A=async(t,s,o)=>{if(r.lookupById){const d=await r.lookupById(t,s);if(d)return{row:d.row,tableName:c.has(d.tableName)?d.tableName:void 0}}const a=await r.get(t,s);if(!a)return{row:null,tableName:void 0};const l=s??o,y=l===void 0?[...c.keys()]:[l].filter(d=>c.has(d)),u=await Promise.all(y.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:a,tableName:u.find(d=>d!==void 0)}},U=async(t,s,o)=>{const a=await A(t,s,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},O=async(t,s,o,a,l,y)=>{const u=await U(t,l,y);if(!u)return o(e);const d=a?a(u.row):void 0;if(!_(u.tableName,s,u.row,d))throw new W("FORBIDDEN",`${s} denied by policy`);return o(r)},E=(t,s)=>{const{baseWhere:o}=f(t);if($(o))throw new W("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`)},D=e.rankBefore,P=e.rankPageRows,{relationEdges:N}=e,k={...e,async count(t,s){const{baseWhere:o}=f(t),a=_e(s);return w(t).count(t,{...a,baseWhere:R(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,s,o)=>O(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??X),{baseWhere:a}=f(t);let l=0;for(;;){const u=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(d=>String(d._id));if(u.length===0)break;for(const d of u)await O(d,"delete",m=>m.delete(d,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(u.length<o)break}return{deleted:l}},async deleteMany(t,s,o){I(t.length,s?.limit,"deleteMany");for(const a of t)await O(a,"delete",l=>l.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s,a),relationBaseWhere:g})).page.map(u=>String(u._id));I(y.length,o?.limit,"deleteWhere");for(const u of y)await O(u,"delete",d=>d.delete(u),void 0,void 0,t);return{deleted:y.length}},async findFirst(t,s){const{baseWhere:o}=f(t);return w(t).findFirst(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:l}=f(o.tableName);if(!l)return e.get(t,s);if(!a)return o.row;const y=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return y?._id===t?y:null},async lookupById(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0||!f(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=f(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const l=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?{row:l,tableName:o.tableName}:null},async insert(t,s){if(c.has(t)){if(!_(t,"insert",s))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){if(I(s.length,o?.limit,"insertMany"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){if(I(s.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>O(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){I(t.length,s?.limit,"patchMany");for(const a of t)await O(a.id,"update",l=>l.patch(a.id,a.patch,o),l=>({...l,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s.where,a),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:s.patch}));return I(y.length,o?.limit,"patchWhere"),k.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(a=>L(a,s)):o},related:N===void 0?void 0:async(t,s)=>V({findMany:async(o,a)=>k.findMany(o,a),lookupById:async o=>r.lookupById?.(o)},N,t,{cursor:s?.cursor,depth:s?.depth,direction:s?.direction,edges:s?.edges,limit:s?.limit,relationMask:s?.relationMask}),restore:(t,s)=>O(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new W("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>O(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=f(t);return w(t).aggregate(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){return E(t,"rank"),w(t).rank(t,s,o)},rankPage(t,s,o){return E(t,"rankPage"),w(t).rankPage(t,s,o)},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...q("rankBefore",D,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...q("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},x=k;if(c.size>0)for(const[t,s]of Object.entries(e))Ie(s)&&(x[t]=ee(k,t));return Object.defineProperty(k,J,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),k},Z=e=>typeof e=="string"?e:e.name,Me=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>Z(i))));return r},De=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(Z(i))},Pe=["roles","role"],me=e=>{for(const r of Pe){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Ce=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...me(n),...e.roles??[]])];return{can:De(i,r),identity:n,roles:i,userId:e.userId??null}},qe=(e,r={})=>{const n=e,i=Oe(n),c=Me(r.roles);return re(async({ctx:f,next:_})=>{const w={auth:await Ce(f.auth??{},c),ctx:f},g=f.db,A=We(g),U=A?.base??g,O=A?.raw??g[ge]??g,E=Te(U,O,[...A?.steps??[],{context:w,perTable:i}]),D={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(D.orm=te(E)),_({ctx:D})},[{policies:n,roles:r.roles??[]}])};export{Ce as a,Ie as b,ie as c,me as d,De as e,Re as f,Ee as g,Me as i,L as m,q as o,Z as p,qe as r};
|
|
1
|
+
import{LunoraError as W}from"@lunora/errors";import{findRelated as V}from"@lunora/shard-engine";import{i as j}from"./wire-codec-BTOxkE1j.mjs";import{bindTableFacade as ee,bindOrm as te}from"./bindOrm-D_hFUjmr.mjs";import{t as re}from"./policy-tag-V0lqFzgS.mjs";import{deny as ne}from"./allowAll-DkRAgItV.mjs";const se=["every","is","isNot","none","some"],oe=new Set(se),ie=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>oe.has(n))},q=(e,r,n)=>r?{[e]:n(r)}:{},ae=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,b=1,T=e=>e?b:B,p=(e,r)=>e<r?e:r,ce=(e,r)=>e>r?e:r,z=e=>e===v?v:T(e===B),Y=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,M=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},le={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},fe=(e,r,n)=>{let i=b;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(M(e,c,h),!Y(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=le[c];i=p(i,T(Y(r)&&f(r,h)))}}return i},K=(e,r,n)=>{if(!Array.isArray(n))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},Q=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?b:r.some(n=>S(n))?v:B,de=(e,r,n)=>{let i=b;if("in"in n&&(i=p(i,Q(r,K(e,"in",n.in)))),"notIn"in n&&(i=p(i,z(Q(r,K(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;M(e,"contains",c),i=S(r)?p(i,v):p(i,T(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,T(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?T(n===S(e)):S(e)?v:T(n===(e===r)),ue=(e,r,n)=>{let i=b;return"eq"in n&&(M(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(M(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},he=(e,r,n)=>p(ue(e,r,n),p(de(e,r,n),fe(e,r,n))),ye=(e,r,n,i)=>{if(r==="NOT")return z(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?b:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):ce(c,f)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",we=e=>j(e)&&Object.keys(e).every(r=>ae.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return H(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):ie(n)}),G=(e,r)=>{let n=b;for(const i of Object.keys(r)){const c=r[i];if(H(i)){n=p(n,ye(e,i,c,G));continue}const h=e[i];if(we(c)){n=p(n,he(i,h,c));continue}M(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>G(e,r)===b,X=500,I=(e,r,n)=>{const i=r??X;if(e>i)throw new W("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},pe=ne(),ge=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),We=e=>e[J],Oe=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},Re=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const h=c.when(r);if(h!==void 0){if(h===!0){i=!0;break}h!==!1&&n.push(h)}}if(!i)return n.length===0?pe:n.length===1?n[0]:{OR:n}},be=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return L(n,i)},Ae=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||be(e,r,n);if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!L(r.row,i)?!1:n===void 0||L(n,i)},Ee=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!Ae(h,n,i)))return!1;return c},Be=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),ve=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),Se=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>Be.has(n)&&ve(n,e[n]))},_e=e=>e===void 0?{}:j(e)&&Se(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,ke=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},R=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,Ie=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Te=(e,r,n)=>{const[i]=n,c=n.length===1&&i!==void 0?i.perTable:new Set(n.flatMap(t=>[...t.perTable.keys()])),h=new Map,f=t=>{const s=h.get(t);if(s)return s;const o=[];let a=!1;for(const y of n){const u=y.perTable.get(t);if(!u||u.length===0||!u.some(m=>m.on==="read"))continue;a=!0;const d=Re(u,y.context);d!==void 0&&o.push(d)}const l={baseWhere:ke(o),restricts:a};return h.set(t,l),l},_=(t,s,o,a)=>{for(const l of n){const y=l.perTable.get(t);if(y&&!Ee(y,s,{...l.context,row:o},a))return!1}return!0},w=t=>f(t).restricts?r:e,g=t=>f(t).baseWhere,A=async(t,s,o)=>{if(r.lookupById){const d=await r.lookupById(t,s);if(d)return{row:d.row,tableName:c.has(d.tableName)?d.tableName:void 0}}const a=await r.get(t,s);if(!a)return{row:null,tableName:void 0};const l=s??o,y=l===void 0?[...c.keys()]:[l].filter(d=>c.has(d)),u=await Promise.all(y.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:a,tableName:u.find(d=>d!==void 0)}},U=async(t,s,o)=>{const a=await A(t,s,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},O=async(t,s,o,a,l,y)=>{const u=await U(t,l,y);if(!u)return o(e);const d=a?a(u.row):void 0;if(!_(u.tableName,s,u.row,d))throw new W("FORBIDDEN",`${s} denied by policy`);return o(r)},E=(t,s)=>{const{baseWhere:o}=f(t);if($(o))throw new W("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`)},D=e.rankBefore,P=e.rankPageRows,{relationEdges:N}=e,k={...e,async count(t,s){const{baseWhere:o}=f(t),a=_e(s);return w(t).count(t,{...a,baseWhere:R(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,s,o)=>O(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??X),{baseWhere:a}=f(t);let l=0;for(;;){const u=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(d=>String(d._id));if(u.length===0)break;for(const d of u)await O(d,"delete",m=>m.delete(d,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(u.length<o)break}return{deleted:l}},async deleteMany(t,s,o){I(t.length,s?.limit,"deleteMany");for(const a of t)await O(a,"delete",l=>l.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s,a),relationBaseWhere:g})).page.map(u=>String(u._id));I(y.length,o?.limit,"deleteWhere");for(const u of y)await O(u,"delete",d=>d.delete(u),void 0,void 0,t);return{deleted:y.length}},async findFirst(t,s){const{baseWhere:o}=f(t);return w(t).findFirst(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:l}=f(o.tableName);if(!l)return e.get(t,s);if(!a)return o.row;const y=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return y?._id===t?y:null},async lookupById(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0||!f(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=f(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const l=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?{row:l,tableName:o.tableName}:null},async insert(t,s){if(c.has(t)){if(!_(t,"insert",s))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){if(I(s.length,o?.limit,"insertMany"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){if(I(s.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>O(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){I(t.length,s?.limit,"patchMany");for(const a of t)await O(a.id,"update",l=>l.patch(a.id,a.patch,o),l=>({...l,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s.where,a),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:s.patch}));return I(y.length,o?.limit,"patchWhere"),k.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(a=>L(a,s)):o},related:N===void 0?void 0:async(t,s)=>V({findMany:async(o,a)=>k.findMany(o,a),lookupById:async o=>r.lookupById?.(o)},N,t,{cursor:s?.cursor,depth:s?.depth,direction:s?.direction,edges:s?.edges,limit:s?.limit,relationMask:s?.relationMask}),restore:(t,s)=>O(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new W("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>O(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=f(t);return w(t).aggregate(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){return E(t,"rank"),w(t).rank(t,s,o)},rankPage(t,s,o){return E(t,"rankPage"),w(t).rankPage(t,s,o)},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...q("rankBefore",D,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...q("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},x=k;if(c.size>0)for(const[t,s]of Object.entries(e))Ie(s)&&(x[t]=ee(k,t));return Object.defineProperty(k,J,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),k},Z=e=>typeof e=="string"?e:e.name,Me=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>Z(i))));return r},De=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(Z(i))},Pe=["roles","role"],me=e=>{for(const r of Pe){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Ce=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...me(n),...e.roles??[]])];return{can:De(i,r),identity:n,roles:i,userId:e.userId??null}},qe=(e,r={})=>{const n=e,i=Oe(n),c=Me(r.roles);return re(async({ctx:f,next:_})=>{const w={auth:await Ce(f.auth??{},c),ctx:f},g=f.db,A=We(g),U=A?.base??g,O=A?.raw??g[ge]??g,E=Te(U,O,[...A?.steps??[],{context:w,perTable:i}]),D={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(D.orm=te(E)),_({ctx:D})},[{policies:n,roles:r.roles??[]}])};export{Ce as a,Ie as b,ie as c,me as d,De as e,Re as f,Ee as g,Me as i,L as m,q as o,Z as p,qe as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{c as z}from"./compose-middleware-MCpZZKh7.mjs";import{v as B}from"@lunora/values";const _=["de","en","es","fr","it","nl","none","pt"],q=["native","portable"],H=e=>q.includes(e),Q=e=>_.includes(e),F=e=>{if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?F(t):e.kind},D=16,X={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),U=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),P=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},ce=e=>{const t={...e},n=[],r=[],i=[],d=[],u={},l=[],f={},h=U(),b=[];let w={kind:"root"},S=!1,N=!1,$=!1,T=!1,L,M,A,O;const R=a=>{if(w.kind!=="root"&&w.kind!==a.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=a},c={aggregateIndex(a,o){const m=o?.op??"count";if(m!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${a}": op "${m}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:a,on:"",op:m,where:o?.where}),c},get aggregateIndexes(){return n},get externalSource(){return O},commitOrdered(){return S=!0,c},get commitOrderedMode(){return S},externallyManaged(){return N=!0,c},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),c},get geoIndexes(){return r},global(a){return R({backend:a?.backend??"d1",kind:"global"}),c},get isExternallyManaged(){return N},get isPublic(){return T},index(a,o,m){return i.push({fields:o,name:a,unique:m?.unique??!1}),c},get indexes(){return i},memory(){return $=!0,c},get memoryMode(){return $},ownedBy(a){return L=a,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(a,o){return d.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:P(a,o.sortBy),where:o.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(a){return Object.assign(u,a(X)),c},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>D)throw new s("INTERNAL",`searchIndex "${a}": at most ${String(D)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:m}=o;if(m!==void 0&&!Q(m))throw new s("INTERNAL",`searchIndex "${a}": unknown language "${m}" (supported: ${_.join(", ")})`);const{strategy:p}=o;if(p!==void 0&&!H(p))throw new s("INTERNAL",`searchIndex "${a}": unknown strategy "${p}" (supported: ${q.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(a){return R({field:a,kind:"shardBy"}),c},get shardMode(){return w},get softDeleteMode(){return M},source(a){if(!a.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return O=a,N=!0,c},softDelete(a){const o=a?.field??"deletedAt";return M={field:o},o in t||(t[o]=B.optional(B.number().nullable())),c},get triggerMap(){return f},triggers(a){return Object.assign(f,a(h)),c},ttl(a,o){return A={after:o?.after,field:a},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(a,o){return b.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),c}};return c},ue=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),fe=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},he=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:P(e,t.sortBy),where:t.where}),I=e=>({...e,extend(t){return I(K(e,t))},jurisdiction(t){return I(e)},rls(t){return I({...e,rlsMode:t})}}),V=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},Y=(e,t,n)=>{for(const r of Object.values(t)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);i.aggregateIndexes.push(r)}for(const r of Object.values(n)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);i.rankIndexes.push(r)}},G=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},J=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=G(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},W=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);J(t,r)}}},Z=["_commitSeq","_creationTime","_id"],j="_commitSeq",ee=new Set(Z),x=(e,t,n,r)=>{if(!(ee.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const i=new Set;for(const d of n){if(i.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);i.add(d.name),r(d)}},C=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const i of r.fields)x(t,r.name,i,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const i of r.sortBy)x(t,r.name,i.field,n);for(const i of r.partitionBy??[])x(t,r.name,i,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const i of e)r[t(i)]=n(i);return r},te=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},me=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const i=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,te);(i||d||u)&&(t[n]={...i?{geo:i}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ne=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const i=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(i!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${i}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},re=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,i]of Object.entries(n.shape))if(F(i)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},ae=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(j))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${j}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},ge=(e,t={},n={},r={})=>(V(e),Y(e,n,r),W(e),ae(e),re(e),ne(e),C(e),I({tables:e,vectorIndexes:t})),y=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?y(t,e):e,oe=(e,t,n,r)=>{const i=y(t,r),d=h=>h===""?i:k(h,t,n),u={};for(const[h,b]of Object.entries(e.relationMap))u[h]={...b,table:k(b.table,t,n)};const l=e.aggregateIndexes.map(h=>({...h,on:d(h.on)})),f=e.rankIndexes.map(h=>({...h,on:d(h.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},be=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ie=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),we=(e,t)=>({...ie(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),K=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),i={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=y(n,u);if(Object.hasOwn(i,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);i[f]=oe(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=y(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:k(l.table,n,r)}}return C(i),{rlsMode:e.rlsMode,tables:i,vectorIndexes:d}},xe=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=K(n,r.extension));return n},Ie=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return z(t)};export{we as a,ie as b,Ie as c,fe as d,he as e,ge as f,be as g,ce as h,ue as i,me as j,xe as k,K as m,C as v};
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{c as z}from"./compose-middleware-DNvrHMHx.mjs";import{v as B}from"@lunora/values";const _=["de","en","es","fr","it","nl","none","pt"],q=["native","portable"],H=e=>q.includes(e),Q=e=>_.includes(e),F=e=>{if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?F(t):e.kind},D=16,X={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),U=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),P=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},ce=e=>{const t={...e},n=[],r=[],i=[],d=[],u={},l=[],f={},h=U(),b=[];let w={kind:"root"},S=!1,N=!1,$=!1,T=!1,L,M,A,O;const R=a=>{if(w.kind!=="root"&&w.kind!==a.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=a},c={aggregateIndex(a,o){const m=o?.op??"count";if(m!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${a}": op "${m}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:a,on:"",op:m,where:o?.where}),c},get aggregateIndexes(){return n},get externalSource(){return O},commitOrdered(){return S=!0,c},get commitOrderedMode(){return S},externallyManaged(){return N=!0,c},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),c},get geoIndexes(){return r},global(a){return R({backend:a?.backend??"d1",kind:"global"}),c},get isExternallyManaged(){return N},get isPublic(){return T},index(a,o,m){return i.push({fields:o,name:a,unique:m?.unique??!1}),c},get indexes(){return i},memory(){return $=!0,c},get memoryMode(){return $},ownedBy(a){return L=a,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(a,o){return d.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:P(a,o.sortBy),where:o.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(a){return Object.assign(u,a(X)),c},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>D)throw new s("INTERNAL",`searchIndex "${a}": at most ${String(D)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:m}=o;if(m!==void 0&&!Q(m))throw new s("INTERNAL",`searchIndex "${a}": unknown language "${m}" (supported: ${_.join(", ")})`);const{strategy:p}=o;if(p!==void 0&&!H(p))throw new s("INTERNAL",`searchIndex "${a}": unknown strategy "${p}" (supported: ${q.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(a){return R({field:a,kind:"shardBy"}),c},get shardMode(){return w},get softDeleteMode(){return M},source(a){if(!a.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return O=a,N=!0,c},softDelete(a){const o=a?.field??"deletedAt";return M={field:o},o in t||(t[o]=B.optional(B.number().nullable())),c},get triggerMap(){return f},triggers(a){return Object.assign(f,a(h)),c},ttl(a,o){return A={after:o?.after,field:a},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(a,o){return b.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),c}};return c},ue=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),fe=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},he=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:P(e,t.sortBy),where:t.where}),I=e=>({...e,extend(t){return I(K(e,t))},jurisdiction(t){return I(e)},rls(t){return I({...e,rlsMode:t})}}),V=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},Y=(e,t,n)=>{for(const r of Object.values(t)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);i.aggregateIndexes.push(r)}for(const r of Object.values(n)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);i.rankIndexes.push(r)}},G=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},J=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=G(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},W=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);J(t,r)}}},Z=["_commitSeq","_creationTime","_id"],j="_commitSeq",ee=new Set(Z),x=(e,t,n,r)=>{if(!(ee.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const i=new Set;for(const d of n){if(i.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);i.add(d.name),r(d)}},C=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const i of r.fields)x(t,r.name,i,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const i of r.sortBy)x(t,r.name,i.field,n);for(const i of r.partitionBy??[])x(t,r.name,i,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const i of e)r[t(i)]=n(i);return r},te=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},me=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const i=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,te);(i||d||u)&&(t[n]={...i?{geo:i}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ne=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const i=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(i!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${i}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},re=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,i]of Object.entries(n.shape))if(F(i)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},ae=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(j))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${j}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},ge=(e,t={},n={},r={})=>(V(e),Y(e,n,r),W(e),ae(e),re(e),ne(e),C(e),I({tables:e,vectorIndexes:t})),y=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?y(t,e):e,oe=(e,t,n,r)=>{const i=y(t,r),d=h=>h===""?i:k(h,t,n),u={};for(const[h,b]of Object.entries(e.relationMap))u[h]={...b,table:k(b.table,t,n)};const l=e.aggregateIndexes.map(h=>({...h,on:d(h.on)})),f=e.rankIndexes.map(h=>({...h,on:d(h.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},be=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ie=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),we=(e,t)=>({...ie(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),K=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),i={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=y(n,u);if(Object.hasOwn(i,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);i[f]=oe(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=y(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:k(l.table,n,r)}}return C(i),{rlsMode:e.rlsMode,tables:i,vectorIndexes:d}},xe=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=K(n,r.extension));return n},Ie=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return z(t)};export{we as a,ie as b,Ie as c,fe as d,he as e,ge as f,be as g,ce as h,ue as i,me as j,xe as k,K as m,C as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as t}from"./compose-middleware-
|
|
1
|
+
import{c as t}from"./compose-middleware-DNvrHMHx.mjs";const i=c=>{const e=[c.rateLimit,c.captcha,...c.use??[]].filter(r=>r!==void 0);return t(e)};export{i as protectPublic};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./wire-codec-
|
|
1
|
+
import"./wire-codec-BTOxkE1j.mjs";import"./bindOrm-D_hFUjmr.mjs";import{f as t,g as m,i as p,b as l,m as d,p as n,d as c,e as h,a as u,r as v}from"./middleware-CgYaL-lL.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,n as permissionName,c as readIdentityRoles,h as resolveCan,u as resolvePolicyAuth,v as rls};
|
package/dist/packem_shared/{serveStorageObject-BzZEP-B5.mjs → serveStorageObject-9mdw0nyU.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isSafeHeaderValue as l}from"./httpAction-
|
|
1
|
+
import{isSafeHeaderValue as l}from"./httpAction-DFVhrm8u.mjs";const h=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,f=(t,e)=>{if(t===null)return{kind:"full"};const n=h.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let o,r;if(s===""){const i=Number(a);if(i===0)return{kind:"unsatisfiable"};o=Math.max(0,e-i),r=e-1}else o=Number(s),r=a===""?e-1:Math.min(Number(a),e-1);return o>r||o>=e?{kind:"unsatisfiable"}:{end:r,kind:"partial",start:o}},m=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),p=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&l(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return m.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},w=t=>f(t,0).kind==="full",u=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...p(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},b=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},y=async(t,e,n,s,a="no-store")=>{if(!await b(s,e,n))return new Response("Forbidden",{status:403});const o=n.headers.get("range");if(w(o))return u(t,e,a);const r=await t.storage.head(e);if(!r)return new Response("Not Found",{status:404});const i=f(o,r.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(r.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(r.etag)},status:416});if(i.kind==="full")return u(t,e,a);const c=i.end-i.start+1,d=await t.storage.download(e,{range:{length:c,offset:i.start}});return d?new Response(d.body,{headers:{...p(r,a),"content-length":String(c),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(r.size)}`},status:206}):new Response("Not Found",{status:404})};export{y as serveStorageObject};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-CgYaL-lL.mjs";const N=(e,t,o)=>{const a=s=>o.isAllowed("list",s,t)&&o.isAllowed("read",s,t),{get:r,query:b}=e,l={...e},w=s=>s.filter(n=>typeof n.key=="string"&&a(n.key));return typeof r=="function"&&(l.get=async(s,n)=>(s==="_storage"&&o.assertAllowed("read",n,t),r(s,n))),typeof b=="function"&&(l.query=s=>{const n=b(s),{collect:p}=n;return s!=="_storage"||typeof p!="function"?n:{...n,collect:async()=>w(await p())}}),l},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},D=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",D],["getUrl","read"],["head","read"],["store","write"]],M=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},P=(e,t)=>{const o=e.bucketName??"default",{bucket:a}=e;for(const r of new Set(t))if(!(r===o||typeof a=="function"&&M(a,r)))throw new A("INTERNAL",`storageRules: rule for bucket "${r}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${r}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},C=(e,t={})=>{const o=U(t.roles);return async({ctx:a,next:r})=>{const b=await $(a.auth??{},o),l=(c,u,d)=>{const h=e.filter(i=>i.on===c&&i.bucket===d);if(h.length===0)return!0;const f={auth:b,ctx:a,key:u};return h.some(i=>S(i.prefix,u)&&i.when(f)===!0)},w=(c,u,d)=>{if(!l(c,u,d))throw new A("FORBIDDEN",`storage ${c} on "${u}" in bucket "${d}" denied by access rule`)},s=c=>{const u=c.bucketName??"default",d={bucketName:u};for(const[f,i]of E){const k=c[f];typeof k=="function"&&(d[f]=(...y)=>{const R=typeof y[0]=="string"?y[0]:"",v=typeof i=="function"?i(y):i;return w(v,R,u),k(...y)})}const{bucket:h}=c;return typeof h=="function"&&(d.bucket=f=>s(h(f))),d},n=a.storage;if(n===void 0)return r();P(n,e.map(c=>c.bucket));const p={storage:s(n)},g=a.db,m=g?.system;return g!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...g,system:N(m,n.bucketName??"default",{assertAllowed:w,isAllowed:l})}),r({ctx:p})}};export{C as storageRules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const m=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},
|
|
1
|
+
const m=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},A=e=>{const t=atob(e),a=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)a[o]=t.codePointAt(o)??0;return a},i="$lunora.wire$";const w="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},p={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},b=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const a=typeof e;if(a==="bigint")return[i,"bigint",e.toString()];if(a==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(a!=="object")return e;if(e instanceof Date)return[i,"date",b(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const c of Object.keys(r)){if(r[c]===void 0)continue;const u=b(r[c],t+1);c===w?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:u,writable:!0}):n[c]=u}const s=[i,"error",String(r.name),String(r.message),n];return r.cause!==void 0&&s.push(b(r.cause,t+1)),s}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[b(r,t+1),b(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>b(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",m(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",m(s)]:[i,"bytes",m(s),n]}if(Array.isArray(e)){const r=e.map(n=>b(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!l(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,f={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const s=b(n,t+1);r===w?Object.defineProperty(f,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):f[r]=s}return f},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(p,r)?p[r]:void 0)??Error,c=new s(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const u=y(e[4],t+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(u))d===w?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=A(r);if(m(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const c=Object.hasOwn(g,s)?g[s]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(f=>y(f,t+1))}const a=e,o={};for(const f of Object.keys(a)){const r=y(a[f],t+1);f===w?Object.defineProperty(o,f,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[f]=r}return o},E=(e,t,a)=>{try{return b(a)}catch(o){throw new TypeError(`${e}: cannot encode args for '${t}' — ${o instanceof Error?o.message:String(o)}`,o instanceof Error?{cause:o}:void 0)}};export{b as a,y as d,E as e,l as i};
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as y,d as P,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-
|
|
1
|
+
import{i as y,d as P,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-CgYaL-lL.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.125",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -67,8 +67,8 @@
|
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
69
|
"@lunora/errors": "1.0.0-alpha.36",
|
|
70
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
71
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
70
|
+
"@lunora/scheduler": "1.0.0-alpha.73",
|
|
71
|
+
"@lunora/shard-engine": "1.0.0-alpha.68",
|
|
72
72
|
"@lunora/values": "1.0.0-alpha.46",
|
|
73
73
|
"drizzle-orm": "^0.45.2",
|
|
74
74
|
"hono": "^4.13.7"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{assertScheduleInstant as g,assertScheduleDelay as m,resolveScheduleId as v}from"@lunora/scheduler";const p=new WeakMap,h=d=>{let e=d;for(;e!==void 0&&!e.open;)e=e.parent;return e},y=d=>{const e=d,c={innermost:void 0},o=(n,t,r,s,u)=>e[n].call(e,t,r,s,u),l=(n,t,r,s,u)=>{const a=c.innermost;if(a===void 0)return o(n,t,r,s,u);const f=v(u?.id);return a.pending.push(async()=>o(n,t,r,s,{...u,id:f})),Promise.resolve(f)},i={...e,runAfter:(n,t,r,s)=>(m(n,"ctx.scheduler.runAfter"),l("runAfter",n,t,r,s)),runAt:(n,t,r,s)=>(g(n,Date.now(),"ctx.scheduler.runAt"),l("runAt",n,t,r,s))};return Object.setPrototypeOf(i,Object.getPrototypeOf(e)),p.set(i,c),i},A=d=>{const{scheduler:e}=d,c=typeof e=="object"&&e!==null?p.get(e):void 0;if(!c)return async()=>{};const o={open:!0,parent:c.innermost,pending:[]};return c.innermost=o,async l=>{if(!o.open)return;o.open=!1,c.innermost===o&&(c.innermost=h(o.parent));const i=o.pending.splice(0);if(!l||i.length===0)return;const n=h(o.parent);if(n!==void 0){n.pending.push(...i);return}const t=[];for(const u of i)try{await u()}catch(a){t.push(a)}const[r,...s]=t;if(r!==void 0)throw s.length===0?r:new AggregateError(t,`ctx.scheduler: ${String(t.length)} of ${String(i.length)} deferred jobs failed to reach the scheduler after the commit`)}};export{A as beginDeferredSchedules,y as withDeferredSchedules};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{unionMaskColumns as n,tagMaskMiddleware as d}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as m,t as i}from"./policy-tag-V0lqFzgS.mjs";import{r as c}from"./run-middleware-laenw2jQ.mjs";const g=s=>{const o=(async({ctx:r,next:e})=>c(s,r,l=>e({ctx:l}))),a=s.flatMap(r=>m(r));a.length>0&&i(o,a);const t=n(s);return t&&d(o,{columns:t}),o};export{g as c};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as j}from"./apply-output-C5wZ5EAL.mjs";import{v as i}from"./functions-B2-H4PQT.mjs";import{unionMaskColumns as w}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as C}from"./policy-tag-V0lqFzgS.mjs";import{r as b}from"./run-middleware-laenw2jQ.mjs";const h=(e,r,o,n)=>n===0&&r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{args:Object.freeze({...o}),...r===void 0?{}:{meta:r}}),y=(e,r)=>b(e,r,o=>o),M=(e,r,o,n,t)=>async(s,c)=>{const d=i(e,c),m=await y(r,h(s,t,d,r.length)),l=await o({args:d,ctx:m});return n?j(n,l):l},O=(e,r,o,n)=>(t,s,c)=>{const d=i(e,s);return(async function*(){const l=await y(r,h(t,n,d,r.length)),f=o({args:d,ctx:l,signal:c})[Symbol.asyncIterator]();try{for(;;){if(c.aborted)return;const p=await f.next();if(p.done||c.aborted)return;yield p.value}}finally{await f.return?.()}})()},g=e=>{const r=e.flatMap(o=>C(o));return r.length>0?{tags:r}:void 0},x=e=>{for(const r of["add","clear","delete","set"])typeof e[r]=="function"&&Object.defineProperty(e,r,{configurable:!1,enumerable:!1,value:()=>{throw new TypeError(`Cannot mutate a frozen .meta() declaration (${e.constructor.name}.${r})`)},writable:!1})},u=(e,r)=>{if(e===null||typeof e!="object"||r.has(e))return e;if(r.add(e),e instanceof Map){for(const[o,n]of e)u(o,r),u(n,r);x(e)}else if(e instanceof Set){for(const o of e)u(o,r);x(e)}for(const o of Object.values(e))u(o,r);return Object.freeze(e),e},z=e=>u(structuredClone(e),new WeakSet),a=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:n=>a(e,{...r,args:{...r.args,...n}},o),[e]:n=>{const t=g(r.middlewares),s=w(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:M(r.args,r.middlewares,n,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...t?{rls:t}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:n=>a(e,{...r,meta:z({...r.meta,...n})},o),output:n=>a(e,{...r,output:n},o),...e==="query"?{stream:(n,t)=>{const s=g(r.middlewares),c=w(r.middlewares),d=t?.durable===!0?{}:t?.durable;return{args:r.args,...d?{durable:d}:{},...r.expose?{expose:r.expose}:{},handler:O(r.args,r.middlewares,n,r.meta),kind:"stream",...c?{maskedTables:c}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:n=>a(e,{...r,middlewares:[...r.middlewares,n]},o),...o?{}:{expose:n=>a(e,{...r,expose:n},o)},...o?{}:{x402:n=>a(e,{...r,x402:n},o)}}),H={dataModel:()=>({create:e=>({action:a("action",{args:{},middlewares:[]}),internalAction:a("action",{args:{},middlewares:[]},"internal"),internalMutation:a("mutation",{args:{},middlewares:[]},"internal"),internalQuery:a("query",{args:{},middlewares:[]},"internal"),mutation:a("mutation",{args:{},middlewares:[]}),query:a("query",{args:{},middlewares:[]})})})};export{H as initLunora};
|