@lunora/server 1.0.0-alpha.194 → 1.0.0-alpha.195
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/in-process.mjs +1 -1
- package/dist/index.d.mts +45 -13
- package/dist/index.d.ts +45 -13
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-CPywsACf.mjs → ACTION_CACHE_DEFAULT_TTL_MS-BFmhdKJG.mjs} +1 -1
- package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-D2Yzbu0B.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-BeS7G0yM.mjs} +1 -1
- package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-BH2zGHxn.mjs → PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs} +1 -1
- package/dist/packem_shared/{assertShapesDeclareReadPolicies-DV6ejDpe.mjs → assertShapesDeclareReadPolicies-isd_Yupt.mjs} +1 -1
- package/dist/packem_shared/bindOrm-BHq_oUP2.mjs +1 -0
- package/dist/packem_shared/{composePluginMiddleware-CSwsfLtS.mjs → composePluginMiddleware-ZtDIkbvJ.mjs} +1 -1
- package/dist/packem_shared/{defineAggregateIndex-DR1_vB45.mjs → defineAggregateIndex-DF8NiKHr.mjs} +1 -1
- package/dist/packem_shared/{defineShape-dWV0tQBF.mjs → defineShape-CX9Xs8AY.mjs} +1 -1
- package/dist/packem_shared/mask-BdULkLAu.mjs +1 -0
- package/dist/packem_shared/{middleware-BZAwl2WQ.mjs → middleware-DbhB1jRk.mjs} +1 -1
- package/dist/packem_shared/plugin-Bm9wIpiI.mjs +1 -0
- package/dist/packem_shared/{rls-CpVetPZf.mjs → rls-B3xf3YrN.mjs} +1 -1
- package/dist/packem_shared/{storageRules-DUWOC6r7.mjs → storageRules-CMfQu8yY.mjs} +1 -1
- package/dist/rls/testing.mjs +1 -1
- package/dist/types.d.mts +35 -7
- package/dist/types.d.ts +35 -7
- package/package.json +4 -4
- package/dist/packem_shared/bindOrm-BaAMwCFL.mjs +0 -1
- package/dist/packem_shared/mask-DDttugol.mjs +0 -1
- package/dist/packem_shared/plugin-DsVYnlmv.mjs +0 -1
package/dist/in-process.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as I}from"@lunora/errors";import{runShardMigrations as R,TransactionHeadroomTracker as h,createShardCtxDb as T,RLS_UNWRAP_SYMBOL as g}from"@lunora/shard-engine";import{beginDeferredSchedules as p}from"./packem_shared/beginDeferredSchedules-CmmdpWRS.mjs";import{bindTableFacade as y}from"./packem_shared/bindOrm-BHq_oUP2.mjs";const k=e=>{if(e===null||typeof e.userId!="string"||e.userId.length===0)return{claims:null,userId:null};const{userId:r,...s}=e;return{claims:Object.keys(s).length>0?s:null,userId:r}};class S extends h{current=new h;reset(){this.current=new h}headroom(){return this.current.headroom()}recordRead(r){this.current.recordRead(r)}recordWrite(r){this.current.recordWrite(r)}}const x=(e,r)=>{const{scheduler:s,sql:a}=r,i=e;R(a,i);const c=new S,m=t=>{const n=t;for(const o of Object.keys(i.tables))n[o]=y(t,o);return t};let u=!1;const w=t=>{const n=T({auth:{identity:t.claims,userId:t.userId},enforceRls:r.enforceRls??!0,headroom:c,inTransaction:()=>u,schema:i,sql:a}),o=n[g]??n;return{database:m(n),rawDatabase:m(o)}},l=t=>{a.exec.call(a,t)};let f=Promise.resolve();return{createWriters:w,resetHeadroom:()=>{c.reset()},runInTransaction:t=>{const n=async()=>{const b=p({scheduler:s});c.reset(),l("BEGIN"),u=!0;try{const d=await t();return l("COMMIT"),u=!1,await b(!0),d}catch(d){u=!1;try{l("ROLLBACK")}catch{}throw await b(!1),d}},o=f.then(n);return f=o.then(()=>{},()=>{}),o}}},v=e=>{if(typeof e!="object"||e===null)return;const{kind:r}=e;if(r==="query"||r==="mutation"||r==="action")return r},A=(e,r,s,a,i)=>{const c=v(r);if(c!==e)throw new I("INTERNAL",`expected a registered ${e}, received a ${c??"non-function"} reference`);if(!i&&r.visibility==="internal")throw new I("INTERNAL",`This ${e} is an internal function — it is unreachable from the external RPC boundary in production. Call it through ctx.run${e.charAt(0).toUpperCase()}${e.slice(1)} from another function instead.`);return Promise.resolve(r.handler(s,a??{}))};export{x as createInProcessRuntime,v as registeredFunctionKind,k as resolveInProcessIdentity,A as runRegisteredFunction};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Validator, Infer, ColumnValidator, v, Id, ValidatorMap, InferValidatorMap } from '@lunora/values';
|
|
2
2
|
export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
|
|
3
|
-
import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend,
|
|
3
|
+
import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, KeyedRelationDefinition, RelationThrough, ThroughRelationDefinition, OnDeleteAction, RelationDefinition, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook, WhisperEvent } from "./types.mjs";
|
|
4
4
|
export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, PatchIfResult, RankSortKey, ReadOnlyStorage, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, SearchFilterBuilder, SearchIndexDefinition, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerCtx, TriggerDatabase, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorMatch, VectorMatches, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows } from "./types.mjs";
|
|
5
5
|
import { LunoraError } from '@lunora/errors';
|
|
6
6
|
export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
|
|
@@ -573,22 +573,35 @@ interface VectorizeOptions<Shape extends Record<string, Validator> = Record<stri
|
|
|
573
573
|
model?: string;
|
|
574
574
|
}
|
|
575
575
|
/** A `one` (many-to-one) relation descriptor; phantom `Target` carries the target table name. */
|
|
576
|
-
interface OneRelation<Target extends string = string> extends
|
|
576
|
+
interface OneRelation<Target extends string = string> extends KeyedRelationDefinition {
|
|
577
577
|
readonly __target?: Target;
|
|
578
578
|
readonly kind: "one";
|
|
579
579
|
}
|
|
580
580
|
/** A `many` (one-to-many) relation descriptor; phantom `Target` carries the target table name. */
|
|
581
|
-
interface ManyRelation<Target extends string = string> extends
|
|
581
|
+
interface ManyRelation<Target extends string = string> extends KeyedRelationDefinition {
|
|
582
582
|
readonly __target?: Target;
|
|
583
583
|
readonly kind: "many";
|
|
584
584
|
}
|
|
585
|
+
/** A `many` relation through a join table (many-to-many); phantom `Target` carries the target table name. */
|
|
586
|
+
interface ThroughManyRelation<Target extends string = string> extends ThroughRelationDefinition {
|
|
587
|
+
readonly __target?: Target;
|
|
588
|
+
}
|
|
585
589
|
/** The `r` argument passed to `.relations((r) => …)`. */
|
|
586
590
|
interface RelationBuilder {
|
|
587
|
-
/**
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
591
|
+
/**
|
|
592
|
+
* One-to-many (`field`): the FK `field` lives on the target table, matching this table's `references` (default `_id`).
|
|
593
|
+
* Many-to-many (`through`): `through.table` holds one row per linked pair, `through.from` pointing at this table's
|
|
594
|
+
* `_id` and `through.to` at the target's `_id`.
|
|
595
|
+
*/
|
|
596
|
+
many: {
|
|
597
|
+
<Target extends string>(table: Target, options: {
|
|
598
|
+
field: string;
|
|
599
|
+
references?: string;
|
|
600
|
+
}): ManyRelation<Target>;
|
|
601
|
+
<Target extends string>(table: Target, options: {
|
|
602
|
+
through: RelationThrough;
|
|
603
|
+
}): ThroughManyRelation<Target>;
|
|
604
|
+
};
|
|
592
605
|
/** Many-to-one: the FK `field` lives on this table, pointing at `table`.`references` (default `_id`). */
|
|
593
606
|
one: <Target extends string>(table: Target, options: {
|
|
594
607
|
field: string;
|
|
@@ -1607,16 +1620,35 @@ declare const defineEnv: <S extends EnvShape>(shape: S) => EnvAccessor<S>;
|
|
|
1607
1620
|
* The slice of `@lunora/shard-engine`'s `RelationWriteInfo` this reads. Declared here rather than imported so the
|
|
1608
1621
|
* facade's public types do not drag `@lunora/shard-engine` into the declarations of every package built on them.
|
|
1609
1622
|
*/
|
|
1610
|
-
interface
|
|
1623
|
+
interface RelationWriteBaseLike {
|
|
1611
1624
|
readonly colocated: boolean;
|
|
1625
|
+
/** Set by a wrapper that must forbid writes through this relation, with the reason the caller is told. */
|
|
1626
|
+
readonly refusal?: string;
|
|
1627
|
+
readonly table: string;
|
|
1628
|
+
}
|
|
1629
|
+
/** A `one` or `many` relation backed by one foreign-key column. */
|
|
1630
|
+
interface KeyedRelationWriteInfoLike extends RelationWriteBaseLike {
|
|
1612
1631
|
readonly field: string;
|
|
1613
1632
|
readonly kind: "many" | "one";
|
|
1614
1633
|
readonly nullable: boolean;
|
|
1615
1634
|
readonly references: string;
|
|
1616
|
-
|
|
1617
|
-
readonly
|
|
1618
|
-
|
|
1635
|
+
readonly refusalNow?: never;
|
|
1636
|
+
readonly through?: never;
|
|
1637
|
+
}
|
|
1638
|
+
/** A many-to-many relation: the link is a row of the join table, so there is no foreign key to null and the owner side is always `_id`. */
|
|
1639
|
+
interface ThroughRelationWriteInfoLike extends RelationWriteBaseLike {
|
|
1640
|
+
readonly kind: "many";
|
|
1641
|
+
/** Is the (`from`, `to`) pair the join table's only uniqueness rule, so a unique conflict on a join insert can only be that pair? */
|
|
1642
|
+
readonly pairIsOnlyUnique: boolean;
|
|
1643
|
+
/** Asked when the write runs: the reason it cannot run right now (outside a transaction), or `undefined`. */
|
|
1644
|
+
readonly refusalNow: () => string | undefined;
|
|
1645
|
+
readonly through: {
|
|
1646
|
+
readonly from: string;
|
|
1647
|
+
readonly table: string;
|
|
1648
|
+
readonly to: string;
|
|
1649
|
+
};
|
|
1619
1650
|
}
|
|
1651
|
+
type RelationWriteInfoLike = KeyedRelationWriteInfoLike | ThroughRelationWriteInfoLike;
|
|
1620
1652
|
type RelationWriteInfosLike = Readonly<Record<string, RelationWriteInfoLike>>;
|
|
1621
1653
|
/**
|
|
1622
1654
|
* Minimal structural writer the facade binds over. Declared with **method**
|
|
@@ -3907,4 +3939,4 @@ type RegisteredWhisperAuthorizer = RegisteredFunction<Record<string, never>, boo
|
|
|
3907
3939
|
*/
|
|
3908
3940
|
declare const onWhisper: (handler: WhisperAuthorizeHandler) => RegisteredWhisperAuthorizer;
|
|
3909
3941
|
declare const VERSION = "0.0.0";
|
|
3910
|
-
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 ModuleConfig, type ModuleDefinition, 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 PlatformAdminCheck, 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 RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, 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, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineMigration, defineModule, 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, onWhisper, platformAdmin, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, tagPerDispatchMiddleware, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
|
3942
|
+
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 ModuleConfig, type ModuleDefinition, 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 PlatformAdminCheck, 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 RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, 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, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineMigration, defineModule, 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, onWhisper, platformAdmin, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, tagPerDispatchMiddleware, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Validator, Infer, ColumnValidator, v, Id, ValidatorMap, InferValidatorMap } from '@lunora/values';
|
|
2
2
|
export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
|
|
3
|
-
import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend,
|
|
3
|
+
import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, KeyedRelationDefinition, RelationThrough, ThroughRelationDefinition, OnDeleteAction, RelationDefinition, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook, WhisperEvent } from "./types.js";
|
|
4
4
|
export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, PatchIfResult, RankSortKey, ReadOnlyStorage, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, SearchFilterBuilder, SearchIndexDefinition, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerCtx, TriggerDatabase, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorMatch, VectorMatches, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows } from "./types.js";
|
|
5
5
|
import { LunoraError } from '@lunora/errors';
|
|
6
6
|
export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
|
|
@@ -573,22 +573,35 @@ interface VectorizeOptions<Shape extends Record<string, Validator> = Record<stri
|
|
|
573
573
|
model?: string;
|
|
574
574
|
}
|
|
575
575
|
/** A `one` (many-to-one) relation descriptor; phantom `Target` carries the target table name. */
|
|
576
|
-
interface OneRelation<Target extends string = string> extends
|
|
576
|
+
interface OneRelation<Target extends string = string> extends KeyedRelationDefinition {
|
|
577
577
|
readonly __target?: Target;
|
|
578
578
|
readonly kind: "one";
|
|
579
579
|
}
|
|
580
580
|
/** A `many` (one-to-many) relation descriptor; phantom `Target` carries the target table name. */
|
|
581
|
-
interface ManyRelation<Target extends string = string> extends
|
|
581
|
+
interface ManyRelation<Target extends string = string> extends KeyedRelationDefinition {
|
|
582
582
|
readonly __target?: Target;
|
|
583
583
|
readonly kind: "many";
|
|
584
584
|
}
|
|
585
|
+
/** A `many` relation through a join table (many-to-many); phantom `Target` carries the target table name. */
|
|
586
|
+
interface ThroughManyRelation<Target extends string = string> extends ThroughRelationDefinition {
|
|
587
|
+
readonly __target?: Target;
|
|
588
|
+
}
|
|
585
589
|
/** The `r` argument passed to `.relations((r) => …)`. */
|
|
586
590
|
interface RelationBuilder {
|
|
587
|
-
/**
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
591
|
+
/**
|
|
592
|
+
* One-to-many (`field`): the FK `field` lives on the target table, matching this table's `references` (default `_id`).
|
|
593
|
+
* Many-to-many (`through`): `through.table` holds one row per linked pair, `through.from` pointing at this table's
|
|
594
|
+
* `_id` and `through.to` at the target's `_id`.
|
|
595
|
+
*/
|
|
596
|
+
many: {
|
|
597
|
+
<Target extends string>(table: Target, options: {
|
|
598
|
+
field: string;
|
|
599
|
+
references?: string;
|
|
600
|
+
}): ManyRelation<Target>;
|
|
601
|
+
<Target extends string>(table: Target, options: {
|
|
602
|
+
through: RelationThrough;
|
|
603
|
+
}): ThroughManyRelation<Target>;
|
|
604
|
+
};
|
|
592
605
|
/** Many-to-one: the FK `field` lives on this table, pointing at `table`.`references` (default `_id`). */
|
|
593
606
|
one: <Target extends string>(table: Target, options: {
|
|
594
607
|
field: string;
|
|
@@ -1607,16 +1620,35 @@ declare const defineEnv: <S extends EnvShape>(shape: S) => EnvAccessor<S>;
|
|
|
1607
1620
|
* The slice of `@lunora/shard-engine`'s `RelationWriteInfo` this reads. Declared here rather than imported so the
|
|
1608
1621
|
* facade's public types do not drag `@lunora/shard-engine` into the declarations of every package built on them.
|
|
1609
1622
|
*/
|
|
1610
|
-
interface
|
|
1623
|
+
interface RelationWriteBaseLike {
|
|
1611
1624
|
readonly colocated: boolean;
|
|
1625
|
+
/** Set by a wrapper that must forbid writes through this relation, with the reason the caller is told. */
|
|
1626
|
+
readonly refusal?: string;
|
|
1627
|
+
readonly table: string;
|
|
1628
|
+
}
|
|
1629
|
+
/** A `one` or `many` relation backed by one foreign-key column. */
|
|
1630
|
+
interface KeyedRelationWriteInfoLike extends RelationWriteBaseLike {
|
|
1612
1631
|
readonly field: string;
|
|
1613
1632
|
readonly kind: "many" | "one";
|
|
1614
1633
|
readonly nullable: boolean;
|
|
1615
1634
|
readonly references: string;
|
|
1616
|
-
|
|
1617
|
-
readonly
|
|
1618
|
-
|
|
1635
|
+
readonly refusalNow?: never;
|
|
1636
|
+
readonly through?: never;
|
|
1637
|
+
}
|
|
1638
|
+
/** A many-to-many relation: the link is a row of the join table, so there is no foreign key to null and the owner side is always `_id`. */
|
|
1639
|
+
interface ThroughRelationWriteInfoLike extends RelationWriteBaseLike {
|
|
1640
|
+
readonly kind: "many";
|
|
1641
|
+
/** Is the (`from`, `to`) pair the join table's only uniqueness rule, so a unique conflict on a join insert can only be that pair? */
|
|
1642
|
+
readonly pairIsOnlyUnique: boolean;
|
|
1643
|
+
/** Asked when the write runs: the reason it cannot run right now (outside a transaction), or `undefined`. */
|
|
1644
|
+
readonly refusalNow: () => string | undefined;
|
|
1645
|
+
readonly through: {
|
|
1646
|
+
readonly from: string;
|
|
1647
|
+
readonly table: string;
|
|
1648
|
+
readonly to: string;
|
|
1649
|
+
};
|
|
1619
1650
|
}
|
|
1651
|
+
type RelationWriteInfoLike = KeyedRelationWriteInfoLike | ThroughRelationWriteInfoLike;
|
|
1620
1652
|
type RelationWriteInfosLike = Readonly<Record<string, RelationWriteInfoLike>>;
|
|
1621
1653
|
/**
|
|
1622
1654
|
* Minimal structural writer the facade binds over. Declared with **method**
|
|
@@ -3907,4 +3939,4 @@ type RegisteredWhisperAuthorizer = RegisteredFunction<Record<string, never>, boo
|
|
|
3907
3939
|
*/
|
|
3908
3940
|
declare const onWhisper: (handler: WhisperAuthorizeHandler) => RegisteredWhisperAuthorizer;
|
|
3909
3941
|
declare const VERSION = "0.0.0";
|
|
3910
|
-
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 ModuleConfig, type ModuleDefinition, 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 PlatformAdminCheck, 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 RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, 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, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineMigration, defineModule, 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, onWhisper, platformAdmin, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, tagPerDispatchMiddleware, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
|
3942
|
+
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 ModuleConfig, type ModuleDefinition, 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 PlatformAdminCheck, 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 RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, 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, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineMigration, defineModule, 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, onWhisper, platformAdmin, 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 i,actionCacheExtension as n,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 i,actionCacheExtension as n,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BFmhdKJG.mjs";import{initLunora as d}from"./packem_shared/initLunora-B-7Xs3Qq.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as h,withDeferredDeletes as S}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CmmdpWRS.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as I,documentHistoryExtension as L}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BeS7G0yM.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-BHq_oUP2.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-CsKNC6op.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-SPHQyLa4.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as Y}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as J,onDisconnect as K,onShardInit as Q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as q,DEFAULT_MAX_LIMIT as z,clampLimit as Z,defineListArgs as $}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineMigration as re}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as te}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as ne}from"./packem_shared/defineMutator-B4ipDtDR.mjs";import{platformAdmin as fe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as de,d as me,a as pe,b as xe,e as ce,f as le,g as Ee,h as ue,i as he,j as Se,k as De,m as Te}from"./packem_shared/plugin-Bm9wIpiI.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ae,PRESENCE_TABLE as Re,definePresence as _e,presenceExtension as Ie}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs";import{protectPublic as Ce}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Pe}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{createServices as ye}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Oe}from"./packem_shared/defineShape-CX9Xs8AY.mjs";import{onWhisper as Ne}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ue}from"@lunora/errors";import{cronJobs as ve}from"@lunora/scheduler";import{ValidationError as Ve,v as We}from"@lunora/values";import{allowAll as Ye,deny as Ge,isDeny as Je,toWhereInput as Ke}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Xe}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as ze,buildRlsReadRegistry as Ze,composeShapeReadWhere as $e}from"./packem_shared/assertShapesDeclareReadPolicies-isd_Yupt.mjs";import{buildMaskRegistry as rr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as tr,definePermission as ir,definePolicies as nr,definePolicy as ar,defineRole as fr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as dr,defineStorageRules as mr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as xr}from"./packem_shared/mask-BdULkLAu.mjs";import{r as lr}from"./packem_shared/middleware-DbhB1jRk.mjs";import{storageRules as ur}from"./packem_shared/storageRules-CMfQu8yY.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,q as DEFAULT_LIMIT,z as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Ue as LunoraError,Ae as PRESENCE_DEFAULT_TTL_MS,Re as PRESENCE_TABLE,e as VERSION,Ve as ValidationError,n as actionCacheExtension,Ye as allowAll,Xe as asBucketStorage,ze as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,rr as buildMaskRegistry,Ze as buildRlsReadRegistry,a as cacheKeyFor,Z as clampLimit,de as composePluginMiddleware,$e as composeShapeReadWhere,tr as createPolicyDsl,l as createSecrets,ye as createServices,ve as cronJobs,f as defineActionCache,me as defineAggregateIndex,pe as defineComponent,I as defineDocumentHistory,P as defineEnv,W as defineIdentity,Y as defineIdentityGuard,$ as defineListArgs,re as defineMigration,te as defineModule,ne as defineMutator,ir as definePermission,xe as definePlugin,nr as definePolicies,ar as definePolicy,_e as definePresence,ce as defineRankIndex,fr as defineRole,le as defineSchema,Ee as defineSchemaExtension,Oe as defineShape,dr as defineStorageRule,mr as defineStorageRules,ue as defineTable,he as defineVectorIndex,Ge as deny,L as documentHistoryExtension,h as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,Se as indexFieldsFromSchema,d as initLunora,De as installPlugins,Je as isDeny,p as isPerDispatchMiddleware,k as isSafeHeaderValue,xr as mask,Te as mergeSchemaExtension,J as onConnect,K as onDisconnect,Pe as onQueryChange,Q as onShardInit,Ne as onWhisper,fe as platformAdmin,Ie as presenceExtension,Ce as protectPublic,b as redactSecrets,lr as rls,B as serveStorageObject,ur as storageRules,x as tagPerDispatchMiddleware,Ke as toWhereInput,We as v,S as withDeferredDeletes,g as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-CZ4obM6q.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-B-7Xs3Qq.mjs";import{g as k,h as q,a as B}from"./plugin-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-CZ4obM6q.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-B-7Xs3Qq.mjs";import{g as k,h as q,a as B}from"./plugin-Bm9wIpiI.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,e as h}from"./wire-codec-CZ4obM6q.mjs";import{initLunora as x}from"./initLunora-B-7Xs3Qq.mjs";import{g as v,h as R,a as U}from"./plugin-
|
|
1
|
+
import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-CZ4obM6q.mjs";import{initLunora as x}from"./initLunora-B-7Xs3Qq.mjs";import{g as v,h as R,a as U}from"./plugin-Bm9wIpiI.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-B-7Xs3Qq.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-B-7Xs3Qq.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-Bm9wIpiI.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,e as g,f as b,g as y}from"./middleware-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-DbhB1jRk.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{LunoraError as p}from"@lunora/errors";import{i as M}from"./wire-codec-CZ4obM6q.mjs";const b=new Set(["connect","disconnect","set"]),y=500,I=(t,n,s)=>t!==void 0&&Object.hasOwn(t,n)&&M(s),v=t=>typeof t=="object"&&t!==null&&t.code==="CONFLICT"&&t.kind==="unique",u=(t,n)=>{throw new p(t,n)},O=(t,n)=>{if(!Array.isArray(t)||t.some(e=>typeof e!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const s=[...new Set(t)];return s.length>y&&u("VALIDATION_ERROR",`${n} names ${String(s.length)} rows; at most ${String(y)} per list`),s},E=(t,n,s)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${s}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),e!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),e!==void 0?(typeof e!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:e,info:n,name:t}):(i!==!0&&u("VALIDATION_ERROR",`${t}.disconnect must be true`),E(t,n,"disconnect"),{info:n,name:t})},A=(t,n,s)=>{n.through===void 0&&E(t,n,s)},k=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;if(c!==void 0)return(e!==void 0||i!==void 0)&&u("VALIDATION_ERROR",`${t}: set replaces the whole list and cannot be combined with connect or disconnect`),A(t,n,"set"),{attach:[],info:n,name:t,release:[],replace:O(c,`${t}.set`)};i!==void 0&&A(t,n,"disconnect");const a=e===void 0?[]:O(e,`${t}.connect`),r=i===void 0?[]:O(i,`${t}.disconnect`),o=a.find(d=>r.includes(d));return o!==void 0&&u("VALIDATION_ERROR",`${t}: "${o}" is in both connect and disconnect, which is ambiguous`),{attach:a,info:n,name:t,release:r}},j=(t,n,s,e)=>{const i=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0)),c=Object.keys(i).find(r=>!b.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}: "${n}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(i).length===0)return;const a=s.refusal??s.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),s.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${s.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),s.kind==="one"?D(n,s,i):k(n,s,i)},W=t=>t.info.kind==="one",T=(t,n,s)=>{if(n===void 0)return{columns:s,manys:[],ones:[]};const e={},i=[],c=[];for(const[a,r]of Object.entries(s)){if(!I(n,a,r)){e[a]=r;continue}const o=j(t,a,n[a],r);o!==void 0&&(W(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(e,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:e,manys:i,ones:c}},$=(t,n,s,e)=>{const i=Object.entries(s).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${e}: "${i}" is a relation write, which ${e} does not support; use insert or patch`)},R=async(t,n,s,e,i)=>{const c=await t.get(i,e);return c===null&&u("NOT_FOUND",`${n}.${s}: no "${e}" row with id "${i}"`),c},_=async(t,n)=>{const s={...n.columns};for(const{connect:e,info:i,name:c}of n.ones){let a=null;e!==void 0&&(a=(await R(t,c,"connect",i.table,e))[i.references]),s[i.field]=a}return s},F=async(t,{info:n,name:s},e,i)=>{(await R(t,s,"connect",n.table,e))[n.field]!==i&&await t.patch(e,{[n.field]:i},n.table)},U=async(t,{info:n},s,e)=>{s[n.field]===e&&await t.patch(String(s._id),{[n.field]:null},n.table)},V=async(t,{info:n,name:s},e)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:e}});return i.length>y&&u("VALIDATION_ERROR",`${s}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const s=new Set(t),e=new Set(n);return{attach:n.filter(i=>!s.has(i)),release:new Set(t.filter(i=>!e.has(i)))}},w=async(t,{name:n},{from:s,table:e,to:i},c,a)=>{const r=a===void 0?{[s]:c}:{[s]:c,[i]:{in:a}},{page:o}=await t.findMany(e,{limit:y+1,where:r});return o.length>y&&u("VALIDATION_ERROR",`${n}: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},C=async(t,n,s)=>{if(s.length===0)return new Set;const{page:e}=await t.findMany(n,{limit:s.length,where:{_id:{in:s}}});return new Set(e.map(i=>String(i._id)))},P=async(t,n,s)=>{const{info:e,name:i}=n,{from:c,table:a,to:r}=e.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(l=>R(t,i,"disconnect",e.table,l))),d=n.release.length===0?[]:await w(t,n,e.through,s,n.release);const h=n.attach.length===0?[]:await w(t,n,e.through,s,n.attach),f=new Set(h.map(l=>String(l[r])));o=n.attach.filter(l=>!f.has(l))}else{const h=await w(t,n,e.through,s,void 0),f=L(h.map(g=>String(g[r])),n.replace),l=await C(t,e.table,[...f.release]);({attach:o}=f),d=h.filter(g=>f.release.has(String(g[r]))&&l.has(String(g[r])))}await Promise.all(o.map(h=>R(t,i,"connect",e.table,h)));for(const h of d)await t.delete(String(h._id),a);for(const h of o)try{await t.insert(a,{[c]:s,[r]:h})}catch(f){if(!v(f)||!e.pairIsOnlyUnique)throw f}},q=async(t,n,s)=>{let{attach:e}=n,i;if(n.replace===void 0)i=await Promise.all(n.release.map(c=>R(t,n.name,"disconnect",n.info.table,c)));else{const c=await V(t,n,s),a=L(c.map(r=>String(r._id)),n.replace);({attach:e}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await U(t,n,c,s);for(const c of e)await F(t,n,c,s)},S=async(t,n,s,e)=>{for(const i of s.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await e(a);if(r==null&&u("VALIDATION_ERROR",`ctx.db.${n}: ${i.name} is keyed on "${a}", which this row has no value for`),c.through!==void 0){await P(t,{...i,info:c},r);continue}await q(t,{...i,info:c},r)}},x=(t,n,s,e)=>async i=>i==="_id"?s:Object.hasOwn(e,i)?e[i]:(await t.get(s,n))?.[i],B=async(t,n,s,e,i)=>{const c=T(n,s,e);if(c.ones.length===0&&c.manys.length===0)return i(c.columns);const a=await _(t,c),r=await i(a);return r!==null&&await S(t,n,c,x(t,n,r,a)),r},m=async(t,n,s,e,i)=>{const c=T(n,s,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(e,c.columns,n);return}const a=await _(t,c);if(Object.keys(a).length>0)await t.patch(e,a,n);else{if(await t.get(e,n)===null)throw new p("NOT_FOUND",`document not found: ${e}`);await t.assertPatchAllowed?.(e,n)}await S(t,n,c,x(t,n,e,a))},G=(t,n,s,e)=>{const i=typeof n=="string"?[n]:n;if(i.length===0)throw new p("INTERNAL",`ctx.db.${t}.upsert: "target" must name at least one field`);const c={};for(const a of i){if(!(a in s)){const r=Object.entries(e??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in s)?.[0];throw r!==void 0?new p("VALIDATION_ERROR",`ctx.db.${t}.upsert: target field "${a}" is supplied by the "${r}" relation write; pass "${a}" itself so the existing row can be found`):new p("INTERNAL",`ctx.db.${t}.upsert: target field "${a}" is missing from the create document`)}c[a]=s[a]}return c},X=(t,n)=>{const s=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(h){if(v(h))return null;throw h}},e=t.relationWrites?.[n],i=(o,d)=>B(t,n,e,o,h=>s(h,d)),c=(o,d)=>m(t,n,e,o,d),a=async o=>{const d=o??{},h=await t.findMany(n,{...d,limit:2});if(h.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return h.page[0]??null},r=async({create:o,target:d,update:h})=>{const f=G(n,d,o,e),l=await t.findFirst(n,{where:f});return l&&typeof l._id=="string"?(await c(l._id,h??o),{created:!1,id:l._id}):{created:!0,id:await i(o)}};return{aggregate:o=>t.aggregate(n,o),count:o=>t.count(n,o),delete:o=>t.delete(o,n),deleteMany:(o,d)=>{if(Array.isArray(o)){if(t.deleteMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany is unavailable: this writer has no batch delete`);return t.deleteMany(o,d,n)}if(t.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const h=o;return t.deleteWhere(n,h.where,{limit:h.limit})},exists:async o=>await t.findFirst(n,o===void 0?void 0:{where:o})!==null,explain:o=>t.explain(n,o),findFirst:o=>t.findFirst(n,o),findFirstOrThrow:o=>t.findFirstOrThrow(n,o),findMany:o=>t.findMany(n,o),findUnique:a,get:o=>t.get(o,n),groupBy:o=>t.groupBy(n,o),hardDelete:o=>t.delete(o,n,{hard:!0}),insert:i,insertMany:(o,d)=>{for(const h of o)$(n,e,h,"insertMany");if(t.insertMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.insertMany is unavailable: this writer has no batch insert`);return t.insertMany(n,o,d)},patch:c,patchMany:(o,d)=>{const h=Array.isArray(o)?o.map(l=>l.values):[o.values];for(const l of h)$(n,e,l,"patchMany");if(Array.isArray(o)){if(t.patchMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany is unavailable: this writer has no batch patch`);return t.patchMany(o.map(l=>({id:l.id,patch:l.values})),d,n)}if(t.patchWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=o;return t.patchWhere(n,{patch:f.values,where:f.where},{limit:f.limit})},rank:(o,d)=>t.rank(n,o,d),rankPage:(o,d)=>t.rankPage(n,o,d),replace:(o,d)=>($(n,e,d,"replace"),t.replace(o,d,n)),restore:async o=>{if(!t.restore)throw new p("INTERNAL",`ctx.db.${n}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await t.restore(o,n)},upsert:r,upsertMany:async({rows:o,target:d})=>{const h=[];for(const f of o)h.push(await r({create:f.create,target:d,update:f.update}));return h},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},z=t=>{const n=s=>{const e=t[s];if(!e)throw new p("INTERNAL",`unknown table: ${s}`);return e};return{delete:(s,e)=>n(s).delete(e),insert:s=>({values:e=>n(s).insert(e)}),query:t,replace:(s,e)=>({with:i=>n(s).replace(e,i)}),update:(s,e)=>({set:i=>n(s).patch(e,i)})}};export{z as bindOrm,X as bindTableFacade};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./compose-middleware-BK9FlblN.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-
|
|
1
|
+
import"./compose-middleware-BK9FlblN.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-Bm9wIpiI.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-DR1_vB45.mjs → defineAggregateIndex-DF8NiKHr.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d,e as s,f as i,h as n,i as l,j as f,v as o,l as t,n as r}from"./plugin-
|
|
1
|
+
import{d,e as s,f as i,h as n,i as l,j as f,v as o,l as t,n as r}from"./plugin-Bm9wIpiI.mjs";export{d as defineAggregateIndex,s as defineRankIndex,i as defineSchema,n as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,t as validateIndexFields,r as validateTableModes};
|
|
@@ -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-isd_Yupt.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as G,a as C,o as K,b as H,c as J,d as m}from"./middleware-DbhB1jRk.mjs";import{bindTableFacade as Q,bindOrm as V}from"./bindOrm-BHq_oUP2.mjs";import{tagMaskMiddleware as X}from"./buildMaskRegistry-DpWMtalG.mjs";const Y=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},f=(s,i,c)=>{const w={...s};for(const[y,g]of Object.entries(i))y in w&&(w[y]=Y(g,s[y],{...c,column:y,row:s}));return w},F=(s,i,c)=>({...s,page:s.page.map(w=>f(w,i,c))}),I=(s,i)=>{const c=J(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},L=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>u=>(typeof u=="string"&&y.add(u),g())});s(g());for(const u of y)if(I(i,u))throw new A("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${u}" is not supported`)},Z=(s,i,c,w)=>{const y=s.rankBefore,g=s.rankPageRows,u=(r,t)=>{const n=i.get(r);return n?t.map(o=>f(o,n,c)):t},l=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?u:(n,o)=>t(n,u(n,o))}},p=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[t];if(!a)return;const d=a.find(R=>I(e,R));if(d!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${d}" — use an index whose declared fields are all unmasked, or unmask the column`)},k=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield f(o,t,c)},collect:async()=>(await r.collect()).map(e=>f(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=f(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>k(r.filter(e=>o(f(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?f(o,t,c):null},order:o=>k(r.order(o),t,n),paginate:async o=>F(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>f(a,t,c)),unique:async()=>{const o=await r.unique();return o?f(o,t,c):null},withIndex:(o,e)=>(p(n,o,"withIndex","index"),L(e,t,n,"withIndex"),k(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(L(e,t,n,"withSearchIndex"),k(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(p(n,o,"withGeoIndex","geo"),k(r.withGeoIndex(o,e),t,n))}),W=async(r,t)=>{if(s.lookupById){const d=await s.lookupById(r,t);if(d)return{row:d.row,tableName:i.has(d.tableName)?d.tableName:void 0}}const n=await s.get(r,t);if(!n)return{row:null,tableName:void 0};const o=t!==void 0&&i.has(t)?[t]:[],e=t===void 0?[...i.keys()]:o,a=await Promise.all(e.map(async d=>(await s.findFirst(d,{limit:1,where:{_id:r}}))?._id===r?d:void 0));return{row:n,tableName:a.find(d=>d!==void 0)}},S=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&I(o,a));if(e!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},O=new Set;for(const r of i.values())for(const t of Object.keys(r))O.add(t);const P=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,a]of Object.entries(r))q(e,a,t,n,o)},q=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const a of Array.isArray(t)?t:[])P(a,n,o,e);return}if(r==="NOT"){P(t,n,o,e);return}if(!r.startsWith("__")){if(I(n,r))throw new A("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(m(t))for(const a of Object.values(t))P(a,O,`${o}.${r}`,e)}},E=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{O.size===0||t===void 0||P(t,E(r),r,n)},U=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(I(n,a))throw new A("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},v=(r,t,n)=>{if(!(O.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,d=`${r}.${o}`;P(a.where,O,d,n),U(d,a.orderBy,O,n),v(d,a.with,n)}},$=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),U(r,t?.orderBy,E(r),n),v(r,t?.with,n)},_=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,t,n)=>{const o=_(t);h(r,o?.where,n),h(r,o?.baseWhere,n),v(r,o?.with,n)},j=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,B={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[a,d]=e.kind==="one"?[t,e.table]:[e.table,t],R=e.through?j(e.through.table,e.through.from)??j(e.through.table,e.through.to):j(a,e.field)??j(d,e.references);return[o,R===void 0?e:{...e,refusal:`"${R}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new A("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:f(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return S(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=_(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){$(r,t,"findFirst");const n=await s.findFirst(r,l(t)),o=i.get(r);return n&&o?f(n,o,c):n},async findFirstOrThrow(r,t){$(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,l(t)),o=i.get(r);return o?f(n,o,c):n},async explain(r,t){return $(r,t,"explain"),s.explain(r,t)},async findMany(r,t){$(r,t,"findMany");const n=await s.findMany(r,l(t)),o=i.get(r);return o?F(n,o,c):n},async get(r,t){const{row:n,tableName:o}=await W(r,t),e=o===void 0?void 0:i.get(o);return!n||!e?n:f(n,e,c)},related:s.related?async(r,t)=>await s.related(r,l(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?f(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return S(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?k(t,n,r):t},async rank(r,t,n){return M(r,n,"rank"),p(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){M(r,n,"rankPage"),p(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?F(o,e,c):o},...K("rankBefore",y,r=>(t,n,o)=>(M(t,o,"rankBefore"),p(t,n,"rankBefore","rank"),r(t,n,o))),...K("rankPageRows",g,r=>async(t,n,o)=>{M(t,o,"rankPageRows"),p(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(d=>({...d,doc:f(d.doc,a,c)}))}:e})},z=B;if(O.size>0)for(const[r,t]of Object.entries(s))H(t)&&(z[r]=Q(B,r));return B},nr=(s,i={})=>{const c=new Map(Object.entries(s)),w=G(i.roles),y=async({ctx:u,next:l})=>{const p={auth:await C(u.auth??{},w),ctx:u};if(i.bypass?.(p)===!0)return l();const k=Z(u.db,c,p,i.indexFields),W={db:k},{orm:S}=u;return S!==null&&typeof S=="object"&&(W.orm=V(k)),l({ctx:W})},g=new Map;for(const[u,l]of c)g.set(u,new Set(Object.keys(l)));return X(y,{columns:g})};export{nr as mask};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as b,isLunoraError as le}from"@lunora/errors";import{findRelated as fe,whereFilter as de}from"@lunora/shard-engine";import{i as M}from"./wire-codec-CZ4obM6q.mjs";import{bindTableFacade as he,bindOrm as ue}from"./bindOrm-BaAMwCFL.mjs";import{t as ye}from"./policy-tag-V0lqFzgS.mjs";import{deny as pe}from"./allowAll-DkRAgItV.mjs";const K=4;class T extends Error{}const C=e=>e.includes("."),at=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},J=e=>{const t=e.split(".");if(t.length>K||t.includes(""))throw new T(`field path "${e}" must have 1 to ${String(K)} non-empty segments`);return t},we=(e,t)=>{if(!C(t))return e[t];let r=e;for(const s of J(t)){if(!M(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},Z=(e,t,r,s)=>{const[a,...l]=t;if(a===void 0)throw new T(`field path "${s}" is empty`);if(e!=null&&!M(e))throw new T(`cannot set "${s}": "${a}" sits inside a value that is not an object`);const f=e??{};return{...f,[a]:l.length===0?r:Z(f[a],l,r,s)}},ge=(e,t)=>{const r=Object.keys(e).filter(a=>C(a));if(r.length===0)return e;for(const a of r){const l=r.find(f=>f!==a&&f.startsWith(`${a}.`));if(l!==void 0)throw new T(`patch sets both "${a}" and "${l}", which overlap; set one or the other`)}const s={};for(const[a,l]of Object.entries(e))C(a)||(s[a]=l);for(const a of r){const[l="",...f]=J(a);if(Object.hasOwn(e,l))throw new T(`patch sets both "${l}" and "${a}"; set one or the other`);s[l]=Z(Object.hasOwn(s,l)?s[l]:t[l],f,e[a],a)}return s},be=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},ve=["every","is","isNot","none","some"],Oe=new Set(ve),We=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Oe.has(r))},Q=(e,t,r)=>t?{[e]:r(t)}:{},x={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const V=e=>{if(!M(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(x,r)))return{operand:e[r],operator:r}},Re=e=>V(e)!==void 0,Ee=(e,t,r,s)=>{const a=x[t];if(a.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const l=a.apply(s,r);if(!Number.isFinite(l))throw new R(`patch: "${t}" on "${e}" overflows to ${String(l)}.`);return l},ee=(e,t)=>{const r=new Set;for(const[s,a]of Object.entries(e))t(s)!==void 0&&Re(a)&&r.add(s);return r},Ae=(e,t,r)=>{let s;for(const a of ee(e,r)){const{operand:l,operator:f}=V(e[a]),v=r(a);if(x[f].kind!==v)throw new R(`patch: "${f}" does not apply to the ${String(v)} column "${a}".`);s??={...e},s[a]=Ee(a,f,l,t[a])}return s??e},ke=(e,t)=>{const r=a=>{const l=t[a];return typeof l=="number"||typeof l=="boolean"?typeof l:void 0},s={...e};for(const a of ee(e,r))try{Object.assign(s,Ae({[a]:e[a]},t,r))}catch(l){if(!(l instanceof R))throw l}try{return ge(s,t)}catch(a){if(a instanceof T)return s;throw a}},Se=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,P=0,E=1,$=e=>e?E:B,w=(e,t)=>e<t?e:t,me=(e,t)=>e>t?e:t,te=e=>e===P?P:$(e===B),z=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},_=e=>e==null,D=(e,t,r)=>{if(r===void 0)throw new b("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Be={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},Pe=(e,t,r)=>{let s=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const l=r[a];D(e,a,l);const f=C(e);if(f?be(l)===void 0:!z(l))s=w(s,B);else if(_(t))s=w(s,P);else{const v=Be[a],p=f?typeof t==typeof l:z(t);s=w(s,$(p&&v(t,l)))}}return s},X=(e,t,r)=>{if(!Array.isArray(r))throw new b("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new b("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},G=(e,t)=>t.length===0?B:_(e)?P:t.includes(e)?E:t.some(r=>_(r))?P:B,_e=(e,t,r)=>{let s=E;if("in"in r&&(s=w(s,G(t,X(e,"in",r.in)))),"notIn"in r&&(s=w(s,te(G(t,X(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;D(e,"contains",a),s=_(t)?w(s,P):w(s,$(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(s=w(s,$(r.isNull===!0===_(t)))),s},q=(e,t,r)=>t===null?$(r===_(e)):_(e)?P:$(r===(e===t)),Ie=(e,t,r)=>{let s=E;return"eq"in r&&(D(e,"eq",r.eq),s=w(s,q(t,r.eq,!0))),"ne"in r&&(D(e,"ne",r.ne),s=w(s,q(t,r.ne,!1))),s},Te=(e,t,r)=>w(Ie(e,t,r),w(_e(e,t,r),Pe(e,t,r))),$e=(e,t,r,s)=>{if(t==="NOT")return te(s(e,r??{}));if(!Array.isArray(r))return B;let a=t==="AND"?E:B;for(const l of r){const f=s(e,l);a=t==="AND"?w(a,f):me(a,f)}return a},ne=e=>e==="AND"||e==="OR"||e==="NOT",Me=e=>M(e)&&Object.keys(e).every(t=>Se.includes(t)),U=e=>Object.keys(e).some(t=>{const r=e[t];return ne(t)?t==="NOT"?U(r??{}):Array.isArray(r)&&r.some(s=>U(s??{})):We(r)}),re=(e,t)=>{let r=E;for(const s of Object.keys(t)){const a=t[s];if(ne(s)){r=w(r,$e(e,s,a,re));continue}const l=we(e,s);if(Me(a)){r=w(r,Te(s,l,a));continue}D(s,"eq",a),r=w(r,q(l,a,!0))}return r},j=(e,t)=>re(e,t)===E,oe=500,I=(e,t,r)=>{const s=t??oe;if(e>s)throw new b("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(e)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},De=pe(),Fe=Symbol.for("lunora.ctxdb.rls-unwrap"),se=Symbol.for("lunora.rls.wrapped-chain"),Le=e=>e[se],Ce=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Ue=(e,t)=>{const r=[];let s=!1;for(const a of e){if(a.on!=="read")continue;const l=a.when(t);if(l!==void 0){if(l===!0){s=!0;break}l!==!1&&r.push(l)}}if(!s)return r.length===0?De:r.length===1?r[0]:{OR:r}},je=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(U(s))throw new b("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return j(r,s)},Ne=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||je(e,t,r);if(s===!1)return!1;if(U(s))throw new b("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!j(t.row,s)?!1:r===void 0||j(r,s)},qe=(e,t,r,s)=>{let a=!1;for(const l of e)if(l.on===t&&(a=!0,!Ne(l,r,s)))return!1;return a},Ye=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),xe=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":M(t),He=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ye.has(r)&&xe(r,e[r]))},Ke=e=>e===void 0?{}:M(e)&&He(e)?e:{where:e},Y=e=>e!==void 0&&Object.keys(e).length>0,Qe=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>Y(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ze=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},Xe=(e,t,r)=>{const[s]=r,a=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),l=new Map,f=n=>{const o=l.get(n);if(o)return o;const i=[];let c=!1;for(const h of r){const u=h.perTable.get(n);if(!u||u.length===0||!u.some(L=>L.on==="read"))continue;c=!0;const y=Ue(u,h.context);y!==void 0&&i.push(y)}const d={baseWhere:Qe(i),restricts:c};return l.set(n,d),d},v=(n,o,i,c)=>{for(const d of r){const h=d.perTable.get(n);if(h&&!qe(h,o,{...d.context,row:i},c))return!1}return!0},p=n=>f(n).restricts?t:e,g=n=>f(n).baseWhere,A=async(n,o,i)=>{if(t.lookupById){const y=await t.lookupById(n,o);if(y)return{row:y.row,tableName:a.has(y.tableName)?y.tableName:void 0}}const c=await t.get(n,o);if(!c)return{row:null,tableName:void 0};const d=o??i,h=d===void 0?[...a.keys()]:[d].filter(y=>a.has(y)),u=await Promise.all(h.map(async y=>(await t.findFirst(y,{limit:1,where:{_id:n}}))?._id===n?y:void 0));return{row:c,tableName:u.find(y=>y!==void 0)}},N=async(n,o,i)=>{const c=await A(n,o,i);return c.row&&c.tableName!==void 0?{row:c.row,tableName:c.tableName}:void 0},O=async(n,o,i,c,d,h)=>{const u=await N(n,d,h);if(!u)return i(e);const y=c?c(u.row):void 0;if(!v(u.tableName,o,u.row,y))throw new b("FORBIDDEN",`${o} denied by policy`);return i(t,u.tableName)},k=(n,o,i,c)=>O(n,"update",(d,h)=>i(d,{verify:h===void 0?void 0:(u,y)=>v(h,"update",u,y)}),d=>({...d,...ke(o,d)}),c),S=(n,o)=>{const{baseWhere:i}=f(n);if(Y(i))throw new b("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},F=e.rankBefore,ae=e.rankPageRows,{relationEdges:H}=e,m={...e,async count(n,o){const{baseWhere:i}=f(n),c=Ke(o);return p(n).count(n,{...c,baseWhere:W(c.baseWhere,i),relationBaseWhere:g,restrictsCounts:(c.restrictsCounts??!1)||Y(i)})},delete:(n,o,i)=>O(n,"delete",c=>c.delete(n,o,i),void 0,o),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??oe),{baseWhere:c}=f(n);let d=0;for(;;){const u=(await p(n).findMany(n,{baseWhere:c,limit:i,relationBaseWhere:g})).page.map(y=>String(y._id));if(u.length===0)break;for(const y of u)await O(y,"delete",L=>L.delete(y,void 0,o?.hard===void 0?void 0:{hard:o.hard}),void 0,void 0,n),d+=1;if(u.length<i)break}return{deleted:d}},async deleteMany(n,o,i){I(n.length,o?.limit,"deleteMany");for(const c of n)await O(c,"delete",d=>d.delete(c,i),void 0,i);return{deleted:n.length}},async deleteWhere(n,o,i){const{baseWhere:c}=f(n),h=(await p(n).findMany(n,{baseWhere:W(o,c),relationBaseWhere:g})).page.map(u=>String(u._id));I(h.length,i?.limit,"deleteWhere");for(const u of h)await O(u,"delete",y=>y.delete(u),void 0,void 0,n);return{deleted:h.length}},async findFirst(n,o){const{baseWhere:i}=f(n);return p(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async findFirstOrThrow(n,o){const{baseWhere:i}=f(n);return p(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async explain(n,o){const{baseWhere:i}=f(n);return p(n).explain(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async findMany(n,o){const{baseWhere:i}=f(n);return p(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async get(n,o){const i=await A(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:d}=f(i.tableName);if(!d)return e.get(n,o);if(!c)return i.row;const h=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return h?._id===n?h:null},async lookupById(n,o){const i=await A(n,o);if(!i.row)return null;if(i.tableName===void 0||!f(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=f(i.tableName);if(!c)return{row:i.row,tableName:i.tableName};const d=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:i.tableName}:null},async insert(n,o,i){if(a.has(n)){if(!v(n,"insert",o))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(I(o.length,i?.limit,"insertMany"),a.has(n)){for(const c of o)if(!v(n,"insert",c))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(I(o.length,i?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!v(n,"insert",c))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i)=>k(n,o,(c,d)=>c.patch(n,o,i,d),i),assertPatchAllowed:(n,o)=>k(n,{},()=>Promise.resolve(),o),async patchIf(n,o,i){const c=await k(o,i.patch,async(h,u)=>{if(h.patchIf===void 0)throw new b("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return h.patchIf(n,o,{...i,verify:u.verify})},n);return c.doc===null||await m.get(o,n).then(h=>h!==null,h=>{if(le(h)&&h.code==="RLS_REQUIRED")return!1;throw h})?c:{applied:c.applied,doc:null}},async patchMany(n,o,i){I(n.length,o?.limit,"patchMany");for(const c of n)await k(c.id,c.patch,(d,h)=>d.patch(c.id,c.patch,i,h),i);return{patched:n.length}},async patchWhere(n,o,i){const{baseWhere:c}=f(n),h=(await p(n).findMany(n,{baseWhere:W(o.where,c),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:o.patch}));return I(h.length,i?.limit,"patchWhere"),m.patchMany(h,i)},query(n){const{baseWhere:o}=f(n),i=p(n).query(n);return o?i.filter(de(o,c=>j(c,o))):i},related:H===void 0?void 0:async(n,o)=>fe({findMany:async(i,c)=>m.findMany(i,c),lookupById:async i=>t.lookupById?.(i)},H,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>O(n,"update",async i=>{const c=i.restore??t.restore;if(!c)throw new b("BAD_REQUEST","restore is not supported by this writer");await c(n,o)},void 0,o),replace:(n,o,i)=>O(n,"update",c=>c.replace(n,o,i),c=>({...o,_creationTime:o._creationTime??c._creationTime,_id:c._id}),i),aggregate(n,o){const{baseWhere:i}=f(n);return p(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,i),relationBaseWhere:g})},groupBy(n,o){const{baseWhere:i}=f(n);return p(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,i),relationBaseWhere:g})},rank(n,o,i){return S(n,"rank"),p(n).rank(n,o,i)},rankPage(n,o,i){return S(n,"rankPage"),p(n).rankPage(n,o,i)},wipeShard(){throw new b("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",F,n=>(o,i,c)=>(S(o,"rankBefore"),(p(o).rankBefore??n)(o,i,c))),...Q("rankPageRows",ae,n=>(o,i,c)=>(S(o,"rankPageRows"),(p(o).rankPageRows??n)(o,i,c)))},ce=m;if(a.size>0)for(const[n,o]of Object.entries(e))ze(o)&&(ce[n]=he(m,n));return Object.defineProperty(m,se,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),m},ie=e=>typeof e=="string"?e:e.name,Ge=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>ie(s))));return t},Je=(e,t)=>{const r=new Set;for(const s of e)for(const a of t.get(s)??[])r.add(a);return s=>r.has(ie(s))},Ze=["roles","role"],Ve=e=>{for(const t of Ze){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(a=>typeof a=="string"&&a.length>0);if(s.length>0)return s}}return[]},et=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...Ve(r),...e.roles??[]])];return{can:Je(s,t),identity:r,roles:s,userId:e.userId??null}},ct=(e,t={})=>{const r=e,s=Ce(r),a=Ge(t.roles);return ye(async({ctx:f,next:v})=>{const p={auth:await et(f.auth??{},a),ctx:f},g=f.db,A=Le(g),N=A?.base??g,O=A?.raw??g[Fe]??g,k=Xe(N,O,[...A?.steps??[],{context:p,perTable:s}]),S={db:k},{orm:F}=f;return F!==null&&typeof F=="object"&&(S.orm=ue(k)),v({ctx:S})},[{policies:r,roles:t.roles??[]}])};export{et as a,ze as b,at as c,We as d,Ve as e,Ue as f,Je as g,qe as h,Ge as i,j as m,Q as o,ct as r};
|
|
1
|
+
import{LunoraError as b,isLunoraError as le}from"@lunora/errors";import{findRelated as fe,whereFilter as de}from"@lunora/shard-engine";import{i as M}from"./wire-codec-CZ4obM6q.mjs";import{bindTableFacade as he,bindOrm as ue}from"./bindOrm-BHq_oUP2.mjs";import{t as ye}from"./policy-tag-V0lqFzgS.mjs";import{deny as pe}from"./allowAll-DkRAgItV.mjs";const K=4;class T extends Error{}const C=e=>e.includes("."),at=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},J=e=>{const t=e.split(".");if(t.length>K||t.includes(""))throw new T(`field path "${e}" must have 1 to ${String(K)} non-empty segments`);return t},we=(e,t)=>{if(!C(t))return e[t];let r=e;for(const s of J(t)){if(!M(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},Z=(e,t,r,s)=>{const[a,...l]=t;if(a===void 0)throw new T(`field path "${s}" is empty`);if(e!=null&&!M(e))throw new T(`cannot set "${s}": "${a}" sits inside a value that is not an object`);const f=e??{};return{...f,[a]:l.length===0?r:Z(f[a],l,r,s)}},ge=(e,t)=>{const r=Object.keys(e).filter(a=>C(a));if(r.length===0)return e;for(const a of r){const l=r.find(f=>f!==a&&f.startsWith(`${a}.`));if(l!==void 0)throw new T(`patch sets both "${a}" and "${l}", which overlap; set one or the other`)}const s={};for(const[a,l]of Object.entries(e))C(a)||(s[a]=l);for(const a of r){const[l="",...f]=J(a);if(Object.hasOwn(e,l))throw new T(`patch sets both "${l}" and "${a}"; set one or the other`);s[l]=Z(Object.hasOwn(s,l)?s[l]:t[l],f,e[a],a)}return s},be=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},ve=["every","is","isNot","none","some"],Oe=new Set(ve),We=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Oe.has(r))},Q=(e,t,r)=>t?{[e]:r(t)}:{},x={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const V=e=>{if(!M(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(x,r)))return{operand:e[r],operator:r}},Re=e=>V(e)!==void 0,Ee=(e,t,r,s)=>{const a=x[t];if(a.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const l=a.apply(s,r);if(!Number.isFinite(l))throw new R(`patch: "${t}" on "${e}" overflows to ${String(l)}.`);return l},ee=(e,t)=>{const r=new Set;for(const[s,a]of Object.entries(e))t(s)!==void 0&&Re(a)&&r.add(s);return r},Ae=(e,t,r)=>{let s;for(const a of ee(e,r)){const{operand:l,operator:f}=V(e[a]),v=r(a);if(x[f].kind!==v)throw new R(`patch: "${f}" does not apply to the ${String(v)} column "${a}".`);s??={...e},s[a]=Ee(a,f,l,t[a])}return s??e},ke=(e,t)=>{const r=a=>{const l=t[a];return typeof l=="number"||typeof l=="boolean"?typeof l:void 0},s={...e};for(const a of ee(e,r))try{Object.assign(s,Ae({[a]:e[a]},t,r))}catch(l){if(!(l instanceof R))throw l}try{return ge(s,t)}catch(a){if(a instanceof T)return s;throw a}},Se=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,P=0,E=1,$=e=>e?E:B,w=(e,t)=>e<t?e:t,me=(e,t)=>e>t?e:t,te=e=>e===P?P:$(e===B),z=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},_=e=>e==null,D=(e,t,r)=>{if(r===void 0)throw new b("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Be={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},Pe=(e,t,r)=>{let s=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const l=r[a];D(e,a,l);const f=C(e);if(f?be(l)===void 0:!z(l))s=w(s,B);else if(_(t))s=w(s,P);else{const v=Be[a],p=f?typeof t==typeof l:z(t);s=w(s,$(p&&v(t,l)))}}return s},X=(e,t,r)=>{if(!Array.isArray(r))throw new b("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new b("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},G=(e,t)=>t.length===0?B:_(e)?P:t.includes(e)?E:t.some(r=>_(r))?P:B,_e=(e,t,r)=>{let s=E;if("in"in r&&(s=w(s,G(t,X(e,"in",r.in)))),"notIn"in r&&(s=w(s,te(G(t,X(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;D(e,"contains",a),s=_(t)?w(s,P):w(s,$(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(s=w(s,$(r.isNull===!0===_(t)))),s},q=(e,t,r)=>t===null?$(r===_(e)):_(e)?P:$(r===(e===t)),Ie=(e,t,r)=>{let s=E;return"eq"in r&&(D(e,"eq",r.eq),s=w(s,q(t,r.eq,!0))),"ne"in r&&(D(e,"ne",r.ne),s=w(s,q(t,r.ne,!1))),s},Te=(e,t,r)=>w(Ie(e,t,r),w(_e(e,t,r),Pe(e,t,r))),$e=(e,t,r,s)=>{if(t==="NOT")return te(s(e,r??{}));if(!Array.isArray(r))return B;let a=t==="AND"?E:B;for(const l of r){const f=s(e,l);a=t==="AND"?w(a,f):me(a,f)}return a},ne=e=>e==="AND"||e==="OR"||e==="NOT",Me=e=>M(e)&&Object.keys(e).every(t=>Se.includes(t)),U=e=>Object.keys(e).some(t=>{const r=e[t];return ne(t)?t==="NOT"?U(r??{}):Array.isArray(r)&&r.some(s=>U(s??{})):We(r)}),re=(e,t)=>{let r=E;for(const s of Object.keys(t)){const a=t[s];if(ne(s)){r=w(r,$e(e,s,a,re));continue}const l=we(e,s);if(Me(a)){r=w(r,Te(s,l,a));continue}D(s,"eq",a),r=w(r,q(l,a,!0))}return r},j=(e,t)=>re(e,t)===E,oe=500,I=(e,t,r)=>{const s=t??oe;if(e>s)throw new b("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(e)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},De=pe(),Fe=Symbol.for("lunora.ctxdb.rls-unwrap"),se=Symbol.for("lunora.rls.wrapped-chain"),Le=e=>e[se],Ce=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Ue=(e,t)=>{const r=[];let s=!1;for(const a of e){if(a.on!=="read")continue;const l=a.when(t);if(l!==void 0){if(l===!0){s=!0;break}l!==!1&&r.push(l)}}if(!s)return r.length===0?De:r.length===1?r[0]:{OR:r}},je=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(U(s))throw new b("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return j(r,s)},Ne=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||je(e,t,r);if(s===!1)return!1;if(U(s))throw new b("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!j(t.row,s)?!1:r===void 0||j(r,s)},qe=(e,t,r,s)=>{let a=!1;for(const l of e)if(l.on===t&&(a=!0,!Ne(l,r,s)))return!1;return a},Ye=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),xe=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":M(t),He=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ye.has(r)&&xe(r,e[r]))},Ke=e=>e===void 0?{}:M(e)&&He(e)?e:{where:e},Y=e=>e!==void 0&&Object.keys(e).length>0,Qe=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>Y(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ze=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},Xe=(e,t,r)=>{const[s]=r,a=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),l=new Map,f=n=>{const o=l.get(n);if(o)return o;const i=[];let c=!1;for(const h of r){const u=h.perTable.get(n);if(!u||u.length===0||!u.some(L=>L.on==="read"))continue;c=!0;const y=Ue(u,h.context);y!==void 0&&i.push(y)}const d={baseWhere:Qe(i),restricts:c};return l.set(n,d),d},v=(n,o,i,c)=>{for(const d of r){const h=d.perTable.get(n);if(h&&!qe(h,o,{...d.context,row:i},c))return!1}return!0},p=n=>f(n).restricts?t:e,g=n=>f(n).baseWhere,A=async(n,o,i)=>{if(t.lookupById){const y=await t.lookupById(n,o);if(y)return{row:y.row,tableName:a.has(y.tableName)?y.tableName:void 0}}const c=await t.get(n,o);if(!c)return{row:null,tableName:void 0};const d=o??i,h=d===void 0?[...a.keys()]:[d].filter(y=>a.has(y)),u=await Promise.all(h.map(async y=>(await t.findFirst(y,{limit:1,where:{_id:n}}))?._id===n?y:void 0));return{row:c,tableName:u.find(y=>y!==void 0)}},N=async(n,o,i)=>{const c=await A(n,o,i);return c.row&&c.tableName!==void 0?{row:c.row,tableName:c.tableName}:void 0},O=async(n,o,i,c,d,h)=>{const u=await N(n,d,h);if(!u)return i(e);const y=c?c(u.row):void 0;if(!v(u.tableName,o,u.row,y))throw new b("FORBIDDEN",`${o} denied by policy`);return i(t,u.tableName)},k=(n,o,i,c)=>O(n,"update",(d,h)=>i(d,{verify:h===void 0?void 0:(u,y)=>v(h,"update",u,y)}),d=>({...d,...ke(o,d)}),c),S=(n,o)=>{const{baseWhere:i}=f(n);if(Y(i))throw new b("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},F=e.rankBefore,ae=e.rankPageRows,{relationEdges:H}=e,m={...e,async count(n,o){const{baseWhere:i}=f(n),c=Ke(o);return p(n).count(n,{...c,baseWhere:W(c.baseWhere,i),relationBaseWhere:g,restrictsCounts:(c.restrictsCounts??!1)||Y(i)})},delete:(n,o,i)=>O(n,"delete",c=>c.delete(n,o,i),void 0,o),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??oe),{baseWhere:c}=f(n);let d=0;for(;;){const u=(await p(n).findMany(n,{baseWhere:c,limit:i,relationBaseWhere:g})).page.map(y=>String(y._id));if(u.length===0)break;for(const y of u)await O(y,"delete",L=>L.delete(y,void 0,o?.hard===void 0?void 0:{hard:o.hard}),void 0,void 0,n),d+=1;if(u.length<i)break}return{deleted:d}},async deleteMany(n,o,i){I(n.length,o?.limit,"deleteMany");for(const c of n)await O(c,"delete",d=>d.delete(c,i),void 0,i);return{deleted:n.length}},async deleteWhere(n,o,i){const{baseWhere:c}=f(n),h=(await p(n).findMany(n,{baseWhere:W(o,c),relationBaseWhere:g})).page.map(u=>String(u._id));I(h.length,i?.limit,"deleteWhere");for(const u of h)await O(u,"delete",y=>y.delete(u),void 0,void 0,n);return{deleted:h.length}},async findFirst(n,o){const{baseWhere:i}=f(n);return p(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async findFirstOrThrow(n,o){const{baseWhere:i}=f(n);return p(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async explain(n,o){const{baseWhere:i}=f(n);return p(n).explain(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async findMany(n,o){const{baseWhere:i}=f(n);return p(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async get(n,o){const i=await A(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:d}=f(i.tableName);if(!d)return e.get(n,o);if(!c)return i.row;const h=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return h?._id===n?h:null},async lookupById(n,o){const i=await A(n,o);if(!i.row)return null;if(i.tableName===void 0||!f(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=f(i.tableName);if(!c)return{row:i.row,tableName:i.tableName};const d=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:i.tableName}:null},async insert(n,o,i){if(a.has(n)){if(!v(n,"insert",o))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(I(o.length,i?.limit,"insertMany"),a.has(n)){for(const c of o)if(!v(n,"insert",c))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(I(o.length,i?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!v(n,"insert",c))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i)=>k(n,o,(c,d)=>c.patch(n,o,i,d),i),assertPatchAllowed:(n,o)=>k(n,{},()=>Promise.resolve(),o),async patchIf(n,o,i){const c=await k(o,i.patch,async(h,u)=>{if(h.patchIf===void 0)throw new b("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return h.patchIf(n,o,{...i,verify:u.verify})},n);return c.doc===null||await m.get(o,n).then(h=>h!==null,h=>{if(le(h)&&h.code==="RLS_REQUIRED")return!1;throw h})?c:{applied:c.applied,doc:null}},async patchMany(n,o,i){I(n.length,o?.limit,"patchMany");for(const c of n)await k(c.id,c.patch,(d,h)=>d.patch(c.id,c.patch,i,h),i);return{patched:n.length}},async patchWhere(n,o,i){const{baseWhere:c}=f(n),h=(await p(n).findMany(n,{baseWhere:W(o.where,c),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:o.patch}));return I(h.length,i?.limit,"patchWhere"),m.patchMany(h,i)},query(n){const{baseWhere:o}=f(n),i=p(n).query(n);return o?i.filter(de(o,c=>j(c,o))):i},related:H===void 0?void 0:async(n,o)=>fe({findMany:async(i,c)=>m.findMany(i,c),lookupById:async i=>t.lookupById?.(i)},H,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>O(n,"update",async i=>{const c=i.restore??t.restore;if(!c)throw new b("BAD_REQUEST","restore is not supported by this writer");await c(n,o)},void 0,o),replace:(n,o,i)=>O(n,"update",c=>c.replace(n,o,i),c=>({...o,_creationTime:o._creationTime??c._creationTime,_id:c._id}),i),aggregate(n,o){const{baseWhere:i}=f(n);return p(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,i),relationBaseWhere:g})},groupBy(n,o){const{baseWhere:i}=f(n);return p(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,i),relationBaseWhere:g})},rank(n,o,i){return S(n,"rank"),p(n).rank(n,o,i)},rankPage(n,o,i){return S(n,"rankPage"),p(n).rankPage(n,o,i)},wipeShard(){throw new b("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",F,n=>(o,i,c)=>(S(o,"rankBefore"),(p(o).rankBefore??n)(o,i,c))),...Q("rankPageRows",ae,n=>(o,i,c)=>(S(o,"rankPageRows"),(p(o).rankPageRows??n)(o,i,c)))},ce=m;if(a.size>0)for(const[n,o]of Object.entries(e))ze(o)&&(ce[n]=he(m,n));return Object.defineProperty(m,se,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),m},ie=e=>typeof e=="string"?e:e.name,Ge=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>ie(s))));return t},Je=(e,t)=>{const r=new Set;for(const s of e)for(const a of t.get(s)??[])r.add(a);return s=>r.has(ie(s))},Ze=["roles","role"],Ve=e=>{for(const t of Ze){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(a=>typeof a=="string"&&a.length>0);if(s.length>0)return s}}return[]},et=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...Ve(r),...e.roles??[]])];return{can:Je(s,t),identity:r,roles:s,userId:e.userId??null}},ct=(e,t={})=>{const r=e,s=Ce(r),a=Ge(t.roles);return ye(async({ctx:f,next:v})=>{const p={auth:await et(f.auth??{},a),ctx:f},g=f.db,A=Le(g),N=A?.base??g,O=A?.raw??g[Fe]??g,k=Xe(N,O,[...A?.steps??[],{context:p,perTable:s}]),S={db:k},{orm:F}=f;return F!==null&&typeof F=="object"&&(S.orm=ue(k)),v({ctx:S})},[{policies:r,roles:t.roles??[]}])};export{et as a,ze as b,at as c,We as d,Ve as e,Ue as f,Je as g,qe as h,Ge as i,j as m,Q as o,ct as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{c as W}from"./compose-middleware-BK9FlblN.mjs";import{v as S}from"@lunora/values";const C=["de","en","es","fr","it","nl","none","pt"],K=["native","portable"],Y=e=>K.includes(e),Z=e=>C.includes(e),ee=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},H=e=>{if(e.kind==="literal")return ee(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?H(t):e.kind},te=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ne=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,re=(e,t,n)=>e.some(r=>r.unique===!0&&r.fields.length===2&&r.fields.includes(t)&&r.fields.includes(n)),ae=e=>{const t=e?.kind==="id"?e._meta?.tableName:void 0;return typeof t=="string"?t:void 0},oe=(e,t,n,r)=>{const{from:a,table:c,to:d}=r.through,l=`defineSchema: relation "${n}" on table "${t}" (through "${c}")`,f=e[c];if(f===void 0)throw new s("INTERNAL",`${l} names a join table that is not declared`);if(e[r.table]===void 0)throw new s("INTERNAL",`${l} targets "${r.table}", which is not declared`);if(a===d)throw new s("INTERNAL",`${l}: "from" and "to" both name "${a}"; a link needs two different columns`);for(const[p,h]of[[a,t],[d,r.table]])if(ae(f.shape[p])!==h)throw new s("INTERNAL",`${l}: "${c}.${p}" must be a required v.id("${h}") column`);if(!re(f.indexes,a,d))throw new s("INTERNAL",`${l} needs a unique index over ("${a}", "${d}") on "${c}": ${JSON.stringify(`.index("by_${a}_${d}", ["${a}", "${d}"], { unique: true })`)}. Without it a repeated connect stores the same link twice.`)},U=e=>{for(const[t,n]of Object.entries(e))for(const[r,a]of Object.entries(n.relationMap))a.through!==void 0&&oe(e,t,r,a)},F=16;function ie(e,t){return"through"in t?{kind:"many",table:e,through:{...t.through}}:{field:t.field,kind:"many",references:t.references??"_id",table:e}}const se={many:ie,one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},x=(e,t,n)=>({handler:n,op:t,timing:e}),de=()=>({afterDelete:e=>x("after","delete",e),afterInsert:e=>x("after","insert",e),afterUpdate:e=>x("after","update",e),beforeDelete:e=>x("before","delete",e),beforeInsert:e=>x("before","insert",e),beforeUpdate:e=>x("before","update",e)}),Q=(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}))},Te=e=>{const t={...e},n=[],r=[],a=[],c=[],d={},l=[],f={},p=de(),h=[];let m={kind:"root"},g=!1,A=!1,E=!1,M=!1,O=!1,j,T,I;const D=(i,o)=>{i in t||(t[i]=o)};let _,B;const q=i=>{if(m.kind!=="root"&&m.kind!==i.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.");m=i},u={aggregateIndex(i,o){const b=o?.op??"count";if(b!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${b}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:i,on:"",op:b,where:o?.where}),u},get aggregateIndexes(){return n},get externalSource(){return B},commitOrdered(){return g=!0,u},get commitOrderedMode(){return g},dropStalePatches(){return A=!0,u},get dropStalePatchesMode(){return A},externallyManaged(){return E=!0,u},geoIndex(i,o){return r.push({field:o.field,name:i,precision:o.precision}),u},get geoIndexes(){return r},global(i){return q({backend:i?.backend??"d1",kind:"global"}),u},get isExternallyManaged(){return E},get isPublic(){return O},index(i,o,b){return a.push({fields:o,name:i,unique:b?.unique??!1}),u},get indexes(){return a},memory(){return M=!0,u},get memoryMode(){return M},ownedBy(i){return j=i,u},get ownerField(){return j},public(){return O=!0,u},rankIndex(i,o){return c.push({name:i,on:"",partitionBy:o.partitionBy,sortBy:Q(i,o.sortBy),where:o.where}),u},get rankIndexes(){return c},get relationMap(){return d},relations(i){return Object.assign(d,i(se)),u},searchIndex(i,o){if(o.filterFields&&o.filterFields.length>F)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(F)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:b}=o;if(b!==void 0&&!Z(b))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${b}" (supported: ${C.join(", ")})`);const{strategy:w}=o;if(w!==void 0&&!Y(w))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${w}" (supported: ${K.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:i,staged:o.staged,strategy:o.strategy}),u},get searchIndexes(){return l},shape:t,shardBy(i){return q({field:i,kind:"shardBy"}),u},get shardMode(){return m},get softDeleteMode(){return T},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return B=i,E=!0,u},softDelete(i){const o=i?.field??"deletedAt";if(T={field:o},o===I)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);return D(o,S.optional(S.number().nullable())),u},timestamps(i){const o=i?.field??"updatedAt";if(I!==void 0)throw new s("INTERNAL",`defineTable: .timestamps() was called twice ("${I}" and "${o}"); one table tracks one last-change column`);if(o===T?.field)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);const b=t[o],w=b?._meta?.column;if(b!==void 0&&(b.kind!=="timestamp"||w?.onUpdateFn===void 0||w.defaultFn===void 0&&w.defaultValue===void 0))throw new s("INTERNAL",`defineTable: .timestamps() would add "${o}", but the table already declares it as something other than v.timestamp().defaultNow().$onUpdateFn(() => Date.now()); remove the column or declare it that way`);return I=o,D(o,S.timestamp().defaultNow().$onUpdateFn(()=>Date.now())),u},get triggerMap(){return f},triggers(i){return Object.assign(f,i(p)),u},ttl(i,o){return _={after:o?.after,field:i},u},get ttlPolicy(){return _},get vectorIndexes(){return h},vectorize(i,o){return h.push({dimensions:o.dimensions,embed:o.embed,field:i,metadata:o.metadata,metric:o.metric,model:o.model,name:o.index}),u}};return u},Se=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,model:e.model,select:e.source.select,table:e.source.table}),Le=(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}},Re=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:Q(e,t.sortBy),where:t.where}),v=e=>({...e,extend(t){return v(J(e,t))},jurisdiction(t,n){return v(e)},rls(t){return v({...e,rlsMode:t})}}),le=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},ce=(e,t,n)=>{for(const r of Object.values(t)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);a.aggregateIndexes.push(r)}for(const r of Object.values(n)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);a.rankIndexes.push(r)}},ue=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},he=(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=ue(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).`)},fe=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.`);he(t,r)}}},me=["_commitSeq","_creationTime","_id"],P="_commitSeq",be=new Set(me),N=(e,t,n,r)=>{if(!(be.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`)},L=(e,t,n,r)=>{const a=new Set;for(const c of n){if(a.has(c.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${c.name}" more than once`);a.add(c.name),r(c)}},z=e=>{for(const[t,n]of Object.entries(e))L(t,"index",n.indexes,r=>{for(const a of r.fields)N(t,r.name,a,n)}),L(t,"rank index",n.rankIndexes,r=>{for(const a of r.sortBy)N(t,r.name,a.field,n);for(const a of r.partitionBy??[])N(t,r.name,a,n)}),L(t,"geo index",n.geoIndexes,r=>{N(t,r.name,r.field,n)})},R=(e,t,n)=>{if(e.length===0)return;const r={};for(const a of e)r[t(a)]=n(a);return r},ge=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},Ae=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=R(r.geoIndexes,l=>l.name,l=>[l.field]),c=R(r.indexes,l=>l.name,l=>l.fields),d=R(r.rankIndexes,l=>l.name,ge);(a||c||d)&&(t[n]={...a?{geo:a}:{},...c?{index:c}:{},...d?{rank:d}:{}})}return t},we=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const a=[[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(([c])=>c)?.[1];if(a!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${a}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},pe=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,a]of Object.entries(n.shape))if(H(a)==="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.`)}},xe=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},ye=e=>{for(const[t,n]of Object.entries(e))if(n.ttlPolicy!==void 0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${te(t)}`)},X=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,a])=>a.vectorIndexes.map(c=>[r,c.name])),...Object.entries(t).map(([r,a])=>[a.table,r])];for(const[r,a]of n)if(e[r]?.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${ne(r,a)}`)},Ie=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(P))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${P}", 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.`)}},G=e=>{Ie(e),xe(e),pe(e),ye(e),we(e)},Me=(e,t={},n={},r={})=>(le(e),ce(e,n,r),fe(e),G(e),X(e,t),z(e),U(e),v({tables:e,vectorIndexes:t})),k=(e,t)=>`${e}_${t}`,y=(e,t,n)=>n.has(e)?k(t,e):e,V=(e,t)=>({...e,_meta:t}),$=(e,t)=>{const n=e._meta;if(n===void 0)return e;if(e.kind==="id"&&n.tableName!==void 0){const d=t(n.tableName);return d===n.tableName?e:V(e,{...n,tableName:d})}const r=d=>d===void 0?void 0:$(d,t),a={...n,...n.inner&&{inner:r(n.inner)},...n.keyValidator&&{keyValidator:r(n.keyValidator)},...n.valueValidator&&{valueValidator:r(n.valueValidator)},...n.members&&{members:n.members.map(d=>$(d,t))},...n.shape&&{shape:Object.fromEntries(Object.entries(n.shape).map(([d,l])=>[d,$(l,t)]))}};return a.inner===n.inner&&a.keyValidator===n.keyValidator&&a.valueValidator===n.valueValidator&&(a.members??[]).every((d,l)=>d===n.members?.[l])&&Object.entries(a.shape??{}).every(([d,l])=>l===n.shape?.[d])?e:V(e,a)},Ne=(e,t,n,r)=>{const a=k(t,r),c=h=>h===""?a:y(h,t,n),d={};for(const[h,m]of Object.entries(e.relationMap)){const g=y(m.table,t,n);d[h]=m.through===void 0?{...m,table:g}:{...m,table:g,through:{...m.through,table:y(m.through.table,t,n)}}}const l=e.aggregateIndexes.map(h=>({...h,on:c(h.on)})),f=e.rankIndexes.map(h=>({...h,on:c(h.on)})),p=Object.fromEntries(Object.entries(e.shape).map(([h,m])=>[h,$(m,g=>y(g,t,n))]));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:d,shape:p}},Oe=(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}:{}}},ve=((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}:{}}}),je=(e,t)=>({...ve(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),J=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),a={...e.tables};for(const[d,l]of Object.entries(t.tables)){const f=k(n,d);if(Object.hasOwn(a,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`);a[f]=Ne(l,n,r,d)}const c={...e.vectorIndexes};if(t.vectorIndexes)for(const[d,l]of Object.entries(t.vectorIndexes)){const f=k(n,d);if(Object.hasOwn(c,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`);c[f]={...l,table:y(l.table,n,r)}}return z(a),G(a),X(a,c),U(a),{rlsMode:e.rlsMode,tables:a,vectorIndexes:c}},De=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=J(n,r.extension));return n},_e=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return W(t)};export{je as a,ve as b,_e as c,Le as d,Re as e,Me as f,Oe as g,Te as h,Se as i,Ae as j,De as k,z as l,J as m,G as n,X as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as i,h as m,i as l,b as p,m as d,e as h,g as n,a as c,r as u}from"./middleware-
|
|
1
|
+
import{f as i,h as m,i as l,b as p,m as d,e as h,g as n,a as c,r as u}from"./middleware-DbhB1jRk.mjs";import"./wire-codec-CZ4obM6q.mjs";import"./bindOrm-BHq_oUP2.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{i as computeReadBaseWhere,m as evaluateWrite,l as indexRolePermissions,p as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,c as resolvePolicyAuth,u as rls};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-
|
|
1
|
+
import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-DbhB1jRk.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" 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 })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-
|
|
1
|
+
import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-DbhB1jRk.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/dist/types.d.mts
CHANGED
|
@@ -651,23 +651,51 @@ interface RankIndexDefinition {
|
|
|
651
651
|
/** FK behavior when a referenced parent row is deleted (mirrors SQL `ON DELETE`). */
|
|
652
652
|
type OnDeleteAction = "cascade" | "restrict" | "set null";
|
|
653
653
|
/**
|
|
654
|
-
*
|
|
654
|
+
* The join table behind a many-to-many relation, declared by
|
|
655
|
+
* `r.many(target, { through: { table, from, to } })`.
|
|
655
656
|
*
|
|
656
|
-
* - `
|
|
657
|
-
*
|
|
658
|
-
* - `
|
|
659
|
-
|
|
657
|
+
* - `table` — the join table, one row per linked pair.
|
|
658
|
+
* - `from` — the join table's `v.id` column pointing at the table that declares the relation.
|
|
659
|
+
* - `to` — the join table's `v.id` column pointing at the relation's target table.
|
|
660
|
+
*/
|
|
661
|
+
interface RelationThrough {
|
|
662
|
+
from: string;
|
|
663
|
+
table: string;
|
|
664
|
+
to: string;
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* A relation backed by one foreign-key column: `one` (many-to-one) or `many` (one-to-many).
|
|
668
|
+
*
|
|
669
|
+
* - `one`: the FK column `field` lives on **this** table and points at
|
|
670
|
+
* `table`.`references` (default `_id`). Loads a single doc.
|
|
671
|
+
* - `many`: the FK column `field` lives on the **target** table and points back
|
|
672
|
+
* at this table's `references` (default `_id`). Loads an array.
|
|
660
673
|
*
|
|
661
674
|
* `onDelete` is meaningful only on `one`: it is the action applied to the
|
|
662
675
|
* holder rows when the referenced parent row is deleted.
|
|
663
676
|
*/
|
|
664
|
-
interface
|
|
677
|
+
interface KeyedRelationDefinition {
|
|
665
678
|
field: string;
|
|
666
679
|
kind: "many" | "one";
|
|
667
680
|
onDelete?: OnDeleteAction;
|
|
668
681
|
references: string;
|
|
669
682
|
table: string;
|
|
683
|
+
through?: never;
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* A many-to-many relation: the link lives in the `through` join table, whose `from` column points at this
|
|
687
|
+
* table's `_id` and whose `to` column points at `table`'s `_id`. Loads an array of `table` rows.
|
|
688
|
+
*
|
|
689
|
+
* It has no `field`/`references`/`onDelete` of its own: the two foreign keys are the join table's, and a delete
|
|
690
|
+
* on either side cascades through the `onDelete` of the join table's own `r.one(...)` relations.
|
|
691
|
+
*/
|
|
692
|
+
interface ThroughRelationDefinition {
|
|
693
|
+
kind: "many";
|
|
694
|
+
table: string;
|
|
695
|
+
through: RelationThrough;
|
|
670
696
|
}
|
|
697
|
+
/** A declared relation between two tables, recorded by `.relations((r) => …)`: a single-key relation or a many-to-many one. */
|
|
698
|
+
type RelationDefinition = KeyedRelationDefinition | ThroughRelationDefinition;
|
|
671
699
|
/** Distance metric used by a Vectorize index. */
|
|
672
700
|
type VectorMetric = "cosine" | "dot-product" | "euclidean";
|
|
673
701
|
/**
|
|
@@ -2809,4 +2837,4 @@ interface ActionCtx {
|
|
|
2809
2837
|
/** Start / resume / inspect durable workflows; see {@link Workflows}. */
|
|
2810
2838
|
readonly workflows: Workflows;
|
|
2811
2839
|
}
|
|
2812
|
-
export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
|
|
2840
|
+
export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, KeyedRelationDefinition, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RelationThrough, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, ThroughRelationDefinition, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
|
package/dist/types.d.ts
CHANGED
|
@@ -651,23 +651,51 @@ interface RankIndexDefinition {
|
|
|
651
651
|
/** FK behavior when a referenced parent row is deleted (mirrors SQL `ON DELETE`). */
|
|
652
652
|
type OnDeleteAction = "cascade" | "restrict" | "set null";
|
|
653
653
|
/**
|
|
654
|
-
*
|
|
654
|
+
* The join table behind a many-to-many relation, declared by
|
|
655
|
+
* `r.many(target, { through: { table, from, to } })`.
|
|
655
656
|
*
|
|
656
|
-
* - `
|
|
657
|
-
*
|
|
658
|
-
* - `
|
|
659
|
-
|
|
657
|
+
* - `table` — the join table, one row per linked pair.
|
|
658
|
+
* - `from` — the join table's `v.id` column pointing at the table that declares the relation.
|
|
659
|
+
* - `to` — the join table's `v.id` column pointing at the relation's target table.
|
|
660
|
+
*/
|
|
661
|
+
interface RelationThrough {
|
|
662
|
+
from: string;
|
|
663
|
+
table: string;
|
|
664
|
+
to: string;
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* A relation backed by one foreign-key column: `one` (many-to-one) or `many` (one-to-many).
|
|
668
|
+
*
|
|
669
|
+
* - `one`: the FK column `field` lives on **this** table and points at
|
|
670
|
+
* `table`.`references` (default `_id`). Loads a single doc.
|
|
671
|
+
* - `many`: the FK column `field` lives on the **target** table and points back
|
|
672
|
+
* at this table's `references` (default `_id`). Loads an array.
|
|
660
673
|
*
|
|
661
674
|
* `onDelete` is meaningful only on `one`: it is the action applied to the
|
|
662
675
|
* holder rows when the referenced parent row is deleted.
|
|
663
676
|
*/
|
|
664
|
-
interface
|
|
677
|
+
interface KeyedRelationDefinition {
|
|
665
678
|
field: string;
|
|
666
679
|
kind: "many" | "one";
|
|
667
680
|
onDelete?: OnDeleteAction;
|
|
668
681
|
references: string;
|
|
669
682
|
table: string;
|
|
683
|
+
through?: never;
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* A many-to-many relation: the link lives in the `through` join table, whose `from` column points at this
|
|
687
|
+
* table's `_id` and whose `to` column points at `table`'s `_id`. Loads an array of `table` rows.
|
|
688
|
+
*
|
|
689
|
+
* It has no `field`/`references`/`onDelete` of its own: the two foreign keys are the join table's, and a delete
|
|
690
|
+
* on either side cascades through the `onDelete` of the join table's own `r.one(...)` relations.
|
|
691
|
+
*/
|
|
692
|
+
interface ThroughRelationDefinition {
|
|
693
|
+
kind: "many";
|
|
694
|
+
table: string;
|
|
695
|
+
through: RelationThrough;
|
|
670
696
|
}
|
|
697
|
+
/** A declared relation between two tables, recorded by `.relations((r) => …)`: a single-key relation or a many-to-many one. */
|
|
698
|
+
type RelationDefinition = KeyedRelationDefinition | ThroughRelationDefinition;
|
|
671
699
|
/** Distance metric used by a Vectorize index. */
|
|
672
700
|
type VectorMetric = "cosine" | "dot-product" | "euclidean";
|
|
673
701
|
/**
|
|
@@ -2809,4 +2837,4 @@ interface ActionCtx {
|
|
|
2809
2837
|
/** Start / resume / inspect durable workflows; see {@link Workflows}. */
|
|
2810
2838
|
readonly workflows: Workflows;
|
|
2811
2839
|
}
|
|
2812
|
-
export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
|
|
2840
|
+
export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, KeyedRelationDefinition, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RelationThrough, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, ThroughRelationDefinition, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
|
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.195",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -71,9 +71,9 @@
|
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
73
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
74
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
75
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
76
|
-
"@lunora/values": "1.0.0-alpha.
|
|
74
|
+
"@lunora/scheduler": "1.0.0-alpha.121",
|
|
75
|
+
"@lunora/shard-engine": "1.0.0-alpha.124",
|
|
76
|
+
"@lunora/values": "1.0.0-alpha.64",
|
|
77
77
|
"drizzle-orm": "^0.45.3",
|
|
78
78
|
"hono": "^4.13.13"
|
|
79
79
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{i as T}from"./wire-codec-CZ4obM6q.mjs";const L=new Set(["connect","disconnect","set"]),y=500,A=(n,t,i)=>n!==void 0&&Object.hasOwn(n,t)&&T(i),u=(n,t)=>{throw new h(n,t)},w=(n,t)=>{if(!Array.isArray(n)||n.some(s=>typeof s!="string"))return u("VALIDATION_ERROR",`${t} must be an array of ids`);const i=[...new Set(n)];return i.length>y&&u("VALIDATION_ERROR",`${t} names ${String(i.length)} rows; at most ${String(y)} per list`),i},O=(n,t,i)=>{t.nullable||u("VALIDATION_ERROR",`${n}.${i}: "${t.field}" cannot be empty; make it optional or nullable to allow it`)},x=(n,t,i)=>{const{connect:s,disconnect:o,set:c}=i;return c!==void 0&&u("VALIDATION_ERROR",`${n} is a to-one relation: use connect or disconnect, not set`),s!==void 0&&o!==void 0&&u("VALIDATION_ERROR",`${n}: connect and disconnect together are ambiguous`),s!==void 0?(typeof s!="string"&&u("VALIDATION_ERROR",`${n}.connect must be an id`),{connect:s,info:t,name:n}):(o!==!0&&u("VALIDATION_ERROR",`${n}.disconnect must be true`),O(n,t,"disconnect"),{info:t,name:n})},_=(n,t,i)=>{const{connect:s,disconnect:o,set:c}=i;return c!==void 0?((s!==void 0||o!==void 0)&&u("VALIDATION_ERROR",`${n}: set replaces the whole list and cannot be combined with connect or disconnect`),O(n,t,"set"),{attach:[],info:t,name:n,release:[],replace:w(c,`${n}.set`)}):(o!==void 0&&O(n,t,"disconnect"),{attach:s===void 0?[]:w(s,`${n}.connect`),info:t,name:n,release:o===void 0?[]:w(o,`${n}.disconnect`)})},M=(n,t,i,s)=>{const o=Object.fromEntries(Object.entries(s).filter(([,r])=>r!==void 0)),c=Object.keys(o).find(r=>!L.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${n}: "${t}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(o).length!==0)return i.refusal!==void 0&&u("UNPROCESSABLE",`ctx.db.${n}: relation "${t}" cannot be written: ${i.refusal}`),i.colocated||u("UNPROCESSABLE",`ctx.db.${n}: relation "${t}" crosses to "${i.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),i.kind==="one"?x(t,i,o):_(t,i,o)},g=(n,t,i)=>{if(t===void 0)return{columns:i,manys:[],ones:[]};const s={},o=[],c=[];for(const[r,l]of Object.entries(i)){if(!A(t,r,l)){s[r]=l;continue}const e=M(n,r,t[r],l);e!==void 0&&(e.info.kind==="one"?c.push(e):o.push(e))}for(const{info:r,name:l}of c)Object.hasOwn(s,r.field)&&u("VALIDATION_ERROR",`ctx.db.${n}: ${l} and its key "${r.field}" are both set; set one or the other`);return{columns:s,manys:o,ones:c}},R=(n,t,i,s)=>{const o=Object.entries(i).find(([c,r])=>A(t,c,r))?.[0];o!==void 0&&u("VALIDATION_ERROR",`ctx.db.${n}.${s}: "${o}" is a relation write, which ${s} does not support; use insert or patch`)},$=async(n,t,i,s,o)=>{const c=await n.get(o,s);return c===null&&u("NOT_FOUND",`${t}.${i}: no "${s}" row with id "${o}"`),c},I=async(n,t)=>{const i={...t.columns};for(const{connect:s,info:o,name:c}of t.ones){let r=null;s!==void 0&&(r=(await $(n,c,"connect",o.table,s))[o.references]),i[o.field]=r}return i},D=async(n,{info:t,name:i},s,o)=>{(await $(n,i,"connect",t.table,s))[t.field]!==o&&await n.patch(s,{[t.field]:o},t.table)},S=async(n,{info:t},i,s)=>{i[t.field]===s&&await n.patch(String(i._id),{[t.field]:null},t.table)},b=async(n,{info:t,name:i},s)=>{const{page:o}=await n.findMany(t.table,{limit:y+1,where:{[t.field]:s}});return o.length>y&&u("VALIDATION_ERROR",`${i}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},v=async(n,t,i,s)=>{for(const o of i.manys){const c=await s(o.info.references);c==null&&u("VALIDATION_ERROR",`ctx.db.${t}: ${o.name} is keyed on "${o.info.references}", which this row has no value for`);let{attach:r}=o,l;if(o.replace===void 0)l=await Promise.all(o.release.map(e=>$(n,o.name,"disconnect",o.info.table,e)));else{const e=await b(n,o,c),a=new Set(e.map(d=>String(d._id)));l=e.filter(d=>!o.replace?.includes(String(d._id))),r=o.replace.filter(d=>!a.has(d))}for(const e of l)await S(n,o,e,c);for(const e of r)await D(n,o,e,c)}},E=(n,t,i,s)=>async o=>o==="_id"?i:Object.hasOwn(s,o)?s[o]:(await n.get(i,t))?.[o],k=async(n,t,i,s,o)=>{const c=g(t,i,s);if(c.ones.length===0&&c.manys.length===0)return o(c.columns);const r=await I(n,c),l=await o(r);return l!==null&&await v(n,t,c,E(n,t,l,r)),l},V=async(n,t,i,s,o)=>{const c=g(t,i,o);if(c.ones.length===0&&c.manys.length===0){await n.patch(s,c.columns,t);return}const r=await I(n,c);if(Object.keys(r).length>0)await n.patch(s,r,t);else{if(await n.get(s,t)===null)throw new h("NOT_FOUND",`document not found: ${s}`);await n.assertPatchAllowed?.(s,t)}await v(n,t,c,E(n,t,s,r))},j=n=>typeof n=="object"&&n!==null&&n.code==="CONFLICT"&&n.kind==="unique",W=(n,t,i,s)=>{const o=typeof t=="string"?[t]:t;if(o.length===0)throw new h("INTERNAL",`ctx.db.${n}.upsert: "target" must name at least one field`);const c={};for(const r of o){if(!(r in i)){const l=Object.entries(s??{}).find(([e,a])=>a.kind==="one"&&a.field===r&&e in i)?.[0];throw l!==void 0?new h("VALIDATION_ERROR",`ctx.db.${n}.upsert: target field "${r}" is supplied by the "${l}" relation write; pass "${r}" itself so the existing row can be found`):new h("INTERNAL",`ctx.db.${n}.upsert: target field "${r}" is missing from the create document`)}c[r]=i[r]}return c},q=(n,t)=>{const i=async(e,a)=>{if(a?.skipDuplicates!==!0)return n.insert(t,e);try{return await n.insert(t,e)}catch(d){if(j(d))return null;throw d}},s=n.relationWrites?.[t],o=(e,a)=>k(n,t,s,e,d=>i(d,a)),c=(e,a)=>V(n,t,s,e,a),r=async e=>{const a=e??{},d=await n.findMany(t,{...a,limit:2});if(d.page.length>1)throw new h("NOT_UNIQUE",`ctx.db.${t}.findUnique matched more than one document; expected at most one`);return d.page[0]??null},l=async({create:e,target:a,update:d})=>{const p=W(t,a,e,s),f=await n.findFirst(t,{where:p});return f&&typeof f._id=="string"?(await c(f._id,d??e),{created:!1,id:f._id}):{created:!0,id:await o(e)}};return{aggregate:e=>n.aggregate(t,e),count:e=>n.count(t,e),delete:e=>n.delete(e,t),deleteMany:(e,a)=>{if(Array.isArray(e)){if(n.deleteMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return n.deleteMany(e,a,t)}if(n.deleteWhere===void 0)throw new h("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const d=e;return n.deleteWhere(t,d.where,{limit:d.limit})},exists:async e=>await n.findFirst(t,e===void 0?void 0:{where:e})!==null,explain:e=>n.explain(t,e),findFirst:e=>n.findFirst(t,e),findFirstOrThrow:e=>n.findFirstOrThrow(t,e),findMany:e=>n.findMany(t,e),findUnique:r,get:e=>n.get(e,t),groupBy:e=>n.groupBy(t,e),hardDelete:e=>n.delete(e,t,{hard:!0}),insert:o,insertMany:(e,a)=>{for(const d of e)R(t,s,d,"insertMany");if(n.insertMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.insertMany is unavailable: this writer has no batch insert`);return n.insertMany(t,e,a)},patch:c,patchMany:(e,a)=>{const d=Array.isArray(e)?e.map(f=>f.values):[e.values];for(const f of d)R(t,s,f,"patchMany");if(Array.isArray(e)){if(n.patchMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return n.patchMany(e.map(f=>({id:f.id,patch:f.values})),a,t)}if(n.patchWhere===void 0)throw new h("INTERNAL",`ctx.db.${t}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const p=e;return n.patchWhere(t,{patch:p.values,where:p.where},{limit:p.limit})},rank:(e,a)=>n.rank(t,e,a),rankPage:(e,a)=>n.rankPage(t,e,a),replace:(e,a)=>(R(t,s,a,"replace"),n.replace(e,a,t)),restore:async e=>{if(!n.restore)throw new h("INTERNAL",`ctx.db.${t}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await n.restore(e,t)},upsert:l,upsertMany:async({rows:e,target:a})=>{const d=[];for(const p of e)d.push(await l({create:p.create,target:a,update:p.update}));return d},withGeoIndex:(e,a)=>n.query(t).withGeoIndex(e,a),withSearchIndex:(e,a)=>n.query(t).withSearchIndex(e,a)}},P=n=>{const t=i=>{const s=n[i];if(!s)throw new h("INTERNAL",`unknown table: ${i}`);return s};return{delete:(i,s)=>t(i).delete(s),insert:i=>({values:s=>t(i).insert(s)}),query:n,replace:(i,s)=>({with:o=>t(i).replace(s,o)}),update:(i,s)=>({set:o=>t(i).patch(s,o)})}};export{P as bindOrm,q as bindTableFacade};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as G,a as C,o as K,b as H,c as J,d as Q}from"./middleware-BZAwl2WQ.mjs";import{bindTableFacade as V,bindOrm as X}from"./bindOrm-BaAMwCFL.mjs";import{tagMaskMiddleware as Y}from"./buildMaskRegistry-DpWMtalG.mjs";const Z=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},u=(s,i,c)=>{const w={...s};for(const[y,g]of Object.entries(i))y in w&&(w[y]=Z(g,s[y],{...c,column:y,row:s}));return w},B=(s,i,c)=>({...s,page:s.page.map(w=>u(w,i,c))}),I=(s,i)=>{const c=J(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},L=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&y.add(f),g())});s(g());for(const f of y)if(I(i,f))throw new A("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${f}" is not supported`)},m=(s,i,c,w)=>{const y=s.rankBefore,g=s.rankPageRows,f=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,c)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?f:(t,o)=>n(t,f(t,o))}},p=(r,n,t,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[n];if(!a)return;const d=a.find(R=>I(e,R));if(d!==void 0)throw new A("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${d}" — use an index whose declared fields are all unmasked, or unmask the column`)},k=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,c)},collect:async()=>(await r.collect()).map(e=>u(e,n,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=u(e.document,n,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>k(r.filter(e=>o(u(e,n,c))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,c):null},order:o=>k(r.order(o),n,t),paginate:async o=>B(await r.paginate(o),n,c),take:async o=>(await r.take(o)).map(a=>u(a,n,c)),unique:async()=>{const o=await r.unique();return o?u(o,n,c):null},withIndex:(o,e)=>(p(t,o,"withIndex","index"),L(e,n,t,"withIndex"),k(r.withIndex(o,e),n,t)),withSearchIndex:(o,e)=>(L(e,n,t,"withSearchIndex"),k(r.withSearchIndex(o,e),n,t)),withGeoIndex:(o,e)=>(p(t,o,"withGeoIndex","geo"),k(r.withGeoIndex(o,e),n,t))}),W=async(r,n)=>{if(s.lookupById){const d=await s.lookupById(r,n);if(d)return{row:d.row,tableName:i.has(d.tableName)?d.tableName:void 0}}const t=await s.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],e=n===void 0?[...i.keys()]:o,a=await Promise.all(e.map(async d=>(await s.findFirst(d,{limit:1,where:{_id:r}}))?._id===r?d:void 0));return{row:t,tableName:a.find(d=>d!==void 0)}},S=(r,n,t)=>{const o=i.get(r);if(!o)return;const e=n.find(a=>typeof a=="string"&&I(o,a));if(e!==void 0)throw new A("MASK_UNSUPPORTED",`${t}() over masked column "${e}" on "${r}" is not supported`)},O=new Set;for(const r of i.values())for(const n of Object.keys(r))O.add(n);const P=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,a]of Object.entries(r))q(e,a,n,t,o)},q=(r,n,t,o,e)=>{if(r==="AND"||r==="OR"){for(const a of Array.isArray(n)?n:[])P(a,t,o,e);return}if(r==="NOT"){P(n,t,o,e);return}if(!r.startsWith("__")){if(I(t,r))throw new A("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(Q(n))for(const a of Object.values(n))P(a,O,`${o}.${r}`,e)}},F=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{O.size===0||n===void 0||P(n,F(r),r,t)},E=(r,n,t,o)=>{if(Array.isArray(n)){for(const e of n)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(I(t,a))throw new A("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},j=(r,n,t)=>{if(!(O.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,e]of Object.entries(n)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,d=`${r}.${o}`;P(a.where,O,d,t),E(d,a.orderBy,O,t),j(d,a.with,t)}},$=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),E(r,n?.orderBy,F(r),t),j(r,n?.with,t)},U=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=U(n);h(r,o?.where,t),h(r,o?.baseWhere,t),j(r,o?.with,t)},_=(r,n)=>Object.hasOwn(i.get(r)??{},n)?n:void 0,v={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[n,t]of Object.entries(s.relationWrites))r[n]=Object.fromEntries(Object.entries(t).map(([o,e])=>{const[a,d]=e.kind==="one"?[n,e.table]:[e.table,n],R=_(a,e.field)??_(d,e.references);return[o,R===void 0?e:{...e,refusal:`"${R}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),s.deleteWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,n,t)},async patchIf(r,n,t){if(h(r,t.where,"patchIf"),s.patchIf===void 0)throw new A("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,n,t),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:u(o.doc,e,c)}:o},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),s.patchWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,n,t)},aggregate(r,n){return S(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),s.aggregate(r,n)},count(r,n){const t=U(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"),s.count(r,n)},async findFirst(r,n){$(r,n,"findFirst");const t=await s.findFirst(r,l(n)),o=i.get(r);return t&&o?u(t,o,c):t},async findFirstOrThrow(r,n){$(r,n,"findFirstOrThrow");const t=await s.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,c):t},async explain(r,n){return $(r,n,"explain"),s.explain(r,n)},async findMany(r,n){$(r,n,"findMany");const t=await s.findMany(r,l(n)),o=i.get(r);return o?B(t,o,c):t},async get(r,n){const{row:t,tableName:o}=await W(r,n),e=o===void 0?void 0:i.get(o);return!t||!e?t:u(t,e,c)},related:s.related?async(r,n)=>await s.related(r,l(n)):void 0,async lookupById(r,n){const t=await s.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,c):t.row,tableName:t.tableName}},groupBy(r,n){return S(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),s.groupBy(r,n)},query(r){const n=s.query(r),t=i.get(r);return t?k(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),p(r,n,"rank","rank"),s.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),p(r,n,"rankPage","rank");const o=await s.rankPage(r,n,t),e=i.get(r);return e?B(o,e,c):o},...K("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),p(n,t,"rankBefore","rank"),r(n,t,o))),...K("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),p(n,t,"rankPageRows","rank");const e=await r(n,t,o),a=i.get(n);return a?{...e,rows:e.rows.map(d=>({...d,doc:u(d.doc,a,c)}))}:e})},z=v;if(O.size>0)for(const[r,n]of Object.entries(s))H(n)&&(z[r]=V(v,r));return v},tr=(s,i={})=>{const c=new Map(Object.entries(s)),w=G(i.roles),y=async({ctx:f,next:l})=>{const p={auth:await C(f.auth??{},w),ctx:f};if(i.bypass?.(p)===!0)return l();const k=m(f.db,c,p,i.indexFields),W={db:k},{orm:S}=f;return S!==null&&typeof S=="object"&&(W.orm=X(k)),l({ctx:W})},g=new Map;for(const[f,l]of c)g.set(f,new Set(Object.keys(l)));return Y(y,{columns:g})};export{tr as mask};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{c as X}from"./compose-middleware-BK9FlblN.mjs";import{v as E}from"@lunora/values";const P=["de","en","es","fr","it","nl","none","pt"],C=["native","portable"],G=e=>C.includes(e),Y=e=>P.includes(e),J=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},K=e=>{if(e.kind==="literal")return J(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?K(t):e.kind},W=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,Z=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,F=16,ee={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}),te=()=>({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)}),H=(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}))},pe=e=>{const t={...e},n=[],r=[],o=[],d=[],u={},c=[],f={},m=te(),w=[];let x={kind:"root"},L=!1,M=!1,v=!1,A=!1,R=!1,O,k,y;const D=(i,a)=>{i in t||(t[i]=a)};let j,B;const _=i=>{if(x.kind!=="root"&&x.kind!==i.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.");x=i},l={aggregateIndex(i,a){const h=a?.op??"count";if(h!=="count"&&!a?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${h}" requires a "field"`);return n.push({by:a?.by,field:a?.field,name:i,on:"",op:h,where:a?.where}),l},get aggregateIndexes(){return n},get externalSource(){return B},commitOrdered(){return L=!0,l},get commitOrderedMode(){return L},dropStalePatches(){return M=!0,l},get dropStalePatchesMode(){return M},externallyManaged(){return v=!0,l},geoIndex(i,a){return r.push({field:a.field,name:i,precision:a.precision}),l},get geoIndexes(){return r},global(i){return _({backend:i?.backend??"d1",kind:"global"}),l},get isExternallyManaged(){return v},get isPublic(){return R},index(i,a,h){return o.push({fields:a,name:i,unique:h?.unique??!1}),l},get indexes(){return o},memory(){return A=!0,l},get memoryMode(){return A},ownedBy(i){return O=i,l},get ownerField(){return O},public(){return R=!0,l},rankIndex(i,a){return d.push({name:i,on:"",partitionBy:a.partitionBy,sortBy:H(i,a.sortBy),where:a.where}),l},get rankIndexes(){return d},get relationMap(){return u},relations(i){return Object.assign(u,i(ee)),l},searchIndex(i,a){if(a.filterFields&&a.filterFields.length>F)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(F)} filterFields are supported (got ${String(a.filterFields.length)})`);const{language:h}=a;if(h!==void 0&&!Y(h))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${h}" (supported: ${P.join(", ")})`);const{strategy:b}=a;if(b!==void 0&&!G(b))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${b}" (supported: ${C.join(", ")})`);return c.push({field:a.field,filterFields:a.filterFields,language:a.language,name:i,staged:a.staged,strategy:a.strategy}),l},get searchIndexes(){return c},shape:t,shardBy(i){return _({field:i,kind:"shardBy"}),l},get shardMode(){return x},get softDeleteMode(){return k},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return B=i,v=!0,l},softDelete(i){const a=i?.field??"deletedAt";if(k={field:a},a===y)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${a}"; give one of them another field`);return D(a,E.optional(E.number().nullable())),l},timestamps(i){const a=i?.field??"updatedAt";if(y!==void 0)throw new s("INTERNAL",`defineTable: .timestamps() was called twice ("${y}" and "${a}"); one table tracks one last-change column`);if(a===k?.field)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${a}"; give one of them another field`);const h=t[a],b=h?._meta?.column;if(h!==void 0&&(h.kind!=="timestamp"||b?.onUpdateFn===void 0||b.defaultFn===void 0&&b.defaultValue===void 0))throw new s("INTERNAL",`defineTable: .timestamps() would add "${a}", but the table already declares it as something other than v.timestamp().defaultNow().$onUpdateFn(() => Date.now()); remove the column or declare it that way`);return y=a,D(a,E.timestamp().defaultNow().$onUpdateFn(()=>Date.now())),l},get triggerMap(){return f},triggers(i){return Object.assign(f,i(m)),l},ttl(i,a){return j={after:a?.after,field:i},l},get ttlPolicy(){return j},get vectorIndexes(){return w},vectorize(i,a){return w.push({dimensions:a.dimensions,embed:a.embed,field:i,metadata:a.metadata,metric:a.metric,model:a.model,name:a.index}),l}};return l},Ie=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,model:e.model,select:e.source.select,table:e.source.table}),Ne=(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}},ve=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:H(e,t.sortBy),where:t.where}),I=e=>({...e,extend(t){return I(z(e,t))},jurisdiction(t,n){return I(e)},rls(t){return I({...e,rlsMode:t})}}),ne=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},re=(e,t,n)=>{for(const r of Object.values(t)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);o.aggregateIndexes.push(r)}for(const r of Object.values(n)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);o.rankIndexes.push(r)}},ae=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},oe=(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=ae(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).`)},ie=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.`);oe(t,r)}}},se=["_commitSeq","_creationTime","_id"],q="_commitSeq",de=new Set(se),p=(e,t,n,r)=>{if(!(de.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`)},S=(e,t,n,r)=>{const o=new Set;for(const d of n){if(o.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);o.add(d.name),r(d)}},Q=e=>{for(const[t,n]of Object.entries(e))S(t,"index",n.indexes,r=>{for(const o of r.fields)p(t,r.name,o,n)}),S(t,"rank index",n.rankIndexes,r=>{for(const o of r.sortBy)p(t,r.name,o.field,n);for(const o of r.partitionBy??[])p(t,r.name,o,n)}),S(t,"geo index",n.geoIndexes,r=>{p(t,r.name,r.field,n)})},T=(e,t,n)=>{if(e.length===0)return;const r={};for(const o of e)r[t(o)]=n(o);return r},le=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},ke=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const o=T(r.geoIndexes,c=>c.name,c=>[c.field]),d=T(r.indexes,c=>c.name,c=>c.fields),u=T(r.rankIndexes,c=>c.name,le);(o||d||u)&&(t[n]={...o?{geo:o}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ce=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const o=[[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(o!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${o}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},ue=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,o]of Object.entries(n.shape))if(K(o)==="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.`)}},he=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},fe=e=>{for(const[t,n]of Object.entries(e))if(n.ttlPolicy!==void 0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${W(t)}`)},U=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,o])=>o.vectorIndexes.map(d=>[r,d.name])),...Object.entries(t).map(([r,o])=>[o.table,r])];for(const[r,o]of n)if(e[r]?.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${Z(r,o)}`)},me=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(q))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${q}", 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.`)}},V=e=>{me(e),he(e),ue(e),fe(e),ce(e)},Ee=(e,t={},n={},r={})=>(ne(e),re(e,n,r),ie(e),V(e),U(e,t),Q(e),I({tables:e,vectorIndexes:t})),N=(e,t)=>`${e}_${t}`,$=(e,t,n)=>n.has(e)?N(t,e):e,be=(e,t,n,r)=>{const o=N(t,r),d=m=>m===""?o:$(m,t,n),u={};for(const[m,w]of Object.entries(e.relationMap))u[m]={...w,table:$(w.table,t,n)};const c=e.aggregateIndexes.map(m=>({...m,on:d(m.on)})),f=e.rankIndexes.map(m=>({...m,on:d(m.on)}));return{...e,aggregateIndexes:c,rankIndexes:f,relationMap:u}},Se=(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}:{}}},ge=((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}:{}}}),Te=(e,t)=>({...ge(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),z=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),o={...e.tables};for(const[u,c]of Object.entries(t.tables)){const f=N(n,u);if(Object.hasOwn(o,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`);o[f]=be(c,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,c]of Object.entries(t.vectorIndexes)){const f=N(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]={...c,table:$(c.table,n,r)}}return Q(o),V(o),U(o,d),{rlsMode:e.rlsMode,tables:o,vectorIndexes:d}},$e=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=z(n,r.extension));return n},Le=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return X(t)};export{Te as a,ge as b,Le as c,Ne as d,ve as e,Ee as f,Se as g,pe as h,Ie as i,ke as j,$e as k,Q as l,z as m,V as n,U as v};
|