@lunora/server 1.0.0-alpha.193 → 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/data-model.d.mts +165 -14
- package/dist/data-model.d.ts +165 -14
- package/dist/in-process.mjs +1 -1
- package/dist/index.d.mts +100 -12
- package/dist/index.d.ts +100 -12
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-DITNUhX1.mjs → ACTION_CACHE_DEFAULT_TTL_MS-BFmhdKJG.mjs} +1 -1
- package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-BYeHnULU.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-BeS7G0yM.mjs} +1 -1
- package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-Bvno49rr.mjs → PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs} +1 -1
- package/dist/packem_shared/{assertShapesDeclareReadPolicies-CUB_PC20.mjs → assertShapesDeclareReadPolicies-isd_Yupt.mjs} +1 -1
- package/dist/packem_shared/bindOrm-BHq_oUP2.mjs +1 -0
- package/dist/packem_shared/{composePluginMiddleware-bf3t7KZi.mjs → composePluginMiddleware-ZtDIkbvJ.mjs} +1 -1
- package/dist/packem_shared/{defineAggregateIndex--ttNAY7M.mjs → defineAggregateIndex-DF8NiKHr.mjs} +1 -1
- package/dist/packem_shared/{defineShape-raxlSVvO.mjs → defineShape-CX9Xs8AY.mjs} +1 -1
- package/dist/packem_shared/mask-BdULkLAu.mjs +1 -0
- package/dist/packem_shared/middleware-DbhB1jRk.mjs +1 -0
- package/dist/packem_shared/plugin-Bm9wIpiI.mjs +1 -0
- package/dist/packem_shared/rls-B3xf3YrN.mjs +1 -0
- package/dist/packem_shared/{storageRules-BQx91H4g.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-D_hFUjmr.mjs +0 -1
- package/dist/packem_shared/mask-0D6SL3i5.mjs +0 -1
- package/dist/packem_shared/middleware-DAVx_tP1.mjs +0 -1
- package/dist/packem_shared/plugin-xbEqjwqP.mjs +0 -1
- package/dist/packem_shared/rls-CpSeGhdp.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap
|
|
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';
|
|
7
7
|
import { Context, Hono } from 'hono';
|
|
8
|
-
import { WhereOperators, QueryArgs as QueryArgs$2 } from "./data-model.mjs";
|
|
8
|
+
import { WhereOperators, QueryArgs as QueryArgs$2, QueryPlan } from "./data-model.mjs";
|
|
9
9
|
import { W as WhereInput, a as Policy, b as RlsOptions, c as Permission, R as Role, T as TypedDefinePolicyInput, D as DefinePolicyInput } from "./packem_shared/types.d-B7FLdYUD.mjs";
|
|
10
10
|
export type { d as PolicyContext, e as PolicyDecision, f as PolicyDecisionOf, P as PolicyOperation } from "./packem_shared/types.d-B7FLdYUD.mjs";
|
|
11
11
|
export { type CronJob, type CronJobsBuilder, type CronScheduleKind, type DailySchedule, type IntervalSchedule, type MonthlySchedule, type WeeklySchedule, cronJobs } from '@lunora/scheduler';
|
|
@@ -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;
|
|
@@ -849,6 +862,27 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
|
|
|
849
862
|
* `external_source_on_global` rejects combining `.source()` with `.global()`.
|
|
850
863
|
*/
|
|
851
864
|
source: (definition: ExternalSourceDefinition) => TableBuilder<Shape>;
|
|
865
|
+
/**
|
|
866
|
+
* Track when a row last changed. Adds an epoch-millisecond column
|
|
867
|
+
* (`options.field`, default `updatedAt`) that is stamped on insert and
|
|
868
|
+
* restamped on every update (any `patch` or `replace`, including a soft delete
|
|
869
|
+
* and `restore()`) unless the write sets it explicitly. Shorthand for
|
|
870
|
+
* `v.timestamp().defaultNow().$onUpdateFn(() => Date.now())`. Creation time is
|
|
871
|
+
* already on every row as `_creationTime`.
|
|
872
|
+
*
|
|
873
|
+
* A column of the same name that you declare yourself is kept only if it already
|
|
874
|
+
* recomputes on update (`$onUpdateFn`); otherwise this throws, since a plain
|
|
875
|
+
* column of that name would make the call do nothing. It also throws when called
|
|
876
|
+
* twice, or on the field `.softDelete()` uses.
|
|
877
|
+
*
|
|
878
|
+
* Call it **before** `.index()` / `.ttl()` to reference the column there
|
|
879
|
+
* (`.timestamps().index("by_updated", ["updatedAt"])`): the chain's types only
|
|
880
|
+
* know the columns added so far. Rows written before the column existed read back
|
|
881
|
+
* without it until their next write.
|
|
882
|
+
*/
|
|
883
|
+
timestamps: <Field extends string = "updatedAt">(options?: {
|
|
884
|
+
field?: Field;
|
|
885
|
+
}) => TableBuilder<string extends Field ? Shape : Field extends keyof Shape ? Shape : Record<Field, ColumnValidator<number, number | undefined>> & Shape>;
|
|
852
886
|
/** Declare named lifecycle triggers fired inline within the write path. */
|
|
853
887
|
triggers: (build: (t: TriggerBuilder<Shape>) => Record<string, TriggerDefinition>) => TableBuilder<Shape>;
|
|
854
888
|
/**
|
|
@@ -1582,6 +1616,40 @@ interface EnvAccessor<S extends EnvShape> {
|
|
|
1582
1616
|
* invalid — lazily on first access of that key, or eagerly via `config.parse(env)`.
|
|
1583
1617
|
*/
|
|
1584
1618
|
declare const defineEnv: <S extends EnvShape>(shape: S) => EnvAccessor<S>;
|
|
1619
|
+
/**
|
|
1620
|
+
* The slice of `@lunora/shard-engine`'s `RelationWriteInfo` this reads. Declared here rather than imported so the
|
|
1621
|
+
* facade's public types do not drag `@lunora/shard-engine` into the declarations of every package built on them.
|
|
1622
|
+
*/
|
|
1623
|
+
interface RelationWriteBaseLike {
|
|
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 {
|
|
1631
|
+
readonly field: string;
|
|
1632
|
+
readonly kind: "many" | "one";
|
|
1633
|
+
readonly nullable: boolean;
|
|
1634
|
+
readonly references: string;
|
|
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
|
+
};
|
|
1650
|
+
}
|
|
1651
|
+
type RelationWriteInfoLike = KeyedRelationWriteInfoLike | ThroughRelationWriteInfoLike;
|
|
1652
|
+
type RelationWriteInfosLike = Readonly<Record<string, RelationWriteInfoLike>>;
|
|
1585
1653
|
/**
|
|
1586
1654
|
* Minimal structural writer the facade binds over. Declared with **method**
|
|
1587
1655
|
* syntax (not arrow properties) so a more-specifically-typed writer — both
|
|
@@ -1605,6 +1673,7 @@ interface FacadeWriterLike {
|
|
|
1605
1673
|
}): Promise<{
|
|
1606
1674
|
deleted: number;
|
|
1607
1675
|
}>;
|
|
1676
|
+
explain(tableName: string, args?: unknown): Promise<unknown>;
|
|
1608
1677
|
findFirst(tableName: string, args?: unknown): Promise<unknown>;
|
|
1609
1678
|
findFirstOrThrow(tableName: string, args?: unknown): Promise<unknown>;
|
|
1610
1679
|
findMany(tableName: string, args?: unknown): Promise<unknown>;
|
|
@@ -1638,6 +1707,8 @@ interface FacadeWriterLike {
|
|
|
1638
1707
|
};
|
|
1639
1708
|
rank(tableName: string, indexName: string, options: unknown): Promise<unknown>;
|
|
1640
1709
|
rankPage(tableName: string, indexName: string, options?: unknown): Promise<unknown>;
|
|
1710
|
+
/** Per-relation facts for nested relation writes, published by the engine's writer; absent on a writer that declares none. */
|
|
1711
|
+
readonly relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
|
|
1641
1712
|
replace(id: string, document: Record<string, unknown>, expectedTable?: string): Promise<void>;
|
|
1642
1713
|
restore?(id: string, expectedTable?: string): Promise<void>;
|
|
1643
1714
|
}
|
|
@@ -1661,6 +1732,8 @@ interface FacadeEntry {
|
|
|
1661
1732
|
};
|
|
1662
1733
|
/** `true` when at least one row matches `where` (or any row exists when omitted). Honors RLS like `findFirst`. */
|
|
1663
1734
|
exists: (where?: unknown) => Promise<boolean>;
|
|
1735
|
+
/** Describe how `findMany(args)` would run: its SQL, parameters and the database's plan. */
|
|
1736
|
+
explain: (args?: unknown) => Promise<unknown>;
|
|
1664
1737
|
findFirst: (args?: unknown) => Promise<unknown>;
|
|
1665
1738
|
findFirstOrThrow: (args?: unknown) => Promise<unknown>;
|
|
1666
1739
|
findMany: (args?: unknown) => Promise<unknown>;
|
|
@@ -2368,6 +2441,15 @@ interface ShardRankPageResultLike {
|
|
|
2368
2441
|
hasMore: boolean;
|
|
2369
2442
|
rows: ReadonlyArray<RankPageRowLike>;
|
|
2370
2443
|
}
|
|
2444
|
+
/**
|
|
2445
|
+
* A post-image verdict handed to the store, which takes it on the row it reads. Structural mirror of
|
|
2446
|
+
* `@lunora/shard-engine`'s `PatchVerifier`/`PatchWriteOptions`, declared here because a `.d.ts` that names a
|
|
2447
|
+
* shard-engine type would have to hoist it (see the note at the top of this file on the other mirrors).
|
|
2448
|
+
*/
|
|
2449
|
+
type PatchVerifier = (previous: Record<string, unknown>, next: Record<string, unknown>) => boolean;
|
|
2450
|
+
interface PatchWriteOptions {
|
|
2451
|
+
verify?: PatchVerifier;
|
|
2452
|
+
}
|
|
2371
2453
|
/**
|
|
2372
2454
|
* Structural mirror of `@lunora/do`'s `QueryArgs` and `CountArgs`. The
|
|
2373
2455
|
* runtime ORM in `@lunora/do`/`@lunora/d1` reads `baseWhere` /
|
|
@@ -2521,6 +2603,8 @@ interface DatabaseWriterLike {
|
|
|
2521
2603
|
* wrapped is `@lunora/do`'s `createShardCtxDb`, which always implements it.
|
|
2522
2604
|
*/
|
|
2523
2605
|
aggregate: (tableName: string, options: AggregateArgs$1) => Promise<null | number>;
|
|
2606
|
+
/** Update-policy check on row `id` with no write; see `@lunora/shard-engine`'s `DatabaseWriterLike.assertPatchAllowed`. */
|
|
2607
|
+
assertPatchAllowed?: (id: string, expectedTable?: string) => Promise<void>;
|
|
2524
2608
|
count: (tableName: string, whereOrArgs?: CountArgs | WhereInput) => Promise<number>;
|
|
2525
2609
|
delete: (id: string, expectedTable?: string, options?: {
|
|
2526
2610
|
hard?: boolean;
|
|
@@ -2542,6 +2626,7 @@ interface DatabaseWriterLike {
|
|
|
2542
2626
|
}) => Promise<{
|
|
2543
2627
|
deleted: number;
|
|
2544
2628
|
}>;
|
|
2629
|
+
explain: (tableName: string, args?: QueryArgs$1) => Promise<QueryPlan>;
|
|
2545
2630
|
findFirst: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown> | null>;
|
|
2546
2631
|
findFirstOrThrow: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown>>;
|
|
2547
2632
|
findMany: (tableName: string, args?: QueryArgs$1) => Promise<QueryPage$1>;
|
|
@@ -2578,10 +2663,11 @@ interface DatabaseWriterLike {
|
|
|
2578
2663
|
row: Record<string, unknown>;
|
|
2579
2664
|
tableName: string;
|
|
2580
2665
|
}>;
|
|
2581
|
-
patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
2666
|
+
patch: (id: string, patch: Record<string, unknown>, expectedTable?: string, options?: PatchWriteOptions) => Promise<void>;
|
|
2582
2667
|
/** Conditional patch. Optional: a writer without an atomic conditional write omits it, and the wrapper refuses. */
|
|
2583
2668
|
patchIf?: (tableName: string, id: string, args: {
|
|
2584
2669
|
patch: Record<string, unknown>;
|
|
2670
|
+
verify?: PatchVerifier;
|
|
2585
2671
|
where: WhereInput;
|
|
2586
2672
|
}) => Promise<{
|
|
2587
2673
|
applied: boolean;
|
|
@@ -2891,6 +2977,7 @@ interface MaskDatabase {
|
|
|
2891
2977
|
}) => Promise<{
|
|
2892
2978
|
deleted: number;
|
|
2893
2979
|
}>;
|
|
2980
|
+
explain: (tableName: string, args?: QueryArgs) => Promise<QueryPlan>;
|
|
2894
2981
|
findFirst: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown> | null>;
|
|
2895
2982
|
findFirstOrThrow: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown>>;
|
|
2896
2983
|
findMany: (tableName: string, args?: QueryArgs) => Promise<QueryPage>;
|
|
@@ -2960,6 +3047,7 @@ interface MaskDatabase {
|
|
|
2960
3047
|
document: Record<string, unknown>;
|
|
2961
3048
|
}[];
|
|
2962
3049
|
}>;
|
|
3050
|
+
relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
|
|
2963
3051
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
2964
3052
|
}
|
|
2965
3053
|
interface MaskContextIn {
|
|
@@ -3851,4 +3939,4 @@ type RegisteredWhisperAuthorizer = RegisteredFunction<Record<string, never>, boo
|
|
|
3851
3939
|
*/
|
|
3852
3940
|
declare const onWhisper: (handler: WhisperAuthorizeHandler) => RegisteredWhisperAuthorizer;
|
|
3853
3941
|
declare const VERSION = "0.0.0";
|
|
3854
|
-
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,11 +1,11 @@
|
|
|
1
|
-
import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap
|
|
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';
|
|
7
7
|
import { Context, Hono } from 'hono';
|
|
8
|
-
import { WhereOperators, QueryArgs as QueryArgs$2 } from "./data-model.js";
|
|
8
|
+
import { WhereOperators, QueryArgs as QueryArgs$2, QueryPlan } from "./data-model.js";
|
|
9
9
|
import { W as WhereInput, a as Policy, b as RlsOptions, c as Permission, R as Role, T as TypedDefinePolicyInput, D as DefinePolicyInput } from "./packem_shared/types.d-BCtjbIzl.js";
|
|
10
10
|
export type { d as PolicyContext, e as PolicyDecision, f as PolicyDecisionOf, P as PolicyOperation } from "./packem_shared/types.d-BCtjbIzl.js";
|
|
11
11
|
export { type CronJob, type CronJobsBuilder, type CronScheduleKind, type DailySchedule, type IntervalSchedule, type MonthlySchedule, type WeeklySchedule, cronJobs } from '@lunora/scheduler';
|
|
@@ -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;
|
|
@@ -849,6 +862,27 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
|
|
|
849
862
|
* `external_source_on_global` rejects combining `.source()` with `.global()`.
|
|
850
863
|
*/
|
|
851
864
|
source: (definition: ExternalSourceDefinition) => TableBuilder<Shape>;
|
|
865
|
+
/**
|
|
866
|
+
* Track when a row last changed. Adds an epoch-millisecond column
|
|
867
|
+
* (`options.field`, default `updatedAt`) that is stamped on insert and
|
|
868
|
+
* restamped on every update (any `patch` or `replace`, including a soft delete
|
|
869
|
+
* and `restore()`) unless the write sets it explicitly. Shorthand for
|
|
870
|
+
* `v.timestamp().defaultNow().$onUpdateFn(() => Date.now())`. Creation time is
|
|
871
|
+
* already on every row as `_creationTime`.
|
|
872
|
+
*
|
|
873
|
+
* A column of the same name that you declare yourself is kept only if it already
|
|
874
|
+
* recomputes on update (`$onUpdateFn`); otherwise this throws, since a plain
|
|
875
|
+
* column of that name would make the call do nothing. It also throws when called
|
|
876
|
+
* twice, or on the field `.softDelete()` uses.
|
|
877
|
+
*
|
|
878
|
+
* Call it **before** `.index()` / `.ttl()` to reference the column there
|
|
879
|
+
* (`.timestamps().index("by_updated", ["updatedAt"])`): the chain's types only
|
|
880
|
+
* know the columns added so far. Rows written before the column existed read back
|
|
881
|
+
* without it until their next write.
|
|
882
|
+
*/
|
|
883
|
+
timestamps: <Field extends string = "updatedAt">(options?: {
|
|
884
|
+
field?: Field;
|
|
885
|
+
}) => TableBuilder<string extends Field ? Shape : Field extends keyof Shape ? Shape : Record<Field, ColumnValidator<number, number | undefined>> & Shape>;
|
|
852
886
|
/** Declare named lifecycle triggers fired inline within the write path. */
|
|
853
887
|
triggers: (build: (t: TriggerBuilder<Shape>) => Record<string, TriggerDefinition>) => TableBuilder<Shape>;
|
|
854
888
|
/**
|
|
@@ -1582,6 +1616,40 @@ interface EnvAccessor<S extends EnvShape> {
|
|
|
1582
1616
|
* invalid — lazily on first access of that key, or eagerly via `config.parse(env)`.
|
|
1583
1617
|
*/
|
|
1584
1618
|
declare const defineEnv: <S extends EnvShape>(shape: S) => EnvAccessor<S>;
|
|
1619
|
+
/**
|
|
1620
|
+
* The slice of `@lunora/shard-engine`'s `RelationWriteInfo` this reads. Declared here rather than imported so the
|
|
1621
|
+
* facade's public types do not drag `@lunora/shard-engine` into the declarations of every package built on them.
|
|
1622
|
+
*/
|
|
1623
|
+
interface RelationWriteBaseLike {
|
|
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 {
|
|
1631
|
+
readonly field: string;
|
|
1632
|
+
readonly kind: "many" | "one";
|
|
1633
|
+
readonly nullable: boolean;
|
|
1634
|
+
readonly references: string;
|
|
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
|
+
};
|
|
1650
|
+
}
|
|
1651
|
+
type RelationWriteInfoLike = KeyedRelationWriteInfoLike | ThroughRelationWriteInfoLike;
|
|
1652
|
+
type RelationWriteInfosLike = Readonly<Record<string, RelationWriteInfoLike>>;
|
|
1585
1653
|
/**
|
|
1586
1654
|
* Minimal structural writer the facade binds over. Declared with **method**
|
|
1587
1655
|
* syntax (not arrow properties) so a more-specifically-typed writer — both
|
|
@@ -1605,6 +1673,7 @@ interface FacadeWriterLike {
|
|
|
1605
1673
|
}): Promise<{
|
|
1606
1674
|
deleted: number;
|
|
1607
1675
|
}>;
|
|
1676
|
+
explain(tableName: string, args?: unknown): Promise<unknown>;
|
|
1608
1677
|
findFirst(tableName: string, args?: unknown): Promise<unknown>;
|
|
1609
1678
|
findFirstOrThrow(tableName: string, args?: unknown): Promise<unknown>;
|
|
1610
1679
|
findMany(tableName: string, args?: unknown): Promise<unknown>;
|
|
@@ -1638,6 +1707,8 @@ interface FacadeWriterLike {
|
|
|
1638
1707
|
};
|
|
1639
1708
|
rank(tableName: string, indexName: string, options: unknown): Promise<unknown>;
|
|
1640
1709
|
rankPage(tableName: string, indexName: string, options?: unknown): Promise<unknown>;
|
|
1710
|
+
/** Per-relation facts for nested relation writes, published by the engine's writer; absent on a writer that declares none. */
|
|
1711
|
+
readonly relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
|
|
1641
1712
|
replace(id: string, document: Record<string, unknown>, expectedTable?: string): Promise<void>;
|
|
1642
1713
|
restore?(id: string, expectedTable?: string): Promise<void>;
|
|
1643
1714
|
}
|
|
@@ -1661,6 +1732,8 @@ interface FacadeEntry {
|
|
|
1661
1732
|
};
|
|
1662
1733
|
/** `true` when at least one row matches `where` (or any row exists when omitted). Honors RLS like `findFirst`. */
|
|
1663
1734
|
exists: (where?: unknown) => Promise<boolean>;
|
|
1735
|
+
/** Describe how `findMany(args)` would run: its SQL, parameters and the database's plan. */
|
|
1736
|
+
explain: (args?: unknown) => Promise<unknown>;
|
|
1664
1737
|
findFirst: (args?: unknown) => Promise<unknown>;
|
|
1665
1738
|
findFirstOrThrow: (args?: unknown) => Promise<unknown>;
|
|
1666
1739
|
findMany: (args?: unknown) => Promise<unknown>;
|
|
@@ -2368,6 +2441,15 @@ interface ShardRankPageResultLike {
|
|
|
2368
2441
|
hasMore: boolean;
|
|
2369
2442
|
rows: ReadonlyArray<RankPageRowLike>;
|
|
2370
2443
|
}
|
|
2444
|
+
/**
|
|
2445
|
+
* A post-image verdict handed to the store, which takes it on the row it reads. Structural mirror of
|
|
2446
|
+
* `@lunora/shard-engine`'s `PatchVerifier`/`PatchWriteOptions`, declared here because a `.d.ts` that names a
|
|
2447
|
+
* shard-engine type would have to hoist it (see the note at the top of this file on the other mirrors).
|
|
2448
|
+
*/
|
|
2449
|
+
type PatchVerifier = (previous: Record<string, unknown>, next: Record<string, unknown>) => boolean;
|
|
2450
|
+
interface PatchWriteOptions {
|
|
2451
|
+
verify?: PatchVerifier;
|
|
2452
|
+
}
|
|
2371
2453
|
/**
|
|
2372
2454
|
* Structural mirror of `@lunora/do`'s `QueryArgs` and `CountArgs`. The
|
|
2373
2455
|
* runtime ORM in `@lunora/do`/`@lunora/d1` reads `baseWhere` /
|
|
@@ -2521,6 +2603,8 @@ interface DatabaseWriterLike {
|
|
|
2521
2603
|
* wrapped is `@lunora/do`'s `createShardCtxDb`, which always implements it.
|
|
2522
2604
|
*/
|
|
2523
2605
|
aggregate: (tableName: string, options: AggregateArgs$1) => Promise<null | number>;
|
|
2606
|
+
/** Update-policy check on row `id` with no write; see `@lunora/shard-engine`'s `DatabaseWriterLike.assertPatchAllowed`. */
|
|
2607
|
+
assertPatchAllowed?: (id: string, expectedTable?: string) => Promise<void>;
|
|
2524
2608
|
count: (tableName: string, whereOrArgs?: CountArgs | WhereInput) => Promise<number>;
|
|
2525
2609
|
delete: (id: string, expectedTable?: string, options?: {
|
|
2526
2610
|
hard?: boolean;
|
|
@@ -2542,6 +2626,7 @@ interface DatabaseWriterLike {
|
|
|
2542
2626
|
}) => Promise<{
|
|
2543
2627
|
deleted: number;
|
|
2544
2628
|
}>;
|
|
2629
|
+
explain: (tableName: string, args?: QueryArgs$1) => Promise<QueryPlan>;
|
|
2545
2630
|
findFirst: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown> | null>;
|
|
2546
2631
|
findFirstOrThrow: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown>>;
|
|
2547
2632
|
findMany: (tableName: string, args?: QueryArgs$1) => Promise<QueryPage$1>;
|
|
@@ -2578,10 +2663,11 @@ interface DatabaseWriterLike {
|
|
|
2578
2663
|
row: Record<string, unknown>;
|
|
2579
2664
|
tableName: string;
|
|
2580
2665
|
}>;
|
|
2581
|
-
patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
2666
|
+
patch: (id: string, patch: Record<string, unknown>, expectedTable?: string, options?: PatchWriteOptions) => Promise<void>;
|
|
2582
2667
|
/** Conditional patch. Optional: a writer without an atomic conditional write omits it, and the wrapper refuses. */
|
|
2583
2668
|
patchIf?: (tableName: string, id: string, args: {
|
|
2584
2669
|
patch: Record<string, unknown>;
|
|
2670
|
+
verify?: PatchVerifier;
|
|
2585
2671
|
where: WhereInput;
|
|
2586
2672
|
}) => Promise<{
|
|
2587
2673
|
applied: boolean;
|
|
@@ -2891,6 +2977,7 @@ interface MaskDatabase {
|
|
|
2891
2977
|
}) => Promise<{
|
|
2892
2978
|
deleted: number;
|
|
2893
2979
|
}>;
|
|
2980
|
+
explain: (tableName: string, args?: QueryArgs) => Promise<QueryPlan>;
|
|
2894
2981
|
findFirst: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown> | null>;
|
|
2895
2982
|
findFirstOrThrow: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown>>;
|
|
2896
2983
|
findMany: (tableName: string, args?: QueryArgs) => Promise<QueryPage>;
|
|
@@ -2960,6 +3047,7 @@ interface MaskDatabase {
|
|
|
2960
3047
|
document: Record<string, unknown>;
|
|
2961
3048
|
}[];
|
|
2962
3049
|
}>;
|
|
3050
|
+
relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
|
|
2963
3051
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
2964
3052
|
}
|
|
2965
3053
|
interface MaskContextIn {
|
|
@@ -3851,4 +3939,4 @@ type RegisteredWhisperAuthorizer = RegisteredFunction<Record<string, never>, boo
|
|
|
3851
3939
|
*/
|
|
3852
3940
|
declare const onWhisper: (handler: WhisperAuthorizeHandler) => RegisteredWhisperAuthorizer;
|
|
3853
3941
|
declare const VERSION = "0.0.0";
|
|
3854
|
-
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,
|
|
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};
|