@lunora/do 1.0.0-alpha.43 → 1.0.0-alpha.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +55 -1
- package/dist/index.d.ts +55 -1
- package/dist/index.mjs +1 -44
- package/dist/packem_shared/ADMIN_FUNCTIONS-PxZ8Lr9e.mjs +1 -0
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs +1 -0
- package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs +22 -0
- package/dist/packem_shared/CDC_LOG_TABLE-E_J5LPoK.mjs +8 -0
- package/dist/packem_shared/ConflictError-C8GtJmjS.mjs +1 -0
- package/dist/packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs +1 -0
- package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs +56 -0
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-CWAm_oYY.mjs +1 -0
- package/dist/packem_shared/LogBuffer-bIvCelI-.mjs +1 -0
- package/dist/packem_shared/MAIL_RETENTION-KmozO2NQ.mjs +18 -0
- package/dist/packem_shared/MAX_SQL_ROWS-Bdu25ASB.mjs +2 -0
- package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-Ch6OW6_3.mjs +1 -0
- package/dist/packem_shared/NotFoundError-J3tjf4Uo.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-BcP6GOem.mjs +1 -0
- package/dist/packem_shared/RANK_TIEBREAK-DtX8zQyc.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs +1 -0
- package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-CP5wvJOW.mjs +101 -0
- package/dist/packem_shared/ReactiveCache-1_9Rs7J_.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +1 -0
- package/dist/packem_shared/SESSION_DO_TTL_DEFAULT-GvBy_DBz.mjs +1 -0
- package/dist/packem_shared/SHARD_REGISTRY_DO_NAME-Caa0fR4N.mjs +1 -0
- package/dist/packem_shared/aggregateTableName-G-eXyjcz.mjs +1 -0
- package/dist/packem_shared/applyOnDelete-BvQN7pDL.mjs +1 -0
- package/dist/packem_shared/applySelect-Bq2KOrkL.mjs +1 -0
- package/dist/packem_shared/armRestore-BNzdvQ_o.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-BAQ3Fwwh.mjs +1 -0
- package/dist/packem_shared/buildFtsMatch-CV0Z7PWv.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-BLcfs4QW.mjs +1 -0
- package/dist/packem_shared/constant-time-equal-BVG05Guz.mjs +1 -0
- package/dist/packem_shared/context-telemetry-8eigmiNQ.mjs +1 -0
- package/dist/packem_shared/createMetrics-CyjLFXtA.mjs +1 -0
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +1 -0
- package/dist/packem_shared/ctx-db-idempotency-wiVoGnpQ.mjs +19 -0
- package/dist/packem_shared/ctx-db-shapes-DzX_H5q8.mjs +1 -0
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +1 -0
- package/dist/packem_shared/do-exec-BLe9lLrN.mjs +1 -0
- package/dist/packem_shared/do-sql-BYIQTG3z.mjs +1 -0
- package/dist/packem_shared/exportShardRows-kt42wijd.mjs +1 -0
- package/dist/packem_shared/hasTrigger-_rexbWMO.mjs +1 -0
- package/dist/packem_shared/isSoftDeleted-BvhQov04.mjs +9 -0
- package/dist/packem_shared/json-response-wrh9TBPw.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-BFmT9gsw.mjs +1 -0
- package/dist/packem_shared/renderSql-B5lF5Jd9.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-bxOHpfID.mjs +5 -0
- package/dist/packem_shared/security-audit-BKUOgE0x.mjs +1 -0
- package/dist/packem_shared/selectExpiredIds-BGVP3d8-.mjs +1 -0
- package/dist/packem_shared/serialize-sql-DiRzL7A4.mjs +1 -0
- package/dist/packem_shared/serveRelationFanout-Ct5D2Tbk.mjs +1 -0
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +1 -0
- package/dist/packem_shared/stableWireKey-YEHLaX6X.mjs +1 -0
- package/dist/packem_shared/subscriptionListDeltas-Bs69JbA8.mjs +1 -0
- package/dist/packem_shared/wire-codec-Ctnni0h6.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-CnZkbXH_.mjs +0 -374
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CQsu2Xga.mjs +0 -56
- package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-CiHHYeJi.mjs +0 -84
- package/dist/packem_shared/CDC_LOG_TABLE-uwOJxJJZ.mjs +0 -107
- package/dist/packem_shared/ConflictError-CLoq37xH.mjs +0 -12
- package/dist/packem_shared/CountRlsUnsupportedError-BGxj0pgS.mjs +0 -133
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CYwBpyTr.mjs +0 -245
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BEan1CRD.mjs +0 -211
- package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-UDNVD7FS.mjs +0 -248
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-BWnsNmpP.mjs +0 -114
- package/dist/packem_shared/LogBuffer-B_Ezju_N.mjs +0 -37
- package/dist/packem_shared/MAIL_RETENTION-CPpgl-dX.mjs +0 -104
- package/dist/packem_shared/MAX_SQL_ROWS-iFAA8FbD.mjs +0 -61
- package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-CCAvoFlr.mjs +0 -1
- package/dist/packem_shared/NotFoundError-C70b9hLw.mjs +0 -9
- package/dist/packem_shared/NotUniqueError-DbtlWwcG.mjs +0 -2031
- package/dist/packem_shared/RANK_TIEBREAK-CXhdcA1o.mjs +0 -91
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DTvHvRzY.mjs +0 -141
- package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-B_zt4RQE.mjs +0 -7676
- package/dist/packem_shared/ReactiveCache-DnSvbjil.mjs +0 -233
- package/dist/packem_shared/SCAN_DEP-DLJF8dsj.mjs +0 -19
- package/dist/packem_shared/SESSION_DO_TTL_DEFAULT-BnSKgVO4.mjs +0 -169
- package/dist/packem_shared/SHARD_REGISTRY_DO_NAME-D99roc-r.mjs +0 -144
- package/dist/packem_shared/aggregateTableName-CxNqY1Sl.mjs +0 -64
- package/dist/packem_shared/applyOnDelete-BXSq3S70.mjs +0 -176
- package/dist/packem_shared/applySelect-WQY8m62C.mjs +0 -103
- package/dist/packem_shared/armRestore-4Px61hHS.mjs +0 -49
- package/dist/packem_shared/backfillAggregateIndexes-BGTwynwh.mjs +0 -81
- package/dist/packem_shared/buildFtsMatch-BLEMawrp.mjs +0 -38
- package/dist/packem_shared/compileWhereSql-DE6yfRcQ.mjs +0 -129
- package/dist/packem_shared/constant-time-equal-BVRWZgES.mjs +0 -12
- package/dist/packem_shared/context-telemetry-CDpyil58.mjs +0 -223
- package/dist/packem_shared/createMetrics-C4I2Yanj.mjs +0 -1
- package/dist/packem_shared/createSystemReader-D12eNH13.mjs +0 -82
- package/dist/packem_shared/ctx-db-idempotency-BdcNpvY4.mjs +0 -108
- package/dist/packem_shared/ctx-db-shapes-DTeFiHYS.mjs +0 -53
- package/dist/packem_shared/diffExternalSource-CovHfdyo.mjs +0 -44
- package/dist/packem_shared/do-exec-5eQy5cEi.mjs +0 -12
- package/dist/packem_shared/do-sql-CGAgiQUz.mjs +0 -88
- package/dist/packem_shared/exportShardRows-Dy3oFZ26.mjs +0 -157
- package/dist/packem_shared/hasTrigger-5N6_Fx0A.mjs +0 -20
- package/dist/packem_shared/isSoftDeleted-CFJmhjFP.mjs +0 -217
- package/dist/packem_shared/json-response-BdbtpOhm.mjs +0 -3
- package/dist/packem_shared/materializeExternalRows-BtEGs1Fv.mjs +0 -45
- package/dist/packem_shared/renderSql-D6eUcn2N.mjs +0 -16
- package/dist/packem_shared/runShardMigrations-BVax6rYu.mjs +0 -120
- package/dist/packem_shared/security-audit-CucgBice.mjs +0 -158
- package/dist/packem_shared/selectExpiredIds-C5W29Upb.mjs +0 -18
- package/dist/packem_shared/serialize-sql-BlRUoiQe.mjs +0 -14
- package/dist/packem_shared/serveRelationFanout-k7HTh3CC.mjs +0 -21
- package/dist/packem_shared/stableStringify-mC40mZts.mjs +0 -40
- package/dist/packem_shared/stableWireKey-DKuXO7T5.mjs +0 -6
- package/dist/packem_shared/subscriptionListDeltas-CT76bYny.mjs +0 -126
- package/dist/packem_shared/wire-codec-CzQc1pvf.mjs +0 -225
package/dist/index.d.mts
CHANGED
|
@@ -1662,6 +1662,21 @@ interface DatabaseWriterLike {
|
|
|
1662
1662
|
* the table.
|
|
1663
1663
|
*/
|
|
1664
1664
|
aggregate: (tableName: string, options: AggregateOptions) => Promise<AggregateResult>;
|
|
1665
|
+
/**
|
|
1666
|
+
* The throwing sibling of `normalizeId`: returns the id when it is
|
|
1667
|
+
* structurally an id, and throws `BAD_REQUEST` otherwise. Pure — it never reads
|
|
1668
|
+
* the database. Same check as `normalizeId` (ids are opaque strings, so empty /
|
|
1669
|
+
* whitespace-bearing / NUL-bearing values are rejected), just non-nullable.
|
|
1670
|
+
*
|
|
1671
|
+
* This is the parse boundary for an id that arrived as a plain `string` (a wire
|
|
1672
|
+
* payload, a mutator's args, a change plan). Without it every such call site
|
|
1673
|
+
* writes `value as Id<"table">`, which asserts rather than checks.
|
|
1674
|
+
*
|
|
1675
|
+
* Optional on the interface (like the batch methods): the DO writer — the only one
|
|
1676
|
+
* ever assigned to `ctx.db` — always implements it, while the `.global()` (D1 /
|
|
1677
|
+
* Hyperdrive) twins that also satisfy this shape structurally do not.
|
|
1678
|
+
*/
|
|
1679
|
+
asId?: (tableName: string, id: string) => string;
|
|
1665
1680
|
/**
|
|
1666
1681
|
* Count rows in `tableName`. Uses a declared `aggregateIndex` when one
|
|
1667
1682
|
* covers the `where` keys (no scan); otherwise scans. Throws
|
|
@@ -1679,6 +1694,22 @@ interface DatabaseWriterLike {
|
|
|
1679
1694
|
delete: (id: string, expectedTable?: string, options?: {
|
|
1680
1695
|
hard?: boolean;
|
|
1681
1696
|
}) => Promise<void>;
|
|
1697
|
+
/**
|
|
1698
|
+
* Delete EVERY row in `tableName`, chunking internally until the table is
|
|
1699
|
+
* empty. Unlike `deleteWhere(tableName, {})` there is no batch cap — the whole
|
|
1700
|
+
* point is a table of unknown size (GDPR erasure, a tenant teardown), where a
|
|
1701
|
+
* `BATCH_LIMIT_EXCEEDED` at row 501 is a bug rather than a safety rail. Every
|
|
1702
|
+
* row still goes through the single-row delete pipeline so triggers, cascades,
|
|
1703
|
+
* companions, CDC, and broadcast stay correct.
|
|
1704
|
+
*
|
|
1705
|
+
* Optional on the interface (like `deleteMany`): the DO writer implements it.
|
|
1706
|
+
*/
|
|
1707
|
+
deleteAll?: (tableName: string, options?: {
|
|
1708
|
+
chunkSize?: number;
|
|
1709
|
+
hard?: boolean;
|
|
1710
|
+
}) => Promise<{
|
|
1711
|
+
deleted: number;
|
|
1712
|
+
}>;
|
|
1682
1713
|
/**
|
|
1683
1714
|
* Delete many rows by id in one call (a loop over `delete()`). The returned
|
|
1684
1715
|
* `deleted` is the number of ids **requested**, not rows actually removed (an
|
|
@@ -1911,6 +1942,26 @@ interface DatabaseWriterLike {
|
|
|
1911
1942
|
* to `ctx.db`, omits it — same pattern as the optional `rankBefore` above.
|
|
1912
1943
|
*/
|
|
1913
1944
|
system?: SystemDatabaseReader;
|
|
1945
|
+
/**
|
|
1946
|
+
* Erase every shard-local table in the schema — the account-deletion /
|
|
1947
|
+
* tenant-teardown primitive. Iterates the non-`.global()` tables and
|
|
1948
|
+
* `deleteAll`s each, returning the per-table counts.
|
|
1949
|
+
*
|
|
1950
|
+
* `.global()` tables are deliberately skipped: their rows live in D1 and are
|
|
1951
|
+
* shared across shards, so "wipe this shard" must not touch them. Pass
|
|
1952
|
+
* `options.tables` to restrict the sweep, or `options.exclude` to spare a table
|
|
1953
|
+
* (e.g. an audit log that must outlive the data).
|
|
1954
|
+
*
|
|
1955
|
+
* Optional on the interface, like the other batch primitives.
|
|
1956
|
+
*/
|
|
1957
|
+
wipeShard?: (options?: {
|
|
1958
|
+
chunkSize?: number;
|
|
1959
|
+
exclude?: ReadonlyArray<string>;
|
|
1960
|
+
tables?: ReadonlyArray<string>;
|
|
1961
|
+
}) => Promise<{
|
|
1962
|
+
deleted: number;
|
|
1963
|
+
tables: Record<string, number>;
|
|
1964
|
+
}>;
|
|
1914
1965
|
}
|
|
1915
1966
|
/**
|
|
1916
1967
|
* Thrown by `.unique()` when more than one row matches. A `LunoraError` subclass
|
|
@@ -4166,11 +4217,14 @@ declare class RlsRequiredError extends LunoraError {
|
|
|
4166
4217
|
readonly table: string;
|
|
4167
4218
|
constructor(table: string);
|
|
4168
4219
|
}
|
|
4169
|
-
/** Minimal schema projection the guard reads: the RLS mode + per-table opt-out. */
|
|
4220
|
+
/** Minimal schema projection the guard reads: the RLS mode + per-table opt-out and shard mode. */
|
|
4170
4221
|
interface GuardableSchema {
|
|
4171
4222
|
readonly rlsMode?: "required";
|
|
4172
4223
|
readonly tables: Record<string, {
|
|
4173
4224
|
readonly isPublic?: boolean;
|
|
4225
|
+
readonly shardMode?: {
|
|
4226
|
+
readonly kind?: string;
|
|
4227
|
+
};
|
|
4174
4228
|
}>;
|
|
4175
4229
|
}
|
|
4176
4230
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -1662,6 +1662,21 @@ interface DatabaseWriterLike {
|
|
|
1662
1662
|
* the table.
|
|
1663
1663
|
*/
|
|
1664
1664
|
aggregate: (tableName: string, options: AggregateOptions) => Promise<AggregateResult>;
|
|
1665
|
+
/**
|
|
1666
|
+
* The throwing sibling of `normalizeId`: returns the id when it is
|
|
1667
|
+
* structurally an id, and throws `BAD_REQUEST` otherwise. Pure — it never reads
|
|
1668
|
+
* the database. Same check as `normalizeId` (ids are opaque strings, so empty /
|
|
1669
|
+
* whitespace-bearing / NUL-bearing values are rejected), just non-nullable.
|
|
1670
|
+
*
|
|
1671
|
+
* This is the parse boundary for an id that arrived as a plain `string` (a wire
|
|
1672
|
+
* payload, a mutator's args, a change plan). Without it every such call site
|
|
1673
|
+
* writes `value as Id<"table">`, which asserts rather than checks.
|
|
1674
|
+
*
|
|
1675
|
+
* Optional on the interface (like the batch methods): the DO writer — the only one
|
|
1676
|
+
* ever assigned to `ctx.db` — always implements it, while the `.global()` (D1 /
|
|
1677
|
+
* Hyperdrive) twins that also satisfy this shape structurally do not.
|
|
1678
|
+
*/
|
|
1679
|
+
asId?: (tableName: string, id: string) => string;
|
|
1665
1680
|
/**
|
|
1666
1681
|
* Count rows in `tableName`. Uses a declared `aggregateIndex` when one
|
|
1667
1682
|
* covers the `where` keys (no scan); otherwise scans. Throws
|
|
@@ -1679,6 +1694,22 @@ interface DatabaseWriterLike {
|
|
|
1679
1694
|
delete: (id: string, expectedTable?: string, options?: {
|
|
1680
1695
|
hard?: boolean;
|
|
1681
1696
|
}) => Promise<void>;
|
|
1697
|
+
/**
|
|
1698
|
+
* Delete EVERY row in `tableName`, chunking internally until the table is
|
|
1699
|
+
* empty. Unlike `deleteWhere(tableName, {})` there is no batch cap — the whole
|
|
1700
|
+
* point is a table of unknown size (GDPR erasure, a tenant teardown), where a
|
|
1701
|
+
* `BATCH_LIMIT_EXCEEDED` at row 501 is a bug rather than a safety rail. Every
|
|
1702
|
+
* row still goes through the single-row delete pipeline so triggers, cascades,
|
|
1703
|
+
* companions, CDC, and broadcast stay correct.
|
|
1704
|
+
*
|
|
1705
|
+
* Optional on the interface (like `deleteMany`): the DO writer implements it.
|
|
1706
|
+
*/
|
|
1707
|
+
deleteAll?: (tableName: string, options?: {
|
|
1708
|
+
chunkSize?: number;
|
|
1709
|
+
hard?: boolean;
|
|
1710
|
+
}) => Promise<{
|
|
1711
|
+
deleted: number;
|
|
1712
|
+
}>;
|
|
1682
1713
|
/**
|
|
1683
1714
|
* Delete many rows by id in one call (a loop over `delete()`). The returned
|
|
1684
1715
|
* `deleted` is the number of ids **requested**, not rows actually removed (an
|
|
@@ -1911,6 +1942,26 @@ interface DatabaseWriterLike {
|
|
|
1911
1942
|
* to `ctx.db`, omits it — same pattern as the optional `rankBefore` above.
|
|
1912
1943
|
*/
|
|
1913
1944
|
system?: SystemDatabaseReader;
|
|
1945
|
+
/**
|
|
1946
|
+
* Erase every shard-local table in the schema — the account-deletion /
|
|
1947
|
+
* tenant-teardown primitive. Iterates the non-`.global()` tables and
|
|
1948
|
+
* `deleteAll`s each, returning the per-table counts.
|
|
1949
|
+
*
|
|
1950
|
+
* `.global()` tables are deliberately skipped: their rows live in D1 and are
|
|
1951
|
+
* shared across shards, so "wipe this shard" must not touch them. Pass
|
|
1952
|
+
* `options.tables` to restrict the sweep, or `options.exclude` to spare a table
|
|
1953
|
+
* (e.g. an audit log that must outlive the data).
|
|
1954
|
+
*
|
|
1955
|
+
* Optional on the interface, like the other batch primitives.
|
|
1956
|
+
*/
|
|
1957
|
+
wipeShard?: (options?: {
|
|
1958
|
+
chunkSize?: number;
|
|
1959
|
+
exclude?: ReadonlyArray<string>;
|
|
1960
|
+
tables?: ReadonlyArray<string>;
|
|
1961
|
+
}) => Promise<{
|
|
1962
|
+
deleted: number;
|
|
1963
|
+
tables: Record<string, number>;
|
|
1964
|
+
}>;
|
|
1914
1965
|
}
|
|
1915
1966
|
/**
|
|
1916
1967
|
* Thrown by `.unique()` when more than one row matches. A `LunoraError` subclass
|
|
@@ -4166,11 +4217,14 @@ declare class RlsRequiredError extends LunoraError {
|
|
|
4166
4217
|
readonly table: string;
|
|
4167
4218
|
constructor(table: string);
|
|
4168
4219
|
}
|
|
4169
|
-
/** Minimal schema projection the guard reads: the RLS mode + per-table opt-out. */
|
|
4220
|
+
/** Minimal schema projection the guard reads: the RLS mode + per-table opt-out and shard mode. */
|
|
4170
4221
|
interface GuardableSchema {
|
|
4171
4222
|
readonly rlsMode?: "required";
|
|
4172
4223
|
readonly tables: Record<string, {
|
|
4173
4224
|
readonly isPublic?: boolean;
|
|
4225
|
+
readonly shardMode?: {
|
|
4226
|
+
readonly kind?: string;
|
|
4227
|
+
};
|
|
4174
4228
|
}>;
|
|
4175
4229
|
}
|
|
4176
4230
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -1,44 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { AGGREGATE_SQL_FUNCTION, aggregateSqlFunction, matchesStaticWhere, normalizeCountArgument, throwingScheduler } from './packem_shared/AGGREGATE_SQL_FUNCTION-CQsu2Xga.mjs';
|
|
3
|
-
export { aggregateTableName, coerceAggregateNumber, encodeAggregateKey, foldAggregateTally, readAggregateValue } from './packem_shared/aggregateTableName-CxNqY1Sl.mjs';
|
|
4
|
-
export { CountRlsUnsupportedError, mergeWhere, planAggregateLookup, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy } from './packem_shared/CountRlsUnsupportedError-BGxj0pgS.mjs';
|
|
5
|
-
export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, ensureAuthMetricsTables, readAuthMetrics, recordAuthEvent } from './packem_shared/AUTH_METRICS_BUCKETS_TABLE-CiHHYeJi.mjs';
|
|
6
|
-
export { c as createMetrics, a as createTracer, d as dispatchRootSpan } from './packem_shared/context-telemetry-CDpyil58.mjs';
|
|
7
|
-
export { NotUniqueError, assertValidClientId, createShardCtxDb, normalizeIdStructurally } from './packem_shared/NotUniqueError-DbtlWwcG.mjs';
|
|
8
|
-
export { DATA_MIGRATION_STATE_TABLE, readMigrationStatus, runDataMigration } from './packem_shared/DATA_MIGRATION_STATE_TABLE-CYwBpyTr.mjs';
|
|
9
|
-
export { SCAN_DEP, createDependencyTracker, depKey } from './packem_shared/SCAN_DEP-DLJF8dsj.mjs';
|
|
10
|
-
export { renderSql } from './packem_shared/renderSql-D6eUcn2N.mjs';
|
|
11
|
-
export { diffExternalSource } from './packem_shared/diffExternalSource-CovHfdyo.mjs';
|
|
12
|
-
export { materializeExternalRows, materializeExternalRowsIncremental, readExternalSourceBaseline, runExternalSourceTick } from './packem_shared/materializeExternalRows-BtEGs1Fv.mjs';
|
|
13
|
-
export { isSoftDeleted, isSourceDue, liftSourceId, pullExternalSourceIncrementalTick, pullExternalSourceTick } from './packem_shared/isSoftDeleted-CFJmhjFP.mjs';
|
|
14
|
-
export { FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_TABLE, ensureFunctionMetricsTables, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetrics, readFunctionMetricsTotals, recordFunctionMetric } from './packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-UDNVD7FS.mjs';
|
|
15
|
-
export { GEO_DEFAULT_PRECISION, boundingBoxGeohashes, coveringGeohashes, encodeGeohash, haversineMeters, pointInBoundingBox } from './packem_shared/GEO_DEFAULT_PRECISION-BWnsNmpP.mjs';
|
|
16
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, FLAGS_FUNCTION_PREFIX, RELATION_FUNCTION_PREFIX, facetColumn, listTables, readTablePage, selectMatchingIds } from './packem_shared/ADMIN_FUNCTIONS-CnZkbXH_.mjs';
|
|
17
|
-
export { LogBuffer } from './packem_shared/LogBuffer-B_Ezju_N.mjs';
|
|
18
|
-
export { MAIL_RETENTION, MAIL_TABLE, clearCapturedMail, ensureMailTable, readCapturedMail, recordCapturedMail } from './packem_shared/MAIL_RETENTION-CPpgl-dX.mjs';
|
|
19
|
-
export { default as NotFoundError } from './packem_shared/NotFoundError-C70b9hLw.mjs';
|
|
20
|
-
export { armRestore, readBookmark } from './packem_shared/armRestore-4Px61hHS.mjs';
|
|
21
|
-
export { applySelect, buildSeekWhere, decodeCursor, encodeCursor, normalizeOrderKeys, softDeleteScope } from './packem_shared/applySelect-WQY8m62C.mjs';
|
|
22
|
-
export { RANK_TIEBREAK, encodePartitionKey, matchesRankStaticWhere, rankTableName, resolveRankPartition, sortColumnName } from './packem_shared/RANK_TIEBREAK-CXhdcA1o.mjs';
|
|
23
|
-
export { ReactiveCache, reactiveCacheKey } from './packem_shared/ReactiveCache-DnSvbjil.mjs';
|
|
24
|
-
export { serveRelationFanout } from './packem_shared/serveRelationFanout-k7HTh3CC.mjs';
|
|
25
|
-
export { DEFAULT_MAX_RELATION_KEYS, assertFlatPredicate, assertShapeShardable, containsRelationPredicate, isRelationPredicate, resolveRelationPredicates } from './packem_shared/DEFAULT_MAX_RELATION_KEYS-BEan1CRD.mjs';
|
|
26
|
-
export { applyOnDelete, fanOutScalarCounts, resolveWith, runRowValidators } from './packem_shared/applyOnDelete-BXSq3S70.mjs';
|
|
27
|
-
export { RLS_UNWRAP_SYMBOL, RlsRequiredError, guardWriter } from './packem_shared/RLS_UNWRAP_SYMBOL-DTvHvRzY.mjs';
|
|
28
|
-
export { buildFtsMatch, ftsTableName, scoreDocument, stringifySearchText, tokenizeSearch } from './packem_shared/buildFtsMatch-BLEMawrp.mjs';
|
|
29
|
-
export { M as MIN_ADMIN_TOKEN_LENGTH, a as MIN_AUTH_SECRET_LENGTH, b as buildSecurityAudit } from './packem_shared/security-audit-CucgBice.mjs';
|
|
30
|
-
export { SESSION_DO_TTL_DEFAULT, SessionDO } from './packem_shared/SESSION_DO_TTL_DEFAULT-BnSKgVO4.mjs';
|
|
31
|
-
export { ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, ShardDO } from './packem_shared/ROOT_DO_SIZE_WARN_BYTES-B_zt4RQE.mjs';
|
|
32
|
-
export { SHARD_REGISTRY_DO_NAME, ShardRegistryDO } from './packem_shared/SHARD_REGISTRY_DO_NAME-D99roc-r.mjs';
|
|
33
|
-
export { MAX_SQL_ROWS, assertReadonly, runReadonlySql } from './packem_shared/MAX_SQL_ROWS-iFAA8FbD.mjs';
|
|
34
|
-
export { createSystemReader } from './packem_shared/createSystemReader-D12eNH13.mjs';
|
|
35
|
-
export { ConflictError } from './packem_shared/ConflictError-CLoq37xH.mjs';
|
|
36
|
-
export { hasTrigger, runTriggers } from './packem_shared/hasTrigger-5N6_Fx0A.mjs';
|
|
37
|
-
export { selectExpiredIds } from './packem_shared/selectExpiredIds-C5W29Upb.mjs';
|
|
38
|
-
export { compileWhereSql } from './packem_shared/compileWhereSql-DE6yfRcQ.mjs';
|
|
39
|
-
export { CDC_LOG_TABLE, applyCdcChanges, readCdcChanges, trimCdcChanges } from './packem_shared/CDC_LOG_TABLE-uwOJxJJZ.mjs';
|
|
40
|
-
export { backfillAggregateIndexes, backfillRankIndexes } from './packem_shared/backfillAggregateIndexes-BGTwynwh.mjs';
|
|
41
|
-
export { runShardMigrations } from './packem_shared/runShardMigrations-BVax6rYu.mjs';
|
|
42
|
-
export { stableStringify } from './packem_shared/stableStringify-mC40mZts.mjs';
|
|
43
|
-
export { stableWireKey } from './packem_shared/stableWireKey-DKuXO7T5.mjs';
|
|
44
|
-
export { subscriptionListDeltas } from './packem_shared/subscriptionListDeltas-CT76bYny.mjs';
|
|
1
|
+
import{exportShardRows as o,exportShardTable as t,importShardRows as a,parseExportShardArgs as n,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as d,matchesStaticWhere as p,normalizeCountArgument as E,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as _,coerceAggregateNumber as u,encodeAggregateKey as x,foldAggregateTally as f,readAggregateValue as I}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as A,mergeWhere as N,planAggregateLookup as g,selectIndexForAggregate as C,selectIndexForCount as M,selectIndexForGroupBy as h}from"./packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs";import{AUTH_METRICS_BUCKETS_TABLE as F,AUTH_METRICS_BUCKET_MS as D,AUTH_METRICS_BUCKET_RETENTION as L,AUTH_METRICS_TABLE as U,ensureAuthMetricsTables as B,readAuthMetrics as b,recordAuthEvent as y}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{c as K,a as G,d as P}from"./packem_shared/context-telemetry-8eigmiNQ.mjs";import{NotUniqueError as v,assertValidClientId as H,createShardCtxDb as w,normalizeIdStructurally as q}from"./packem_shared/NotUniqueError-BcP6GOem.mjs";import{DATA_MIGRATION_STATE_TABLE as X,readMigrationStatus as Y,runDataMigration as V}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Z,createDependencyTracker as j,depKey as J}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{renderSql as ee}from"./packem_shared/renderSql-B5lF5Jd9.mjs";import{diffExternalSource as oe}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{materializeExternalRows as ae,materializeExternalRowsIncremental as ne,readExternalSourceBaseline as ie,runExternalSourceTick as se}from"./packem_shared/materializeExternalRows-BFmT9gsw.mjs";import{isSoftDeleted as ce,isSourceDue as Te,liftSourceId as de,pullExternalSourceIncrementalTick as pe,pullExternalSourceTick as Ee}from"./packem_shared/isSoftDeleted-BvhQov04.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as me,FUNCTION_METRICS_BUCKET_MS as _e,FUNCTION_METRICS_BUCKET_RETENTION as ue,FUNCTION_METRICS_INDEX_TABLE as xe,FUNCTION_METRICS_TABLE as fe,ensureFunctionMetricsTables as Ie,readFunctionMetricBuckets as Re,readFunctionMetricIndexHits as Ae,readFunctionMetrics as Ne,readFunctionMetricsTotals as ge,recordFunctionMetric as Ce}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{GEO_DEFAULT_PRECISION as he,boundingBoxGeohashes as Oe,coveringGeohashes as Fe,encodeGeohash as De,haversineMeters as Le,pointInBoundingBox as Ue}from"./packem_shared/GEO_DEFAULT_PRECISION-CWAm_oYY.mjs";import{ADMIN_FUNCTIONS as be,ADMIN_FUNCTION_PREFIX as ye,FLAGS_FUNCTION_PREFIX as ke,RELATION_FUNCTION_PREFIX as Ke,facetColumn as Ge,listTables as Pe,readTablePage as We,selectMatchingIds as ve}from"./packem_shared/ADMIN_FUNCTIONS-PxZ8Lr9e.mjs";import{LogBuffer as we}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{MAIL_RETENTION as ze,MAIL_TABLE as Xe,clearCapturedMail as Ye,ensureMailTable as Ve,readCapturedMail as Qe,recordCapturedMail as Ze}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{default as Je}from"./packem_shared/NotFoundError-J3tjf4Uo.mjs";import{armRestore as er,readBookmark as rr}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as tr,buildSeekWhere as ar,decodeCursor as nr,encodeCursor as ir,normalizeOrderKeys as sr,softDeleteScope as lr}from"./packem_shared/applySelect-Bq2KOrkL.mjs";import{RANK_TIEBREAK as Tr,encodePartitionKey as dr,matchesRankStaticWhere as pr,rankTableName as Er,resolveRankPartition as Sr,sortColumnName as mr}from"./packem_shared/RANK_TIEBREAK-DtX8zQyc.mjs";import{ReactiveCache as ur,reactiveCacheKey as xr}from"./packem_shared/ReactiveCache-1_9Rs7J_.mjs";import{serveRelationFanout as Ir}from"./packem_shared/serveRelationFanout-Ct5D2Tbk.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ar,assertFlatPredicate as Nr,assertShapeShardable as gr,containsRelationPredicate as Cr,isRelationPredicate as Mr,resolveRelationPredicates as hr}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs";import{applyOnDelete as Fr,fanOutScalarCounts as Dr,resolveWith as Lr,runRowValidators as Ur}from"./packem_shared/applyOnDelete-BvQN7pDL.mjs";import{RLS_UNWRAP_SYMBOL as br,RlsRequiredError as yr,guardWriter as kr}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{buildFtsMatch as Gr,ftsTableName as Pr,scoreDocument as Wr,stringifySearchText as vr,tokenizeSearch as Hr}from"./packem_shared/buildFtsMatch-CV0Z7PWv.mjs";import{o as qr,c as zr,_ as Xr}from"./packem_shared/security-audit-BKUOgE0x.mjs";import{SESSION_DO_TTL_DEFAULT as Vr,SessionDO as Qr}from"./packem_shared/SESSION_DO_TTL_DEFAULT-GvBy_DBz.mjs";import{ROOT_DO_SIZE_WARN_BYTES as jr,ROOT_SHARD_NAME as Jr,ShardDO as $r}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-CP5wvJOW.mjs";import{SHARD_REGISTRY_DO_NAME as ro,ShardRegistryDO as oo}from"./packem_shared/SHARD_REGISTRY_DO_NAME-Caa0fR4N.mjs";import{MAX_SQL_ROWS as ao,assertReadonly as no,runReadonlySql as io}from"./packem_shared/MAX_SQL_ROWS-Bdu25ASB.mjs";import{createSystemReader as lo}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as To}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{hasTrigger as Eo,runTriggers as So}from"./packem_shared/hasTrigger-_rexbWMO.mjs";import{selectExpiredIds as _o}from"./packem_shared/selectExpiredIds-BGVP3d8-.mjs";import{compileWhereSql as xo}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{CDC_LOG_TABLE as Io,applyCdcChanges as Ro,readCdcChanges as Ao,trimCdcChanges as No}from"./packem_shared/CDC_LOG_TABLE-E_J5LPoK.mjs";import{backfillAggregateIndexes as Co,backfillRankIndexes as Mo}from"./packem_shared/backfillAggregateIndexes-BAQ3Fwwh.mjs";import{runShardMigrations as Oo}from"./packem_shared/runShardMigrations-bxOHpfID.mjs";import{stableStringify as Do}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Uo}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";import{subscriptionListDeltas as bo}from"./packem_shared/subscriptionListDeltas-Bs69JbA8.mjs";export{be as ADMIN_FUNCTIONS,ye as ADMIN_FUNCTION_PREFIX,T as AGGREGATE_SQL_FUNCTION,F as AUTH_METRICS_BUCKETS_TABLE,D as AUTH_METRICS_BUCKET_MS,L as AUTH_METRICS_BUCKET_RETENTION,U as AUTH_METRICS_TABLE,Io as CDC_LOG_TABLE,To as ConflictError,A as CountRlsUnsupportedError,X as DATA_MIGRATION_STATE_TABLE,Ar as DEFAULT_MAX_RELATION_KEYS,ke as FLAGS_FUNCTION_PREFIX,me as FUNCTION_METRICS_BUCKETS_TABLE,_e as FUNCTION_METRICS_BUCKET_MS,ue as FUNCTION_METRICS_BUCKET_RETENTION,xe as FUNCTION_METRICS_INDEX_TABLE,fe as FUNCTION_METRICS_TABLE,he as GEO_DEFAULT_PRECISION,we as LogBuffer,ze as MAIL_RETENTION,Xe as MAIL_TABLE,ao as MAX_SQL_ROWS,qr as MIN_ADMIN_TOKEN_LENGTH,zr as MIN_AUTH_SECRET_LENGTH,Je as NotFoundError,v as NotUniqueError,Tr as RANK_TIEBREAK,Ke as RELATION_FUNCTION_PREFIX,br as RLS_UNWRAP_SYMBOL,jr as ROOT_DO_SIZE_WARN_BYTES,Jr as ROOT_SHARD_NAME,ur as ReactiveCache,yr as RlsRequiredError,Z as SCAN_DEP,Vr as SESSION_DO_TTL_DEFAULT,ro as SHARD_REGISTRY_DO_NAME,Qr as SessionDO,$r as ShardDO,oo as ShardRegistryDO,d as aggregateSqlFunction,_ as aggregateTableName,Ro as applyCdcChanges,Fr as applyOnDelete,tr as applySelect,er as armRestore,Nr as assertFlatPredicate,no as assertReadonly,gr as assertShapeShardable,H as assertValidClientId,Co as backfillAggregateIndexes,Mo as backfillRankIndexes,Oe as boundingBoxGeohashes,Gr as buildFtsMatch,Xr as buildSecurityAudit,ar as buildSeekWhere,Ye as clearCapturedMail,u as coerceAggregateNumber,xo as compileWhereSql,Cr as containsRelationPredicate,Fe as coveringGeohashes,j as createDependencyTracker,K as createMetrics,w as createShardCtxDb,lo as createSystemReader,G as createTracer,nr as decodeCursor,J as depKey,oe as diffExternalSource,P as dispatchRootSpan,x as encodeAggregateKey,ir as encodeCursor,De as encodeGeohash,dr as encodePartitionKey,B as ensureAuthMetricsTables,Ie as ensureFunctionMetricsTables,Ve as ensureMailTable,o as exportShardRows,t as exportShardTable,Ge as facetColumn,Dr as fanOutScalarCounts,f as foldAggregateTally,Pr as ftsTableName,kr as guardWriter,Eo as hasTrigger,Le as haversineMeters,a as importShardRows,Mr as isRelationPredicate,ce as isSoftDeleted,Te as isSourceDue,de as liftSourceId,Pe as listTables,pr as matchesRankStaticWhere,p as matchesStaticWhere,ae as materializeExternalRows,ne as materializeExternalRowsIncremental,N as mergeWhere,E as normalizeCountArgument,q as normalizeIdStructurally,sr as normalizeOrderKeys,n as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,Ue as pointInBoundingBox,pe as pullExternalSourceIncrementalTick,Ee as pullExternalSourceTick,Er as rankTableName,xr as reactiveCacheKey,I as readAggregateValue,b as readAuthMetrics,rr as readBookmark,Qe as readCapturedMail,Ao as readCdcChanges,ie as readExternalSourceBaseline,Re as readFunctionMetricBuckets,Ae as readFunctionMetricIndexHits,Ne as readFunctionMetrics,ge as readFunctionMetricsTotals,Y as readMigrationStatus,We as readTablePage,y as recordAuthEvent,Ze as recordCapturedMail,Ce as recordFunctionMetric,ee as renderSql,Sr as resolveRankPartition,hr as resolveRelationPredicates,Lr as resolveWith,V as runDataMigration,se as runExternalSourceTick,io as runReadonlySql,Ur as runRowValidators,Oo as runShardMigrations,So as runTriggers,Wr as scoreDocument,_o as selectExpiredIds,s as selectExportTables,C as selectIndexForAggregate,M as selectIndexForCount,h as selectIndexForGroupBy,ve as selectMatchingIds,Ir as serveRelationFanout,lr as softDeleteScope,mr as sortColumnName,Do as stableStringify,Uo as stableWireKey,vr as stringifySearchText,bo as subscriptionListDeltas,S as throwingScheduler,Hr as tokenizeSearch,No as trimCdcChanges,l as validateImportRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";const m=e=>`"${e.replaceAll('"','""')}"`,Q="__lunora_admin__:",H="__lunora_relation__:",G="__lunora_flags__:",K={applyCdc:"__lunora_admin__:applyCdc",assignIssue:"__lunora_admin__:assignIssue",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},N=50,b=500,x=30,L=200,d="__doc__",R=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},F=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const r=[];for(const s of t){const _=s[d],c=typeof _=="string"?R(_):void 0;if(c===void 0)return{columns:e,rows:t};const i=Object.fromEntries(Object.entries(s).filter(([u])=>u!==d));r.push({...i,...c})}const a=e.filter(s=>s!==d),o=[],n=new Set(a);for(const s of r)for(const _ of Object.keys(s))n.has(_)||(n.add(_),o.push(_));return{columns:[...a,...o],rows:r}},k=e=>e.replaceAll(/[\\%_]/g,t=>`\\${t}`),h=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),v=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},X=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:a}of t)h(a)||r.push({name:a,rowCount:v(e,m(a))});return r},A=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,P={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},W=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",E=(e,t)=>{const r=t.includes(e),a=t.includes(d);if(!(!r&&!a))return r?{expression:m(e),params:[]}:{expression:`json_extract(${m(d)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},U=(e,t)=>{const r=E(e.column,t);if(r===void 0)return;const{expression:a,params:o}=r;return e.operator==="contains"?{params:[...o,`%${k(W(e.value))}%`],sql:String.raw`CAST(${a} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...o,e.value],sql:`${a} ${P[e.operator]} ?`}},$=(e,t,r)=>{const a=[],o=[];if(t!==""&&e.length>0){const n=`%${k(t)}%`;a.push(`(${e.map(s=>String.raw`CAST(${m(s)} AS TEXT) LIKE ? ESCAPE '\'`).join(" OR ")})`),o.push(...e.map(()=>n))}for(const n of r??[]){const s=U(n,e);s!==void 0&&(a.push(`(${s.sql})`),o.push(...s.params))}return a.length===0?void 0:{parameters:o,where:a.join(" AND ")}},q=(e,t)=>{if(e===void 0)return;const r=E(e.column,t);if(r===void 0)return;const a=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${a}`}},Y=(e,t)=>{const{table:r}=t;if(h(r)||!A(e,r))throw new S("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const a=C(Math.trunc(t.limit??N),1,b),o=Math.max(0,Math.trunc(t.offset??0)),n=m(r),s=e.exec(`PRAGMA table_info(${n})`).toArray().map(M=>M.name),_=t.search?.trim()??"",c=M=>{if(t.refs===void 0)return M;const I={};for(const w of M.columns){const O=t.refs[w];O!==void 0&&(I[w]=O)}return Object.keys(I).length>0?{...M,refs:I}:M},i=$(s,_,t.filters),u=q(t.orderBy,s),l=i===void 0?"":` WHERE ${i.where}`,g=u===void 0?"":` ORDER BY ${u.sql}`,p=i?.parameters??[],T=u?.params??[];let f;t.skipCount||(f=i===void 0?v(e,n):Number(e.exec(`SELECT COUNT(*) AS c FROM ${n}${l}`,...p).one().c));const y=e.exec(`SELECT * FROM ${n}${l}${g} LIMIT ? OFFSET ?`,...p,...T,a,o).toArray();return c({...F(s,y),total:f})},z=(e,t)=>{const{table:r}=t;if(h(r)||!A(e,r))throw new S("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const a=C(Math.trunc(t.limit??b),1,b),o=m(r),n=e.exec(`PRAGMA table_info(${o})`).toArray().map(l=>l.name),s=t.search?.trim()??"",_=$(n,s,t.filters),c=_===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,a+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${_.where} LIMIT ?`,..._.parameters,a+1).toArray(),i=c.length>a,u=(i?c.slice(0,a):c).map(l=>l.id);return{hasMore:i,ids:u}},j=(e,t,r)=>{const a=new Set(r.filter(n=>n!==d));if(!r.includes(d))return a;const o=e.exec(`SELECT ${m(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:n}of o){const s=typeof n=="string"?R(n):void 0;if(s!==void 0)for(const _ of Object.keys(s))a.add(_)}return a},J=(e,t)=>{const{column:r,table:a}=t;if(h(a)||!A(e,a))throw new S("UNKNOWN_TABLE",`unknown table: ${a}`,{status:404});const o=m(a),n=e.exec(`PRAGMA table_info(${o})`).toArray().map(f=>f.name);if(!j(e,o,n).has(r))throw new S("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=E(r,n);if(s===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const _=C(Math.trunc(t.limit??x),1,L),c=t.search?.trim()??"",i=$(n,c,t.filters),u=i===void 0?"":` WHERE ${i.where}`,l=i?.parameters??[],g=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,_+1).toArray(),p=g.length>_,T=p?g.slice(0,_):g;return{truncated:p,values:T.map(f=>({count:Number(f.count),value:f.value}))}},Z=(e,t,r)=>{const a={},o=r.slice(0,b);for(const s of o)a[s]=[];if(o.length===0)return{references:a,storageColumns:t};const n=o.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(h(s)||!A(e,s))continue;const c=m(s),i=e.exec(`PRAGMA table_info(${c})`).toArray().map(u=>u.name);for(const u of _){const l=E(u,i);if(l===void 0)continue;const g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${c} WHERE ${l.expression} IN (${n})`,...l.params,...l.params,...o).toArray();for(const p of g)a[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:a,storageColumns:t}},V=e=>{const t=e.map((a,o)=>{const n=Object.values(a.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:a.admin===!0,id:o,subscriptions:n}}),r=t.reduce((a,o)=>a+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},D=20,ee=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),te=(e,t,r,a)=>({maxMs:Math.max(e.maxMs,a),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+a}),ae=(e,t=D)=>{const r=new Map,a=new Map;for(const n of e){for(const s of Object.values(n.shapes??{})){const _=s.name??"(unknown shape)";r.set(_,(r.get(_)??0)+1)}for(const s of n.whispers??[])a.set(s,(a.get(s)??0)+1)}const o=[...[...r].map(([n,s])=>({kind:"shape",subscribers:s,topic:n})),...[...a].map(([n,s])=>({kind:"whisper",subscribers:s,topic:n}))];return o.sort((n,s)=>s.subscribers-n.subscribers||n.topic.localeCompare(s.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{K as ADMIN_FUNCTIONS,Q as ADMIN_FUNCTION_PREFIX,D as DEFAULT_FANOUT_TOPIC_LIMIT,G as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,H as RELATION_FUNCTION_PREFIX,ee as createFanoutCounters,J as facetColumn,Z as findStorageReferences,X as listTables,Y as readTablePage,te as recordFanoutPass,z as selectMatchingIds,ae as summarizeFanoutTopics,V as summarizeSubscriptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";const i=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),f=(e,r)=>{for(const[n,t]of Object.entries(r)){const s=e[n];if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const c=Object.keys(t);if(c.length===1&&c[0]==="eq"){if(s!==t.eq)return!1;continue}return!1}if(s!==t)return!1}return!0},h=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>i.has(n))?e:{where:e}},u={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},g=e=>{const r=u[e];if(r===void 0)throw new o("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(u).join(", ")}`);return r},l={runAfter:()=>{throw new o("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},runAt:()=>{throw new o("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")}};export{u as AGGREGATE_SQL_FUNCTION,g as aggregateSqlFunction,f as matchesStaticWhere,h as normalizeCountArgument,l as throwingScheduler};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const _="__lunora_auth_metrics",T="__lunora_auth_metrics_buckets",A="app",N=6e4,R=1440,t=(s,e,...E)=>s.exec.call(s,e,...E),c=s=>Math.floor(s/6e4)*6e4,r=s=>{t(s,`CREATE TABLE IF NOT EXISTS "${_}" (
|
|
2
|
+
key TEXT PRIMARY KEY,
|
|
3
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
4
|
+
failures INTEGER NOT NULL DEFAULT 0,
|
|
5
|
+
since_ms INTEGER NOT NULL DEFAULT 0
|
|
6
|
+
)`),t(s,`CREATE TABLE IF NOT EXISTS "${T}" (
|
|
7
|
+
bucket_ms INTEGER PRIMARY KEY,
|
|
8
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
9
|
+
failures INTEGER NOT NULL DEFAULT 0
|
|
10
|
+
)`)},l=(s,e)=>{r(s);const E=e.outcome==="fail"?1:0;t(s,`INSERT INTO "${_}" (key, attempts, failures, since_ms)
|
|
11
|
+
VALUES (?, 1, ?, ?)
|
|
12
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
13
|
+
attempts = attempts + 1,
|
|
14
|
+
failures = failures + excluded.failures,
|
|
15
|
+
since_ms = CASE WHEN since_ms = 0 THEN excluded.since_ms ELSE since_ms END`,"app",E,e.ts);const a=c(e.ts);t(s,`INSERT INTO "${T}" (bucket_ms, attempts, failures)
|
|
16
|
+
VALUES (?, 1, ?)
|
|
17
|
+
ON CONFLICT(bucket_ms) DO UPDATE SET
|
|
18
|
+
attempts = attempts + 1,
|
|
19
|
+
failures = failures + excluded.failures`,a,E),t(s,`DELETE FROM "${T}"
|
|
20
|
+
WHERE bucket_ms <= (
|
|
21
|
+
SELECT MAX(bucket_ms) - ? FROM "${T}"
|
|
22
|
+
)`,864e5)},L=s=>{r(s);const e=t(s,`SELECT attempts, failures, since_ms FROM "${_}" WHERE key = ?`,"app").toArray()[0],E=e?.attempts??0,a=e?.failures??0,m=e?.since_ms??0,i=t(s,`SELECT bucket_ms, attempts, failures FROM "${T}" ORDER BY bucket_ms ASC`).toArray().map(u=>({attempts:u.attempts,bucketMs:u.bucket_ms,failures:u.failures}));return{attempts:E,failureRate:E===0?0:a/E,failures:a,history:i,sinceMs:m}};export{T as AUTH_METRICS_BUCKETS_TABLE,N as AUTH_METRICS_BUCKET_MS,R as AUTH_METRICS_BUCKET_RETENTION,A as AUTH_METRICS_ROW_KEY,_ as AUTH_METRICS_TABLE,r as ensureAuthMetricsTables,L as readAuthMetrics,l as recordAuthEvent};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{r as a}from"./do-exec-BLe9lLrN.mjs";import{ConflictError as l}from"./ConflictError-C8GtJmjS.mjs";const o="__cdc_log",$=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
${e.identifier("table")} TEXT NOT NULL,
|
|
5
|
+
id TEXT NOT NULL,
|
|
6
|
+
op TEXT NOT NULL,
|
|
7
|
+
doc TEXT
|
|
8
|
+
)`)},R=(t,i,s,E,c,d)=>{const r=d===void 0?null:JSON.stringify(d);a(t,e`INSERT INTO ${e.identifier(o)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${i}, ${s}, ${E}, ${c}, ${r})`)},A=(t,i={})=>{const s=i.sinceSeq??0,E=Math.max(1,Math.min(i.limit??1e3,1e4)),c=i.tables&&i.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...i.tables].map(r=>e`${r}`),e`, `)})`:e``,d=a(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(o)} WHERE seq > ${s}${c} ORDER BY seq ASC LIMIT ${E}`).toArray().map(r=>{const T={id:r.id,op:r.op,seq:r.seq,table:r.table,ts:r.ts};return r.doc===null?T:{...T,doc:JSON.parse(r.doc)}});return{changes:d,cursor:d.at(-1)?.seq??s}},O=(t,i)=>{a(t,e`DELETE FROM ${e.identifier(o)} WHERE seq <= ${i}`)},I=t=>{const i=a(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${o}`).toArray()[0]?.seq;return typeof i=="number"?i:a(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(o)}`).toArray()[0]?.seq??0},S=t=>a(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(o)}`).toArray()[0]?.seq??void 0,n="__cdc_meta",p=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},m=t=>{p(t);const i=a(t,e`SELECT epoch FROM ${e.identifier(n)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const s=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${s})`),s},q=t=>{p(t);const i=crypto.randomUUID();return a(t,e`INSERT INTO ${e.identifier(n)} (id, epoch) VALUES (1, ${i}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),i},C=async(t,i)=>{if(i.op==="delete"){await t.delete(i.id,i.table);return}const s=i.doc??{};try{await t.insert(i.table,s,{allowExplicitId:!0})}catch(E){if(!(E instanceof l))throw E;const c={};for(const[d,r]of Object.entries(s))d!=="_id"&&(c[d]=r);await t.replace(i.id,c,void 0,{allowExplicitId:!0})}},h=async(t,i)=>{for(const s of i)await C(t,s)};export{o as CDC_LOG_TABLE,n as CDC_META_TABLE,R as appendCdcChange,h as applyCdcChanges,q as bumpCdcEpoch,$ as migrateCdcLog,p as migrateCdcMeta,S as minCdcSeq,A as readCdcChanges,I as readCdcCursor,m as readCdcEpoch,O as trimCdcChanges};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";class i extends c{kind;constructor(r="Optimistic concurrency conflict",o="conflict"){super("CONFLICT",r,{name:"ConflictError"}),this.kind=o}}export{i as ConflictError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";class A extends y{constructor(e){super("COUNT_RLS_UNSUPPORTED",e===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${e}" inside an RLS-restricted context`)}}const R=(t,e)=>t?e?{AND:[t,e]}:t:e,g=new Set(["AND","NOT","OR"]),f=Symbol("not-eq"),b=t=>{if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const e=Object.keys(t);return e.length===1&&e[0]==="eq"?t.eq:f}return t},d=(t,e)=>{const s={};for(const[o,n]of Object.entries(t)){if(g.has(o)||!e(o))return;const r=b(n);if(r===f)return;s[o]=r}return s},a=(t,e,s,o)=>{const n={...e};if(!t)return n;for(const[r,i]of Object.entries(t))if(r in n){if(n[r]!==i)return}else if(o&&r in s){if(s[r]!==i)return}else n[r]=i;return n},x=(t,e)=>{const s=t.by??[],o=e??{},n=d(o,r=>s.includes(r));if(n!==void 0){for(const r of s)if(!(r in n))return;return a(t.where,n,o,!0)}},h=(t,e,s)=>{const o=d(e??{},n=>s.has(n));if(o!==void 0)return a(t.where,o,{},!1)},l=(t,e,s,o)=>{let n;for(const r of t){if(r.op!==e||e!=="count"&&r.field!==s)continue;const i=x(r,o);i&&(!n||(r.by?.length??0)>(n.index.by?.length??0))&&(n={index:r,key:i})}return n},S=(t,e)=>l(t,"count",void 0,e),v=(t,e,s,o)=>l(t,e,s,o),w=(t,e,s,o,n)=>{const r=new Set(o);for(const i of t){if(i.op!==e||e!=="count"&&i.field!==s)continue;const c=i.by??[];if(c.length!==r.size||!c.every(p=>r.has(p)))continue;const u=h(i,n,r);if(u!==void 0)return{index:i,partial:u}}};export{A as CountRlsUnsupportedError,R as mergeWhere,x as planAggregateLookup,v as selectIndexForAggregate,S as selectIndexForCount,w as selectIndexForGroupBy};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{LunoraError as I}from"@lunora/errors";const o="__lunora_migrations",O=100,y=3e4,D=1e4,i=(r,t,...e)=>r.exec.call(r,t,...e),$=r=>{i(r,`CREATE TABLE IF NOT EXISTS "${o}" (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
direction TEXT NOT NULL,
|
|
4
|
+
status TEXT NOT NULL,
|
|
5
|
+
cursor TEXT,
|
|
6
|
+
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
started_at REAL,
|
|
9
|
+
updated_at REAL,
|
|
10
|
+
error TEXT
|
|
11
|
+
)`)},R=(r,t)=>{const e=i(r,`SELECT * FROM "${o}" WHERE id = ?`,t).toArray()[0];if(e)return{changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,startedAt:typeof e.started_at=="number"?e.started_at:void 0,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}},w=(r,t)=>{i(r,`DELETE FROM "${o}" WHERE id = ?`,t)},f=(r,t)=>{i(r,`INSERT INTO "${o}"
|
|
12
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
13
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
14
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
15
|
+
direction = excluded.direction,
|
|
16
|
+
status = excluded.status,
|
|
17
|
+
cursor = excluded.cursor,
|
|
18
|
+
processed = excluded.processed,
|
|
19
|
+
changed = excluded.changed,
|
|
20
|
+
updated_at = excluded.updated_at,
|
|
21
|
+
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},U=(r,t,e,n)=>(i(r,`INSERT INTO "${o}"
|
|
22
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
23
|
+
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
24
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
25
|
+
status = 'in_progress',
|
|
26
|
+
updated_at = excluded.updated_at
|
|
27
|
+
WHERE
|
|
28
|
+
"${o}".direction <> excluded.direction
|
|
29
|
+
OR "${o}".status <> 'in_progress'
|
|
30
|
+
OR "${o}".updated_at IS NULL
|
|
31
|
+
OR "${o}".updated_at <= excluded.updated_at - ${String(y)}`,t,e,n,n),i(r,"SELECT changes() AS changed").one().changed>0),x=(r,t)=>{i(r,`UPDATE "${o}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},C=(r,t,e)=>{i(r,`UPDATE "${o}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,e,t)},b=(r,t)=>{if(i(r,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",o).toArray().length===0)return[];const e=t===void 0?" ORDER BY id":" WHERE id = ?",n=t===void 0?[]:[t];return i(r,`SELECT * FROM "${o}"${e}`,...n).toArray().map(d=>({changed:d.changed,cursor:typeof d.cursor=="string"?d.cursor:null,direction:d.direction==="down"?"down":"up",error:typeof d.error=="string"?d.error:null,id:d.id,processed:d.processed,startedAt:typeof d.started_at=="number"?d.started_at:null,status:d.status==="completed"||d.status==="failed"?d.status:"in_progress",updatedAt:typeof d.updated_at=="number"?d.updated_at:null}))},F=async r=>{const{migration:t,sql:e,writer:n}=r,d=r.direction??"up",c=r.dryRun??!1,g=r.clock??(()=>Date.now()),m=r.maxBatches??Number.POSITIVE_INFINITY,S=r.batchSize??t.batchSize??O,N=d==="up"?t.up:t.down;if(!N)throw new I("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);let u=null,l=0,T=0,_=g();if(!c){$(e);const s=R(e,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:c,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&w(e,t.id),!U(e,t.id,d,g())){const E=R(e,t.id);return{changed:E?.changed??0,cursor:E?.cursor??u,direction:d,dryRun:c,id:t.id,processed:E?.processed??0,status:E?.status??"in_progress"}}const a=s?.direction===d?s:void 0;a&&(u=a.cursor,l=a.processed,T=a.changed,_=a.startedAt??_)}let p=!1,A=0,h=_;try{for(;!p&&A<m;){const s=await n.findMany(t.table,{cursor:u,limit:S});for(const a of s.page){l+=1;const E=N(a);if(E!==void 0&&(T+=1,c||await n.replace(String(a._id),{...E,_creationTime:a._creationTime,_id:a._id},void 0,{allowExplicitId:!0})),!c){const L=g();L-h>=D&&(C(e,t.id,L),h=L)}}if(u=s.continueCursor,p=s.isDone,A+=1,!c){const a=g();f(e,{changed:T,cursor:p?null:u,direction:d,error:null,id:t.id,processed:l,startedAt:_,status:p?"completed":"in_progress",updatedAt:a}),h=a;try{await r.onBatch?.({batches:A,changed:T,processed:l})}catch{}}}}catch(s){throw c||f(e,{changed:T,cursor:u,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:l,startedAt:_,status:"failed",updatedAt:g()}),s}if(!c&&!p)try{x(e,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:T,cursor:p?null:u,direction:d,dryRun:c,id:t.id,processed:l,status:p?"completed":"in_progress"}};export{o as DATA_MIGRATION_STATE_TABLE,b as readMigrationStatus,F as runDataMigration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{distinctValues as O}from"./applyOnDelete-BvQN7pDL.mjs";const k="__relationExists",f={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=new Set(Object.keys(f)),A=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,u=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],g=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>R.has(n))},d=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const r=e[s];return s==="AND"||s==="OR"?b(r).some(o=>d(o,t,n)):s==="NOT"?d(r??{},t,n):!!a[s]&&p(r)})},I=(e,t,n,a)=>{if(e&&d(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},E=async(e,t,n,a,s)=>{const r=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:r}),i=O(o,n);if(i.length>a.maxRelationKeys){if(s)return u;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,s)=>{const r=f[e];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);const{clause:o,project:i}=A(t),l=await E(t,r.negateChild?{NOT:n}:n,i,a,s);return l===u?u:r.negated?r.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},m=async(e,t,n,a,s)=>{const r=f[e];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);const o=s.relationBaseWhere?.(t.table),i=r.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,s),negated:r.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=f[e];if(a&&a.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,s)=>{const r=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=s.canPushExists?.(t)??!1;if(l&&s.existsPushMode==="always"){r.push(await m(o,t,i,a,s));continue}const w=await T(o,t,i,s,l);w===u?r.push(await m(o,t,i,a,s)):r.push(w)}return g(r)},S=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const r=[];for(const o of b(t))r.push(await c(o,n,a));return{[e]:r}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const s=a.schema.tables[n]?.relationMap?.[e];return s&&p(t)?x(e,s,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const s of Object.keys(e))a.push(await S(s,e[s],t,n));return g(a)},L=async(e,t)=>!e||!d(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),y=(e,t,n)=>{for(const a of e){const s=N(a,t,n);if(s)return s}},D=(e,t,n,a)=>{if(e==="AND"||e==="OR")return y(b(t),n,a);if(e==="NOT")return y([t??{}],n,a);const s=n.tables[a]?.relationMap?.[e];if(!(!s||!p(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:y(Object.values(t),n,s.table)},N=(e,t,n)=>{for(const a of Object.keys(e)){const s=D(a,e[a],t,n);if(s)return s}},M=(e,t,n)=>{if(!e)return;const a=N(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,I as assertFlatPredicate,M as assertShapeShardable,d as containsRelationPredicate,p as isRelationPredicate,L as resolveRelationPredicates};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const n="__lunora_metrics",_="__lunora_metrics_buckets",c="__lunora_metrics_scans",N="__lunora_metrics_index",O=6e4,R=1440,I=5e3,C=1e3,t=(a,s,...e)=>a.exec.call(a,s,...e),u=a=>Math.floor(a/6e4)*6e4,A=a=>{const s=new Map;for(const e of a)s.set(`${e.table}\0${e.index}`,{index:e.index,table:e.table});return[...s.values()]},l=a=>{t(a,`CREATE TABLE IF NOT EXISTS "${n}" (
|
|
2
|
+
path TEXT PRIMARY KEY,
|
|
3
|
+
calls INTEGER NOT NULL DEFAULT 0,
|
|
4
|
+
errors INTEGER NOT NULL DEFAULT 0,
|
|
5
|
+
conflicts INTEGER NOT NULL DEFAULT 0,
|
|
6
|
+
scans INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
total_duration_ms REAL NOT NULL DEFAULT 0,
|
|
8
|
+
min_duration_ms REAL,
|
|
9
|
+
max_duration_ms REAL NOT NULL DEFAULT 0,
|
|
10
|
+
last_called_at REAL NOT NULL DEFAULT 0,
|
|
11
|
+
last_error_at REAL,
|
|
12
|
+
last_error_message TEXT
|
|
13
|
+
)`);for(const s of["scans","conflicts"])try{t(a,`ALTER TABLE "${n}" ADD COLUMN ${s} INTEGER NOT NULL DEFAULT 0`)}catch{}t(a,`CREATE TABLE IF NOT EXISTS "${_}" (
|
|
14
|
+
path TEXT NOT NULL,
|
|
15
|
+
bucket_ms INTEGER NOT NULL,
|
|
16
|
+
calls INTEGER NOT NULL DEFAULT 0,
|
|
17
|
+
errors INTEGER NOT NULL DEFAULT 0,
|
|
18
|
+
PRIMARY KEY (path, bucket_ms)
|
|
19
|
+
)`),t(a,`CREATE TABLE IF NOT EXISTS "${c}" (
|
|
20
|
+
path TEXT NOT NULL,
|
|
21
|
+
table_name TEXT NOT NULL,
|
|
22
|
+
scans INTEGER NOT NULL DEFAULT 0,
|
|
23
|
+
PRIMARY KEY (path, table_name)
|
|
24
|
+
)`),t(a,`CREATE TABLE IF NOT EXISTS "${N}" (
|
|
25
|
+
table_name TEXT NOT NULL,
|
|
26
|
+
index_name TEXT NOT NULL,
|
|
27
|
+
reads INTEGER NOT NULL DEFAULT 0,
|
|
28
|
+
PRIMARY KEY (table_name, index_name)
|
|
29
|
+
)`)},U=(a,s)=>{if(l(a),t(a,`SELECT COUNT(*) AS n FROM "${n}"`).one().n>=5e3&&t(a,`SELECT COUNT(*) AS c FROM "${n}" WHERE path = ?`,s.path).one().c===0)return;const e=s.scannedTables?[...new Set(s.scannedTables)]:[],r=e.length,E=A(s.indexHits??[]),T=s.errored?1:0,d=s.conflicted?1:0,L=s.errored?s.ts:null,i=s.errored?s.errorMessage??null:null;t(a,`INSERT INTO "${n}"
|
|
30
|
+
(path, calls, errors, conflicts, scans, total_duration_ms, min_duration_ms, max_duration_ms, last_called_at, last_error_at, last_error_message)
|
|
31
|
+
VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
32
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
33
|
+
calls = calls + 1,
|
|
34
|
+
errors = errors + excluded.errors,
|
|
35
|
+
conflicts = conflicts + excluded.conflicts,
|
|
36
|
+
scans = scans + excluded.scans,
|
|
37
|
+
total_duration_ms = total_duration_ms + excluded.total_duration_ms,
|
|
38
|
+
min_duration_ms = MIN(COALESCE(min_duration_ms, excluded.min_duration_ms), excluded.min_duration_ms),
|
|
39
|
+
max_duration_ms = MAX(max_duration_ms, excluded.max_duration_ms),
|
|
40
|
+
last_called_at = excluded.last_called_at,
|
|
41
|
+
last_error_at = CASE WHEN excluded.last_error_at IS NULL THEN last_error_at ELSE excluded.last_error_at END,
|
|
42
|
+
last_error_message = CASE WHEN excluded.last_error_at IS NULL THEN last_error_message ELSE excluded.last_error_message END`,s.path,T,d,r,s.durationMs,s.durationMs,s.durationMs,s.ts,L,i);const m=u(s.ts);t(a,`INSERT INTO "${_}" (path, bucket_ms, calls, errors)
|
|
43
|
+
VALUES (?, ?, 1, ?)
|
|
44
|
+
ON CONFLICT(path, bucket_ms) DO UPDATE SET
|
|
45
|
+
calls = calls + 1,
|
|
46
|
+
errors = errors + excluded.errors`,s.path,m,T),t(a,`DELETE FROM "${_}"
|
|
47
|
+
WHERE path = ?
|
|
48
|
+
AND bucket_ms <= (
|
|
49
|
+
SELECT MAX(bucket_ms) - ? FROM "${_}" WHERE path = ?
|
|
50
|
+
)`,s.path,864e5,s.path);for(const o of e)t(a,`INSERT INTO "${c}" (path, table_name, scans)
|
|
51
|
+
VALUES (?, ?, 1)
|
|
52
|
+
ON CONFLICT(path, table_name) DO UPDATE SET
|
|
53
|
+
scans = scans + 1`,s.path,o);for(const o of E)t(a,`INSERT INTO "${N}" (table_name, index_name, reads)
|
|
54
|
+
VALUES (?, ?, 1)
|
|
55
|
+
ON CONFLICT(table_name, index_name) DO UPDATE SET
|
|
56
|
+
reads = reads + 1`,o.table,o.index)},S=a=>{l(a);const s=t(a,`SELECT path, table_name, scans FROM "${c}" ORDER BY scans DESC, path ASC, table_name ASC LIMIT ${String(1e3)}`).toArray(),e=new Map;for(const r of s){const E=e.get(r.path),T={scans:r.scans,table:r.table_name};E===void 0?e.set(r.path,[T]):E.push(T)}return e},M=a=>(l(a),t(a,`SELECT table_name, index_name, reads FROM "${N}" ORDER BY table_name ASC, index_name ASC`).toArray().map(s=>({index:s.index_name,reads:s.reads,table:s.table_name}))),F=(a,s)=>{for(const e of s){const r=a.find(E=>E.table===e);r===void 0?a.push({scans:1,table:e}):r.scans+=1}return a.sort((e,r)=>r.scans-e.scans||e.table.localeCompare(r.table)),a},b=a=>{l(a);const s=S(a);return t(a,`SELECT * FROM "${n}" ORDER BY last_called_at DESC LIMIT ${String(1e3)}`).toArray().map(e=>({calls:e.calls,conflicts:e.conflicts,errors:e.errors,lastCalledAt:e.last_called_at,lastErrorAt:e.last_error_at,lastErrorMessage:e.last_error_message,maxDurationMs:e.max_duration_ms,path:e.path,scannedTables:s.get(e.path)??[],scans:e.scans,totalDurationMs:e.total_duration_ms}))},p=(a,s)=>(l(a),(s===void 0?t(a,`SELECT path, bucket_ms, calls, errors FROM "${_}" ORDER BY bucket_ms ASC, path ASC`).toArray():t(a,`SELECT path, bucket_ms, calls, errors FROM "${_}" WHERE path = ? ORDER BY bucket_ms ASC`,s).toArray()).map(e=>({bucketMs:e.bucket_ms,calls:e.calls,errors:e.errors,path:e.path}))),h=a=>{l(a);const s=t(a,`SELECT SUM(calls) AS requests, SUM(errors) AS errors FROM "${n}"`).one();return{errors:s.errors??0,requests:s.requests??0}};export{_ as FUNCTION_METRICS_BUCKETS_TABLE,O as FUNCTION_METRICS_BUCKET_MS,R as FUNCTION_METRICS_BUCKET_RETENTION,N as FUNCTION_METRICS_INDEX_TABLE,I as FUNCTION_METRICS_MAX_PATHS,C as FUNCTION_METRICS_READ_LIMIT,c as FUNCTION_METRICS_SCANS_TABLE,n as FUNCTION_METRICS_TABLE,l as ensureFunctionMetricsTables,F as mergeScanAttribution,p as readFunctionMetricBuckets,M as readFunctionMetricIndexHits,S as readFunctionMetricScans,b as readFunctionMetrics,h as readFunctionMetricsTotals,U as recordFunctionMetric};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const x="0123456789bcdefghjkmnpqrstuvwxyz",y=9,b=63710088e-1,i=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],d=t=>Math.min(Math.max(Math.trunc(t),1),12),f=(t,n)=>{const e=d(n);let s=-90,o=90,r=-180,l=180,g="",u=0,a=0,w=!0;for(;g.length<e;){if(w){const c=(r+l)/2;t.lng>=c?(a=a*2+1,r=c):(a*=2,l=c)}else{const c=(s+o)/2;t.lat>=c?(a=a*2+1,s=c):(a*=2,o=c)}w=!w,u<4?u+=1:(g+=x[a]??"0",u=0,a=0)}return g},m=(t,n)=>{const e=u=>u*Math.PI/180,s=e(n.lat-t.lat),o=e(n.lng-t.lng),r=e(t.lat),l=e(n.lat),g=Math.sin(s/2)**2+Math.cos(r)*Math.cos(l)*Math.sin(o/2)**2;return 2*b*Math.asin(Math.min(1,Math.sqrt(g)))},p=t=>{for(let n=i.length-1;n>=1;n-=1){const e=i[n];if(e!==void 0&&e>=t)return n}return 1},v={east:["bc01fg45238967deuvhjyznpkmstqrwx","bc01fg45238967deuvhjyznpkmstqrwx"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","238967debc01fg45kmstqrwxuvhjyznp"]},M={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},h=(t,n)=>{const e=t.toLowerCase(),s=e.at(-1)??"";let o=e.slice(0,-1);const r=e.length%2===0?0:1;return M[n][r].includes(s)&&o!==""&&(o=h(o,n)),o+(x[v[n][r].indexOf(s)]??"")},z=(t,n)=>{const e=p(Math.max(n,1)),s=f(t,e),o=h(s,"north"),r=h(s,"south"),l=[s,o,r,h(s,"east"),h(s,"west"),h(o,"east"),h(o,"west"),h(r,"east"),h(r,"west")];return[...new Set(l)]},q=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,j=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),k=t=>{const n=j(t);return z(n,Math.max(m(n,t.ne),1))};export{y as GEO_DEFAULT_PRECISION,j as boundingBoxCenter,k as boundingBoxGeohashes,z as coveringGeohashes,f as encodeGeohash,m as haversineMeters,q as pointInBoundingBox};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class r{buffer=[];capacity;constructor(t=500){this.capacity=t>0?Math.trunc(t):500}get size(){return this.buffer.length}clear(){this.buffer.length=0}entries(){return this.buffer.toReversed()}push(t){this.buffer.push(t),this.buffer.length>this.capacity&&this.buffer.shift()}}export{r as LogBuffer};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const t="__lunora_mail",l=500,_=262144,i=d=>d!==void 0&&d.length>262144?`${d.slice(0,262144)}
|
|
2
|
+
… [truncated by the dev mail catcher]`:d,c=(d,e,...r)=>d.exec.call(d,e,...r),T=d=>d??null,s=d=>d===void 0?null:JSON.stringify(d),E=d=>{if(!(d==null||d===""))try{return JSON.parse(d)}catch{return}},o=d=>{c(d,`CREATE TABLE IF NOT EXISTS "${t}" (
|
|
3
|
+
id TEXT PRIMARY KEY,
|
|
4
|
+
captured_at INTEGER NOT NULL,
|
|
5
|
+
from_addr TEXT,
|
|
6
|
+
to_addrs TEXT NOT NULL,
|
|
7
|
+
cc_addrs TEXT,
|
|
8
|
+
bcc_addrs TEXT,
|
|
9
|
+
reply_to TEXT,
|
|
10
|
+
subject TEXT NOT NULL,
|
|
11
|
+
html TEXT,
|
|
12
|
+
body_text TEXT,
|
|
13
|
+
headers TEXT
|
|
14
|
+
)`)},u=(d,e,r)=>{o(d);const a=crypto.randomUUID();return c(d,`INSERT INTO "${t}" (id, captured_at, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to, subject, html, body_text, headers)
|
|
15
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,a,r,T(e.from),JSON.stringify(e.to),s(e.cc),s(e.bcc),T(e.replyTo),e.subject,T(i(e.html)),T(i(e.text)),s(e.headers)),c(d,`DELETE FROM "${t}"
|
|
16
|
+
WHERE id NOT IN (
|
|
17
|
+
SELECT id FROM "${t}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
18
|
+
)`,500),{id:a}},p=(d,e={})=>{o(d);const r=Math.min(Math.max(e.limit??50,1),500);return{entries:c(d,`SELECT * FROM "${t}" ORDER BY captured_at DESC, id DESC LIMIT ?`,r).toArray().map(a=>({bcc:E(a.bcc_addrs),capturedAt:a.captured_at,cc:E(a.cc_addrs),from:a.from_addr??void 0,headers:E(a.headers),html:a.html??void 0,id:a.id,replyTo:a.reply_to??void 0,subject:a.subject,text:a.body_text??void 0,to:E(a.to_addrs)??a.to_addrs}))}},m=d=>(o(d),c(d,`DELETE FROM "${t}"`),{cleared:!0});export{l as MAIL_RETENTION,t as MAIL_TABLE,_ as MAX_BODY_CHARS,m as clearCapturedMail,o as ensureMailTable,p as readCapturedMail,u as recordCapturedMail};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";const a=1e3,n=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,i=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,u=/;\s*$/u,c=/\s/u,d=(r,e)=>{let t=e+2;for(;t<r.length&&r[t]!==`
|
|
2
|
+
`;)t+=1;return t},h=(r,e)=>{const t=r.indexOf("*/",e+2);return t===-1?-1:t+2},f=r=>{let e=0;for(;e<r.length;){const t=r[e];if(t!==void 0&&c.test(t))e+=1;else if(t==="-"&&r[e+1]==="-")e=d(r,e);else if(t==="/"&&r[e+1]==="*"){const s=h(r,e);if(s===-1)break;e=s}else break}return r.slice(e)},l=(r,e)=>new o(e,r,{status:400}),y=r=>{const e=f(r).trim();if(e==="")throw l("the query is empty","SQL_EMPTY");const t=e.replace(u,"");if(t.includes(";"))throw l("only a single statement may be run","SQL_MULTIPLE_STATEMENTS");if(!n.test(t)||i.test(t))throw l("the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed","SQL_NOT_READONLY")},m=(r,e)=>{y(e);const t=r.exec(e).toArray(),s=t.length>a?t.slice(0,a):t;return{columns:s.length>0?Object.keys(s[0]):[],rowCount:t.length,rows:s,truncated:t.length>a}};export{a as MAX_SQL_ROWS,y as assertReadonly,m as runReadonlySql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as E,c as T,_ as a}from"./security-audit-BKUOgE0x.mjs";export{E as MIN_ADMIN_TOKEN_LENGTH,T as MIN_AUTH_SECRET_LENGTH,a as buildSecurityAudit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";class e extends r{constructor(o="Document not found"){super("NOT_FOUND",o,{name:"NotFoundError"})}}export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as Be,aggregateSqlFunction as Ne,normalizeCountArgument as bt,throwingScheduler as yt}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as de,foldAggregateTally as _t,aggregateTableName as Te,coerceAggregateNumber as Fe,readAggregateValue as qe}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as oe,CountRlsUnsupportedError as Ue,selectIndexForGroupBy as Nt,selectIndexForCount as Tt,selectIndexForAggregate as Rt}from"./CountRlsUnsupportedError-Cl8XpYDL.mjs";import{appendCdcChange as St}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{CDC_LOG_TABLE as Qn,applyCdcChanges as Xn,bumpCdcEpoch as Zn,minCdcSeq as er,readCdcChanges as tr,readCdcCursor as nr,readCdcEpoch as rr,trimCdcChanges as ir}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{r as v}from"./do-exec-BLe9lLrN.mjs";import{N as st,s as X,L as fe,a as ce,d as te,m as Q,g as lt,p as Le,T as ee,u as At,E as dt,$ as Ye}from"./do-sql-BYIQTG3z.mjs";import{param as Ke}from"./renderSql-B5lF5Jd9.mjs";import{encodeGeohash as It,GEO_DEFAULT_PRECISION as vt,coveringGeohashes as kt,boundingBoxGeohashes as Mt,pointInBoundingBox as Lt,haversineMeters as xt}from"./GEO_DEFAULT_PRECISION-CWAm_oYY.mjs";import{sortColumnName as Se,matchesRankStaticWhere as ct,encodePartitionKey as De,rankTableName as Ae,resolveRankPartition as ft,RANK_TIEBREAK as we}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{stringifySearchText as ut,ftsTableName as ht,tokenizeSearch as $t,buildFtsMatch as Ct,scoreDocument as Dt}from"./buildFtsMatch-CV0Z7PWv.mjs";import{t as ue}from"./serialize-sql-DiRzL7A4.mjs";import{SCAN_DEP as Y}from"./SCAN_DEP-D_yR9EeV.mjs";import{decodeCursor as Ce,normalizeOrderKeys as Ot,buildSeekWhere as pt,applySelect as Qe,encodeCursor as Pe,softDeleteScope as Ee,buildSeekBeforeWhere as Wt}from"./applySelect-Bq2KOrkL.mjs";import Bt from"./NotFoundError-J3tjf4Uo.mjs";import{assertFlatPredicate as je,resolveRelationPredicates as Xe}from"./DEFAULT_MAX_RELATION_KEYS-BRdmX7WW.mjs";import{runRowValidators as He,resolveWith as Ze,applyOnDelete as Ft,fanOutScalarCounts as qt}from"./applyOnDelete-BvQN7pDL.mjs";import{guardWriter as Ut}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as jt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Ht}from"./hasTrigger-_rexbWMO.mjs";import{compileWhereSql as he}from"./compileWhereSql-BLcfs4QW.mjs";import{backfillAggregateIndexes as ar,backfillRankIndexes as sr}from"./backfillAggregateIndexes-BAQ3Fwwh.mjs";import{e as dr,t as cr,r as fr,o as ur,l as hr,p as $r,_ as pr,a as wr,b as mr,d as gr,m as Er,u as br,S as yr,T as _r}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{runShardMigrations as Tr}from"./runShardMigrations-bxOHpfID.mjs";import{a as Sr,s as Ar}from"./ctx-db-shapes-DzX_H5q8.mjs";const Pt=(i,o,n)=>[...i.partitionBy??[],...i.sortBy.map(s=>s.field),...i.where?Object.keys(i.where):[]].every(s=>o[s]===n[s]),Gt=(i,o,n,s,l,c)=>{if(l&&c&&Pt(n,l,c))return;const E=Ae(o,n.name);if(l&&v(i,t`DELETE FROM ${t.identifier(E)} WHERE ${t.identifier("__id__")} = ${s}`),!c||n.where&&!ct(c,n.where))return;const w=n.sortBy.map((u,S)=>Se(S)),_=t.join(["__id__","__partition__",...w].map(u=>t.identifier(u)),t`, `),T=De(n.partitionBy??[],c),k=n.sortBy.map(u=>ue(c[u.field]??null)),b=t.join([s,T,...k].map(u=>Ke(u)),t`, `);v(i,t`INSERT INTO ${t.identifier(E)} (${_}) VALUES (${b})`)},Kt=i=>{const{broadcast:o,invalidateCache:n,recordCdc:s,schema:l,sql:c}=i,E=new Set,w=new Set,_=(A,m)=>{const I=`${A}::${m.name}`;if(E.has(I))return;const F=Te(A,m.name),W=m.by??[],H=new Map,j=v(c,t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(A)}`).toArray();for(const q of j){const L=fe(q);if(!L||m.where&&!Be(L,m.where))continue;const P=de(W,L);_t(H,P,m,L)}v(c,t`DELETE FROM ${t.identifier(F)}`);const G=32,B=[...H];for(let q=0;q<B.length;q+=G){const L=B.slice(q,q+G),P=t.join(L.map(([U,V])=>t`(${U}, ${V.value}, ${V.count})`),t`, `);v(c,t`INSERT INTO ${t.identifier(F)} (${ce}, ${te}, ${Q}) VALUES ${P}`)}E.add(I)},T=(A,m,I)=>{const F=m.by??[],W=Ne(m.op),H=m.field??"",j=[];for(const q of F){const L=ue(I[q]??null);L===null?j.push(t`${ee(q)} IS NULL`):j.push(t`${ee(q)} = ${L}`)}for(const[q,L]of Object.entries(m.where??{})){const P=L!==null&&typeof L=="object"&&!Array.isArray(L)?L.eq:L,U=ue(P);U===null?j.push(t`${ee(q)} IS NULL`):j.push(t`${ee(q)} = ${U}`)}const G=j.length>0?t` WHERE ${t.join(j,t` AND `)}`:t``,B=ee(H);return{value:v(c,t`SELECT ${t.raw(W)}(${B}) AS value FROM ${t.identifier(A)}${G}`).one().value??null}},k=(A,m,I,F)=>{const W=Te(A,m.name),{op:H}=m,j=m.field??"",G=L=>{v(c,t`DELETE FROM ${t.identifier(W)} WHERE ${ce} = ${L} AND ${Q} <= 0`)},B=I&&(!m.where||Be(I,m.where))?I:void 0,q=F&&(!m.where||Be(F,m.where))?F:void 0;if(!(!B&&!q)){if(H==="count"){for(const[L,P]of[[B,-1],[q,1]]){if(!L)continue;const U=de(m.by??[],L);v(c,Le(W,U,P,P,t`${te} = ${te} + excluded.${te}, ${Q} = ${Q} + excluded.${Q}`))}B&&G(de(m.by??[],B));return}if(H==="sum"||H==="avg"){for(const[L,P]of[[B,-1],[q,1]]){if(!L)continue;const U=Fe(L[j]);if(U===void 0)continue;const V=de(m.by??[],L);v(c,Le(W,V,P*U,P,t`${te} = COALESCE(${te}, 0) + excluded.${te}, ${Q} = ${Q} + excluded.${Q}`))}B&&G(de(m.by??[],B));return}if(B){const L=de(m.by??[],B),P=Fe(B[j]),U=v(c,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(W)} WHERE ${ce} = ${L}`).toArray()[0],V=(U?.count??0)-1;if(V<=0)v(c,t`DELETE FROM ${t.identifier(W)} WHERE ${ce} = ${L}`);else if(U&&P!==void 0&&U.value!==null&&P===U.value){const re=T(A,m,B);v(c,t`UPDATE ${t.identifier(W)} SET ${te} = ${re.value}, ${Q} = ${V} WHERE ${ce} = ${L}`)}else v(c,t`UPDATE ${t.identifier(W)} SET ${Q} = ${Q} - 1 WHERE ${ce} = ${L}`)}if(q){const L=de(m.by??[],q),P=Fe(q[j]);if(P===void 0)v(c,Le(W,L,null,1,t`${Q} = ${Q} + 1`));else{const U=H==="min"?"MIN":"MAX";v(c,Le(W,L,P,1,t`${te} = ${t.raw(U)}(COALESCE(${te}, excluded.${te}), excluded.${te}), ${Q} = ${Q} + 1`))}}}},b=A=>{const m=l.tables[A]?.aggregateIndexes;if(!(!m||m.length===0))for(const I of m)_(A,I)},u=(A,m,I)=>{const F=l.tables[A]?.aggregateIndexes;if(!(!F||F.length===0))for(const W of F)k(A,W,m,I)},S=(A,m)=>{const I=`${A}::rank::${m.name}`;if(w.has(I))return;const F=Ae(A,m.name),W=v(c,t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(A)}`).toArray();v(c,t`DELETE FROM ${t.identifier(F)}`);const H=m.sortBy.map((G,B)=>Se(B)),j=t.join(["__id__","__partition__",...H].map(G=>t.identifier(G)),t`, `);for(const G of W){const B=fe(G);if(!B||m.where&&!ct(B,m.where))continue;const q=De(m.partitionBy??[],B),L=m.sortBy.map(U=>ue(B[U.field]??null)),P=t.join([B._id,q,...L].map(U=>Ke(U)),t`, `);v(c,t`INSERT INTO ${t.identifier(F)} (${j}) VALUES (${P})`)}w.add(I)},M=A=>{const m=l.tables[A]?.rankIndexes;if(!(!m||m.length===0))for(const I of m)S(A,I)},D=(A,m,I,F)=>{const W=l.tables[A]?.rankIndexes;if(!(!W||W.length===0))for(const H of W)Gt(c,A,H,m,I,F)},O=(A,m,I)=>{const F=l.tables[A]?.searchIndexes;if(!(!F||F.length===0||!st(c)))for(const W of F){const H=ht(A,W.name);v(c,t`DELETE FROM ${t.identifier(H)} WHERE ${t.identifier("__id__")} = ${m}`),I&&v(c,t`INSERT INTO ${t.identifier(H)} (${t.identifier("__text__")}, ${t.identifier("__id__")}) VALUES (${ut(I[W.field])}, ${m})`)}},Z=(A,m,I)=>{const F=l.tables[A]?.geoIndexes;if(!(!F||F.length===0))for(const W of F){const H=lt(A,W.name);v(c,t`DELETE FROM ${t.identifier(H)} WHERE ${t.identifier("__id__")} = ${m}`);const j=I?.[W.field];if(j!==null&&typeof j=="object"&&typeof j.lat=="number"&&typeof j.lng=="number"){const{lat:G,lng:B}=j,q=It({lat:G,lng:B},W.precision??vt);v(c,t`INSERT INTO ${t.identifier(H)} (${t.identifier("__id__")}, ${t.identifier("__geohash__")}, ${t.identifier("__lat__")}, ${t.identifier("__lng__")}) VALUES (${m}, ${q}, ${G}, ${B})`)}}};return{ensureBackfilledForTable:b,ensureBackfilledIndex:_,ensureRankBackfilled:S,ensureRankBackfilledForTable:M,syncAggregates:u,syncCompanionsForInsert:(A,m,I)=>{O(A,m,I),Z(A,m,I),u(A,void 0,I),D(A,m,void 0,I),n(A,m),s(A,m,"insert",I),o({key:m,op:"insert",row:I,table:A})},syncGeo:Z,syncRanks:D,syncSearch:O}},Vt="__doc__",Jt=i=>{const o=JSON.stringify(i),n=new TextEncoder().encode(o);let s="";for(const l of n)s+=String.fromCodePoint(l);return btoa(s)},zt=i=>i.after?[i.after.partitionKey,...i.after.sortValues,i.after.rowId]:i.cursor?Ce(i.cursor):void 0,Yt=(i,o,n)=>{if(i?.length!==1+o.length+1)return;const s=[{column:"__partition__",direction:"asc"}];for(const[c,E]of o.entries())s.push({column:E,direction:n[c]?.direction??"asc"});s.push({column:we,direction:"asc"});const l=[];for(const[c,E]of s.entries()){const w=[];for(const[T,k]of s.slice(0,c).entries())w.push(t`${t.identifier(k.column)} IS ${i[T]}`);w.push(t`${t.identifier(E.column)} ${t.raw(E.direction==="desc"?"<":">")} ${i[c]}`);const[_]=w;l.push(w.length===1&&_!==void 0?_:t`(${t.join(w,t` AND `)})`)}return t`(${t.join(l,t` OR `)})`},wt=null,Qt=(i,o)=>{if(i===void 0)return wt;const n=[i.__partition__,...o.map(s=>i[s]),i[we]];return Jt(n)},Xt=(i,o,n)=>{const s=[];for(const l of i){const c=l[we];if(typeof c!="string")continue;const E=o.get(c);if(!E)continue;const w=typeof l.__partition__=="string"?l.__partition__:"",_=n.map(T=>l[T]??null);s.push({doc:E,key:{partitionKey:w,rowId:c,sortValues:_}})}return s},Zt=(i,o,n)=>{const{rowToDocument:s}=i,l=new Map;if(n.length===0)return l;const c=t.join(n.map(w=>Ke(w)),t`, `),E=v(i.sql,t`SELECT id, _creationTime, ${t.identifier(Vt)} FROM ${t.identifier(o)} WHERE id IN (${c})`).toArray();for(const w of E){const _=s(w),T=w.id;_&&typeof T=="string"&&l.set(T,_)}return l},et=(i,o,n,s)=>{const{assertRankPartitionLocal:l,ensureRankBackfilled:c,onRead:E,schema:w}=i,_=w.tables[o];if(!_)throw new N("INTERNAL",`unknown table: ${o}`);const T=_.rankIndexes?.find(V=>V.name===n);if(!T)throw new N("INTERNAL",`unknown rankIndex "${n}" on table "${o}"`);l(o,_,T),E(o,Y),c(o,T);const k=Ae(o,T.name),b=T.sortBy.map((V,re)=>Se(re)),u=Math.max(1,Math.min(1e3,Math.floor(s.take??100))),S=oe(s.baseWhere,s.where),M=ft(T,S),D=[t`${t.identifier("__partition__")} ASC`];for(const[V,re]of b.entries()){const se=T.sortBy[V]?.direction;D.push(t`${t.identifier(re)} ${t.raw(se==="desc"?"DESC":"ASC")}`)}D.push(t`${t.identifier(we)} ASC`);const O=[];typeof s.partitionKey=="string"?O.push(t`${t.identifier("__partition__")} = ${s.partitionKey}`):M&&O.push(t`${t.identifier("__partition__")} = ${De(T.partitionBy??[],M)}`);const Z=zt(s),A=Yt(Z,b,T.sortBy);A&&O.push(A);const m=t.identifier(we),I=t.identifier("__partition__"),F=O.length>0?t` WHERE ${t.join(O,t` AND `)}`:t``,W=b.length>0?t`${m}, ${I}, ${t.join(b.map(V=>t.identifier(V)),t`, `)}`:t`${m}, ${I}`,H=t`SELECT ${W} FROM ${t.identifier(k)}${F} ORDER BY ${t.join(D,t`, `)} LIMIT ${t.raw(String(u+1))}`,j=v(i.sql,H).toArray(),G=j.length>u,B=G?j.slice(0,u):j,q=B.map(V=>V[we]),L=Xt(B,Zt(i,o,q),b),P=G?Qt(B.at(-1),b):wt,U=T.sortBy.map(V=>V.direction==="desc"?"desc":"asc");return{continueCursor:P,directions:U,hasMore:G,rows:L}},en=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,tn=i=>{if(!en.test(i))throw new N("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},tt=50,mt=500,ge=(i,o,n)=>{const s=o??mt;if(i>s)throw new N("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(i)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},nn=i=>{const o={eq:(n,s)=>(i.sqlConditions.push({comparator:"=",field:n,value:s}),o),gt:(n,s)=>(i.sqlConditions.push({comparator:">",field:n,value:s}),o),gte:(n,s)=>(i.sqlConditions.push({comparator:">=",field:n,value:s}),o),lt:(n,s)=>(i.sqlConditions.push({comparator:"<",field:n,value:s}),o),lte:(n,s)=>(i.sqlConditions.push({comparator:"<=",field:n,value:s}),o)};return o},rn=(i,o)=>{const n={eq:(s,l)=>{if(!i.definition.filterFields?.includes(s))throw new N("INTERNAL",`field "${s}" is not a filter field of search index "${i.indexName}" on table "${o}"`);return i.filters.push({field:s,value:l}),n},search:(s,l)=>{if(s!==i.definition.field)throw new N("INTERNAL",`search index "${i.indexName}" on table "${o}" indexes "${i.definition.field}", not "${s}"`);const c=i;return c.field=s,c.query=l,c.hasQuery=!0,n}};return n},on=(i,o,n,s,l)=>{const c=$t(n.query);if(c.length===0)return[];const E=ht(o,n.indexName),w=[t`f.${t.identifier("__text__")} MATCH ${Ct(c)}`];for(const b of n.filters)w.push(t`${ee(b.field)} = ${ue(b.value)}`);l&&w.push(l);let _=t`SELECT m.id, m._creationTime, m.${t.identifier(X)} FROM ${t.identifier(E)} f JOIN ${t.identifier(o)} m ON m.id = f.${t.identifier("__id__")} WHERE ${t.join(w,t` AND `)} ORDER BY f.rank, m._creationTime DESC`;typeof s=="number"&&(_=t`${_} LIMIT ${t.raw(String(Math.max(0,Math.floor(s))))}`);const T=v(i,_).toArray(),k=[];for(const b of T){const u=fe(b);u&&k.push(u)}return k},an=(i,o,n,s,l)=>{const c=$t(n.query);if(c.length===0)return[];const E=[];for(const b of n.filters)E.push(t`${ee(b.field)} = ${ue(b.value)}`);l&&E.push(l);let w=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;E.length>0&&(w=t`${w} WHERE ${t.join(E,t` AND `)}`);const _=v(i,w).toArray(),T=[];for(const b of _){const u=fe(b);if(!u)continue;const S=Dt(ut(u[n.field]),c);S>0&&T.push({creationTime:typeof u._creationTime=="number"?u._creationTime:0,doc:u,score:S})}T.sort((b,u)=>u.score-b.score||u.creationTime-b.creationTime);const k=T.map(b=>b.doc);return typeof s=="number"?k.slice(0,Math.max(0,Math.floor(s))):k},sn=(i,o)=>{const n=i,s={near:(l,c)=>{if(n.within)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.near={point:{lat:l.lat,lng:l.lng},radiusMeters:c},s},within:l=>{if(n.near)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.within={ne:{lat:l.ne.lat,lng:l.ne.lng},sw:{lat:l.sw.lat,lng:l.sw.lng}},s}};return s},ln=(i,o)=>{const n=i[o];if(n===null||typeof n!="object")return;const{lat:s,lng:l}=n;return typeof s=="number"&&typeof l=="number"?{lat:s,lng:l}:void 0},dn=(i,o)=>{const n=ln(i,o.definition.field);if(!n)return;const s=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const l=xt(o.near.point,n);return l<=o.near.radiusMeters?{creationTime:s,distance:l}:void 0}return Lt(n,o.within)?{creationTime:s,distance:0}:void 0},cn=(i,o,n,s,l)=>{if(!n.near&&!n.within)throw new N("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const c=n.near?kt(n.near.point,n.near.radiusMeters):Mt(n.within),E=lt(o,n.indexName),w=c.map(S=>t`(g.${t.identifier("__geohash__")} >= ${S} AND g.${t.identifier("__geohash__")} < ${`${S}{`})`),_=[t`(${t.join(w,t` OR `)})`];l&&_.push(l);const T=t`SELECT m.id, m._creationTime, m.${t.identifier(X)} FROM ${t.identifier(E)} g JOIN ${t.identifier(o)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(_,t` AND `)}`,k=v(i,T).toArray(),b=[];for(const S of k){const M=fe(S),D=M?dn(M,n):void 0;M&&D&&b.push({creationTime:D.creationTime,distance:D.distance,doc:M})}b.sort((S,M)=>S.distance-M.distance||M.creationTime-S.creationTime);const u=b.map(S=>S.doc);return typeof s=="number"?u.slice(0,Math.max(0,Math.floor(s))):u},fn=(i,o,n,s,l)=>{const{geo:c}=n;if(!c)throw new N("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,w=cn(i,o,c,E?void 0:l,s);if(!E)return w;const _=[];for(const T of w)if(n.inMemoryFilters.every(k=>k(T))&&(_.push(T),typeof l=="number"&&_.length>=l))break;return _},un=(i,o,n,s,l,c)=>{const E=[];for(const k of n.sqlConditions)E.push(t`${ee(k.field)} ${t.raw(k.comparator)} ${ue(k.value)}`);s&&E.push(s);let w=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;E.length>0&&(w=t`${w} WHERE ${t.join(E,t` AND `)}`),w=t`${w} ORDER BY ${l}`,typeof c=="number"&&n.inMemoryFilters.length===0&&(w=t`${w} LIMIT ${t.raw(String(Math.max(0,Math.floor(c))))}`);const _=v(i,w).toArray(),T=[];for(const k of _){const b=fe(k);if(b&&n.inMemoryFilters.every(u=>u(b))&&(T.push(b),typeof c=="number"&&T.length>=c))break}return T},pe={fieldRef:ee,serialize:ue},hn=i=>{let o=0;const n=[],s={fieldRef:ee,relationExists:l=>{const{childWhere:c,negated:E,parentTable:w,relation:_}=l,T=`__rel_${String(o)}`,k=n.at(-1)??w;o+=1,i(_.table,Y);const b=_.kind==="one"?_.field:_.references,u=_.kind==="one"?_.references:_.field,S=t`${Ye(T,u)} = ${Ye(k,b)}`;n.push(T);const M=he(c,s);n.pop();const D=M?t`${S} AND ${M}`:S,O=t`EXISTS (SELECT 1 FROM ${t.identifier(_.table)} AS ${t.identifier(T)} WHERE ${D})`;return E?t`NOT ${O}`:O},serialize:ue};return s},gt=i=>{const o=i.map(n=>t`${ee(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return i.some(n=>n.field==="_id"||n.field==="id")||o.push(t`${ee("id")} ASC`),t.join(o,t`, `)},$n={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},pn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(n=>({direction:o,field:n})):[{direction:o,field:"_creationTime"}]},wn=(i,o,n,s)=>{const l=i.sqlConditions.map(c=>({[c.field]:{[$n[c.comparator]??"eq"]:c.value}}));if(n&&l.push(pt(o,Ce(n))),s&&l.push(Wt(o,Ce(s))),l.length!==0)return l.length===1?l[0]:{AND:l}},mn=(i,o,n)=>{const s=[];for(const l of i){const c=fe(l);if(c&&o.every(E=>E(c))&&(s.push(c),n!==void 0&&s.length>n))break}return s},gn=(i,o,n,s,l)=>{const c=Math.max(0,Math.floor(s.numItems)),E=pn(n),w=typeof s.endCursor=="string",_=he(wn(n,E,s.cursor,s.endCursor),pe),T=l&&_?t`${_} AND ${l}`:l??_;let k=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(o)}`;T&&(k=t`${k} WHERE ${T}`),k=t`${k} ORDER BY ${gt(E)}`;const b=n.inMemoryFilters.length>0;!b&&!w&&(k=t`${k} LIMIT ${t.raw(String(c+1))}`);const u=v(i,k).toArray(),S=mn(u,n.inMemoryFilters,b||w?void 0:c);if(w){const Z=S.length>=2?S[Math.floor(S.length/2)-1]:void 0;return{continueCursor:s.endCursor??null,isDone:!0,page:S,splitCursor:Z?Pe(Z,E):null}}const M=S.length>c,D=M?S.slice(0,c):S,O=D.at(-1);return{continueCursor:M&&O?Pe(O,E):null,isDone:!M,page:D}};class En extends N{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const bn=/\s/u,yn=String.fromCodePoint(0),nt=(i,o,n)=>{if(!i.tables[o])throw new N("INTERNAL",`unknown table: ${o}`);return typeof n!="string"||n.length===0||bn.test(n)||n.includes(yn)?null:n},_n=(i,o,n,s=()=>{})=>{const l=o.tables[n];if(!l)throw new N("INTERNAL",`unknown table: ${n}`);const c=Ee(l.softDeleteMode,void 0),E=c?he(c,pe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},_=u=>{const{search:S}=w;if(!S)throw new N("INTERNAL","runSearchFetch called without a staged search");const M=w.inMemoryFilters.length>0,D=M?void 0:u,O=st(i)?on(i,n,S,D,E):an(i,n,S,D,E);if(!M)return O;const Z=[];for(const A of O)if(w.inMemoryFilters.every(m=>m(A))&&(Z.push(A),typeof u=="number"&&Z.length>=u))break;return Z},T=()=>{const u=w.indexFields.length>0?w.indexFields:["_creationTime"],S=w.order==="desc"?"DESC":"ASC";return t.join(u.map(M=>t`${ee(M)} ${t.raw(S)}`),t`, `)},k=u=>w.search?_(u):w.geo?fn(i,n,w,E,u):un(i,n,w,E,T(),u),b={async collect(){return k(void 0)},filter(u){return w.inMemoryFilters.push(u),b},async first(){return k(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(u){return w.order=u==="desc"?"desc":"asc",b},async paginate(u){if(w.search)throw new N("INTERNAL","pagination is not supported on search queries; use .take(n) or .collect()");if(w.geo)throw new N("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return gn(i,n,w,u,E)},async take(u){return k(u)},async unique(){const u=k(w.inMemoryFilters.length>0?void 0:2);if(u.length>1)throw new En(`unique() on table "${n}" matched ${String(u.length)} documents; expected at most one`);return u[0]??null},withGeoIndex(u,S){const M=(l.geoIndexes??[]).find(O=>O.name===u);if(!M)throw new N("INTERNAL",`unknown geo index "${u}" on table "${n}"`);s(n,u,"geo");const D={definition:M,indexName:u};if(w.geo=D,S(sn(D,n)),!D.near&&!D.within)throw new N("INTERNAL",`geo index "${u}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return b},withIndex(u,S){const M=l.indexes.find(D=>D.name===u);if(!M)throw new N("INTERNAL",`unknown index "${u}" on table "${n}"`);return s(n,u,"index"),w.indexName=u,w.indexFields=M.fields,S&&S(nn(w)),b},withSearchIndex(u,S){const M=(l.searchIndexes??[]).find(O=>O.name===u);if(!M)throw new N("INTERNAL",`unknown search index "${u}" on table "${n}"`);s(n,u,"search");const D={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:u,query:""};if(w.search=D,S(rn(D,n)),!D.hasQuery)throw new N("INTERNAL",`search index "${u}" on table "${n}" requires a .search(field, query) call`);return b}};return b},rt=(i,o,n)=>{const s={...o};for(const[l,c]of dt(i)){if(c.serverDefault){s[l]=c.serverDefault({auth:n});continue}s[l]===void 0&&(c.defaultFn?s[l]=c.defaultFn():"defaultValue"in c&&(s[l]=c.defaultValue))}return s},it=(i,o,n,s)=>{const l=n;for(const[c,E]of dt(i)){if(E.serverDefault){c in o&&(l[c]=E.serverDefault({auth:s}));continue}E.onUpdateFn&&!(c in o)&&(l[c]=E.onUpdateFn())}},ot=(i,o)=>{for(const n of Object.keys(o))if(o[n]===void 0)throw new N("INTERNAL",`Cannot ${i} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Nn=/unique constraint failed/i,Tn=i=>i instanceof Error&&Nn.test(i.message),Ge=(i,o,n)=>{try{v(i,n)}catch(s){throw Tn(s)?new Re(`unique constraint violation on "${o}"`,"unique"):s}},xe=(i,o,n)=>{if(Ge(i,o,n),v(i,t`SELECT changes() AS changed`).one().changed===0)throw new Re(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},at=(i,o,n,s,l,c,E)=>{const w=[];for(let b=0;b<n.length+1;b+=1){const u=[];for(let O=0;O<b;O+=1)u.push(t`${t.identifier(n[O])} IS ${c[O]}`);const S=n[b],M=s[b];if(S!==void 0&&M!==void 0){const O=M.direction==="desc"?">":"<";u.push(t`${t.identifier(S)} ${t.raw(O)} ${c[b]}`)}else u.push(t`${t.identifier(we)} < ${E}`);const[D]=u;w.push(u.length===1&&D!==void 0?D:t`(${t.join(u,t` AND `)})`)}const _=t.join(w,t` OR `),T=v(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l} AND (${_})`).one(),k=v(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l}`).one();return{before:T.c,total:k.c}},Jn=i=>{const{sql:o}=i,{schema:n}=i,s=i.broadcast??(()=>{}),l=i.onRead??(()=>{}),c=i.onIndexUse??(()=>{}),E=i.onWrite??(()=>{}),{cache:w}=i,_=i.clock??(()=>Date.now()),T=i.idGenerator??(()=>crypto.randomUUID()),k=i.scheduler??yt,{globalDb:b}=i,u=i.auth??{identity:null,userId:null},S=i.cdc??!1,M=k,D=jt({scheduler:typeof M.list=="function"&&typeof M.get=="function"?M:void 0,storage:i.storage}),O=(e,r,a,p)=>{S&&St(o,_(),e,r,a,p)},Z=e=>n.tables[e]?.shardMode?.kind==="global",A=(e,r)=>{if(Z(e)){if(!b)throw new N("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return b}return J},m=e=>A(e,"cascade"),I=(e,r)=>{if(Z(e)){if(!b)throw new N("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return b}},F=()=>b,W=(e,r)=>A(e,"relation load").findMany(e,r),H=(e,r)=>(Z(e)&&l(e,Y),W(e,r)),j=e=>!Z(e.table),G=i.relationExistsPushDown??"auto",B=G!=="never",{maxRelationKeys:q}=i,L=(e,r,a)=>Xe(e,{fetcher:H,maxRelationKeys:q,relationBaseWhere:a,schema:n,tableName:r}),P=async(e,r,a,p)=>{const $=I(e,"relation grouped count");if($)return l(e,Y),qt((C,ie)=>$.count(C,ie),e,r,a,p);const h=n.tables[e];if(!h)throw new N("INTERNAL",`unknown table: ${e}`);l(e,Y);const d=Ee(h.softDeleteMode,void 0),f={[r]:{in:a}},g=oe(oe(f,p),d),R=await L(g,e,void 0),y=he(R,pe),x=ee(r);let z=t`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;y&&(z=t`${z} WHERE ${y}`),z=t`${z} GROUP BY ${x}`;const K=v(o,z).toArray();return new Map(K.map(C=>[C.__fk__,C.count]))};let U=0;const V=new Set;for(const[e,r]of Object.entries(n.tables))for(const a of Object.values(r.triggerMap??{}))V.add(`${e} ${a.timing} ${a.op}`);const re=(e,r,a)=>V.has(`${e} ${r} ${a}`),se=async(e,r,a)=>{if(U+=1,U>tt)throw U-=1,new Re(`trigger recursion exceeded ${String(tt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Ht({ctx:Et,event:a,op:r,schema:n,tableName:a.table,timing:e})}finally{U-=1}},{ensureBackfilledForTable:be,ensureBackfilledIndex:Oe,ensureRankBackfilled:We,ensureRankBackfilledForTable:ye,syncAggregates:Ie,syncCompanionsForInsert:Ve,syncGeo:ve,syncRanks:_e,syncSearch:ke}=Kt({broadcast:s,invalidateCache:(e,r)=>w?.invalidate(e,r),recordCdc:O,schema:n,sql:o}),Je=(e,r,a)=>{const{shardMode:p}=r;if(p?.kind==="shardBy"&&!(p.field!==void 0&&(a.partitionBy??[]).includes(p.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${p.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},$e=(e,r)=>{const a=Object.entries(n.tables).filter(([,R])=>R.shardMode?.kind!=="global").map(([R])=>R).filter(R=>r===void 0||R===r);if(a.length===0)return;const p=a.map(R=>t`SELECT ${t.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(R)} WHERE id = ${e}`),$=t`${t.join(p,t` UNION ALL `)} LIMIT 1`,[h]=v(o,$).toArray();if(!h)return;const d=h.__t__,f=fe(h);if(typeof d!="string"||!f)return;const g=h[X];return{docJson:typeof g=="string"?g:JSON.stringify(g??{}),row:f,tableName:d}},ze={assertRankPartitionLocal:Je,ensureRankBackfilled:We,onRead:l,rowToDocument:fe,schema:n,sql:o},J={system:D,async aggregate(e,r){const a=I(e,"aggregate");if(a)return l(e,Y),a.aggregate(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return J.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new N("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);l(e,Y);const $=Ee(p.softDeleteMode,void 0),h=oe(oe(r.baseWhere,r.where),$),d=await L(h,e,r.relationBaseWhere),f=d!==h;if(p.aggregateIndexes&&!r.baseWhere&&!f&&!$){const K=Rt(p.aggregateIndexes,r.op,r.field,r.where);if(K){Oe(e,K.index);const C=de(K.index.by??[],K.key),ie=Te(e,K.index.name),ae=v(o,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)} WHERE ${ce} = ${C}`).toArray()[0];return qe(r.op,ae)}}const g=he(d,pe),R=Ne(r.op),y=ee(r.field);let x=t`SELECT ${t.raw(R)}(${y}) AS value FROM ${t.identifier(e)}`;return g&&(x=t`${x} WHERE ${g}`),v(o,x).toArray()[0]?.value??null},asId(e,r){const a=nt(n,e,r);if(a===null)throw new N("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=I(e,"count");if(a)return l(e,Y),a.count(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=bt(r);if($.restrictsCounts)throw new Ue(e);l(e,Y);const h=Ee(p.softDeleteMode,void 0),d=oe(oe($.baseWhere,$.where),h),f=await L(d,e,$.relationBaseWhere),g=f!==d;if(p.aggregateIndexes&&!$.baseWhere&&!g&&!h){const x=Tt(p.aggregateIndexes,$.where);if(x){Oe(e,x.index);const z=de(x.index.by??[],x.key),K=Te(e,x.index.name),C=v(o,t`SELECT ${te} AS value FROM ${t.identifier(K)} WHERE ${ce} = ${z}`).toArray();return C[0]===void 0?0:C[0].value??0}}const R=he(f,pe);let y=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return R&&(y=t`${y} WHERE ${R}`),v(o,y).one().count},async delete(e,r,a){const p=$e(e,r);if(!p){const y=r===void 0?F():void 0;y&&await y.delete(e,void 0,a);return}const{docJson:$,row:h,tableName:d}=p,f=n.tables[d],g=a?.hard===!0,R=!g&&f?.softDeleteMode?f.softDeleteMode.field:void 0;if(!(R&&h[R]!==null&&h[R]!==void 0)){if(re(d,"before","delete")&&await se("before","delete",{id:e,op:"delete",previous:h,table:d}),await Ft({deletedId:e,deletedReference:y=>h[y],findHolders:async(y,x,z)=>(await m(y).findMany(y,{includeDeleted:g,where:{[x]:z}})).page,onCascade:(y,x)=>m(y).delete(x,void 0,a),onRestrict:y=>{throw new Re(y,"restrict")},onSetNull:(y,x,z)=>m(y).patch(x,{[z]:null}),schema:n,tableName:d}),be(d),ye(d),R){const y={...h,[R]:_(),_id:e};xe(o,d,t`UPDATE ${t.identifier(d)} SET ${t.identifier(X)} = ${JSON.stringify(y)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,y),ve(d,e,void 0),Ie(d,h,y),_e(d,e,h,void 0),w?.invalidate(d,e),O(d,e,"update",y),s({key:e,op:"update",row:y,table:d}),re(d,"after","delete")&&await se("after","delete",{id:e,op:"delete",previous:h,table:d}),await E({id:e,op:"delete",table:d});return}xe(o,d,t`DELETE FROM ${t.identifier(d)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,void 0),ve(d,e,void 0),Ie(d,h,void 0),_e(d,e,h,void 0),w?.invalidate(d,e),O(d,e,"delete"),s({key:e,op:"delete",table:d}),re(d,"after","delete")&&await se("after","delete",{id:e,op:"delete",previous:h,table:d}),await E({id:e,op:"delete",table:d})}},async deleteAll(e,r){if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??mt),p=r?.hard===void 0?void 0:{hard:r.hard},$=Z(e)?void 0:e;let h=0;for(;;){const d=(await J.findMany(e,{limit:a})).page.map(f=>String(f._id));if(d.length===0)break;for(const f of d)await J.delete(f,$,p),h+=1;if(d.length<a)break}return{deleted:h}},async deleteMany(e,r,a){ge(e.length,r?.limit,"deleteMany");for(const p of e)await J.delete(p,a);return{deleted:e.length}},async deleteWhere(e,r,a){const p=I(e,"deleteWhere");let $;if(p)$=(await p.findMany(e,{where:r})).page.map(h=>String(h._id));else{if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);$=(await J.findMany(e,{where:r})).page.map(h=>String(h._id))}if(ge($.length,a?.limit,"deleteWhere"),J.deleteMany===void 0)throw new N("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return J.deleteMany($,a)},async findFirst(e,r={}){return(await J.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await J.findFirst(e,r);if(a===null)throw new Bt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=I(e,"findMany");if(a)return l(e,Y),a.findMany(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=!r.where&&!r.baseWhere;$?l(e,Y):l(e);const h=Ot(r.orderBy),d=r.cursor?pt(h,Ce(r.cursor)):void 0;let f=oe(r.baseWhere,r.where);f=oe(f,Ee(p.softDeleteMode,r.includeDeleted)),f=await Xe(f,{canPushExists:B?j:void 0,existsPushMode:G==="always"?"always":"auto",fetcher:H,maxRelationKeys:q,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),d&&(f=f?{AND:[f,d]}:d);const g=B?hn(l):pe,R=he(f,g);let y=t`SELECT id, _creationTime, ${t.identifier(X)} FROM ${t.identifier(e)}`;R&&(y=t`${y} WHERE ${R}`),y=t`${y} ORDER BY ${gt(h)}`;const x=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;x!==void 0&&(y=t`${y} LIMIT ${t.raw(String(x+1))}`);const z=v(o,y).toArray(),K=[];for(const le of z){const ne=fe(le);ne&&(K.push(ne),!$&&typeof ne._id=="string"&&l(e,ne._id))}if(x===void 0)return r.with&&await Ze({groupedCounter:P,fetcher:W,parents:K,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:Qe(K,r.select,r.with)};const C=K.length>x,ie=C?K.slice(0,x):K,ae=ie.at(-1);return r.with&&await Ze({fetcher:W,groupedCounter:P,parents:ie,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:C&&ae?Pe(ae,h):null,isDone:!C,page:Qe(ie,r.select,r.with)}},async get(e,r){const a=$e(e,r);if(!a){const p=r===void 0?F():void 0;return p?p.get(e):null}return l(a.tableName,e),a.row},async lookupById(e,r){const a=$e(e,r);return a?(l(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=I(e,"groupBy");if(a)return l(e,Y),a.groupBy(e,r);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);l(e,Y);const $=r.agg??{op:"count"};if(Ne($.op),$.op!=="count"&&!$.field)throw new N("INTERNAL",`groupBy(${e}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);const h=Ee(p.softDeleteMode,void 0),d=oe(oe(r.baseWhere,r.where),h),f=await L(d,e,r.relationBaseWhere),g=f!==d;if(p.aggregateIndexes&&!r.baseWhere&&!g&&!h){const C=Nt(p.aggregateIndexes,$.op,$.field,r.by,r.where);if(C){Oe(e,C.index);const ie=Te(e,C.index.name),ae=Object.keys(C.partial),le=[];if(ae.length===(C.index.by??[]).length&&ae.length>0){const me=de(C.index.by??[],C.partial),Me=v(o,t`SELECT ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)} WHERE ${ce} = ${me}`).toArray();return Me.length>0&&le.push({key:{...C.partial},value:qe($.op,Me[0])}),le}const ne=v(o,t`SELECT ${ce} AS key, ${te} AS value, ${Q} AS count FROM ${t.identifier(ie)}`).toArray();for(const me of ne){const Me=JSON.parse(me.key);le.push({key:Me,value:qe($.op,me)})}return le}}const R=he(f,pe),y=r.by.map(C=>t`${ee(C)} AS ${t.identifier(C)}`);if($.op==="count")y.push(t`COUNT(*) AS value`);else{const{field:C}=$;if(C===void 0)throw new N("INTERNAL",`groupBy(${e}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);y.push(t`${t.raw(Ne($.op))}(${ee(C)}) AS value`)}let x=t`SELECT ${t.join(y,t`, `)} FROM ${t.identifier(e)}`;R&&(x=t`${x} WHERE ${R}`),x=t`${x} GROUP BY ${t.join(r.by.map(C=>ee(C)),t`, `)}`;const z=v(o,x).toArray(),K=[];for(const C of z){const ie={};for(const le of r.by)ie[le]=C[le]??null;const{value:ae}=C;K.push({key:ie,value:ae==null?null:Number(ae)})}return K},async insert(e,r,a){const p=I(e,"insert");if(p){const R=await p.insert(e,r,a);return s({key:R,op:"insert",row:{...r,_id:R},table:e}),R}const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);const h=rt($,r,u);He($,h);let d;a?.clientId!==void 0?(tn(a.clientId),d=a.clientId):a?.allowExplicitId&&typeof h._id=="string"?d=h._id:d=T();const f=a?.allowExplicitId&&typeof h._creationTime=="number"?h._creationTime:_(),g={...h,_creationTime:f,_id:d};return re(e,"before","insert")&&await se("before","insert",{doc:{...g},id:d,op:"insert",table:e}),be(e),ye(e),Ge(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(X)}) VALUES (${d}, ${f}, ${JSON.stringify(g)})`),Ve(e,d,g),re(e,"after","insert")&&await se("after","insert",{doc:g,id:d,op:"insert",table:e}),await E({doc:g,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,r,a){if(ge(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const p=I(e,"insert");if(p){const f=[];for(const g of r){const R=await p.insert(e,g,{allowExplicitId:a?.allowExplicitId});s({key:R,op:"insert",row:{...g,_id:R},table:e}),f.push(R)}return f}const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);be(e),ye(e);const h=r.map(f=>{const g=rt($,f,u),R=a?.allowExplicitId===!0&&typeof g._id=="string"?g._id:T(),y=a?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:_();return{creationTime:y,document:{...g,_creationTime:y,_id:R},id:R}}),d=t.join(h.map(f=>t`(${f.id}, ${f.creationTime}, ${JSON.stringify(f.document)})`),t`, `);Ge(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(X)}) VALUES ${d}`);for(const{document:f,id:g}of h)Ve(e,g,f),await E({doc:f,id:g,op:"insert",table:e});return h.map(f=>f.id)},async insertMany(e,r,a){ge(r.length,a?.limit,"insertMany");const p=a?.skipDuplicates===!0,$=[];for(const h of r)try{$.push(await J.insert(e,h))}catch(d){if(p&&d instanceof Re&&d.kind==="unique")$.push(null);else throw d}return $},normalizeId(e,r){return nt(n,e,r)},async patch(e,r,a){const p=$e(e,a);if(!p){const R=a===void 0?F():void 0;if(R){await R.patch(e,r);return}throw new N("INTERNAL",`document not found: ${e}`)}const{docJson:$,row:h,tableName:d}=p,f=n.tables[d];if(!f)throw new N("INTERNAL",`unknown table: ${d}`);l(d,e),ot("patch",r);const g={...h,...r,_id:e};it(f,r,g,u),He(f,g),re(d,"before","update")&&await se("before","update",{doc:{...g},id:e,op:"update",previous:h,table:d}),be(d),ye(d),xe(o,d,t`UPDATE ${t.identifier(d)} SET ${t.identifier(X)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(X)} = ${$}`),ke(d,e,g),ve(d,e,g),Ie(d,h,g),_e(d,e,h,g),w?.invalidate(d,e),O(d,e,"update",g),s({key:e,op:"update",row:g,table:d}),re(d,"after","update")&&await se("after","update",{doc:g,id:e,op:"update",previous:h,table:d}),await E({doc:g,id:e,op:"update",table:d})},async patchMany(e,r,a){ge(e.length,r?.limit,"patchMany");for(const p of e)await J.patch(p.id,p.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const p=I(e,"patchWhere");let $;if(p)$=(await p.findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));else{if(!n.tables[e])throw new N("INTERNAL",`unknown table: ${e}`);$=(await J.findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}))}if(ge($.length,a?.limit,"patchWhere"),J.patchMany===void 0)throw new N("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await J.patchMany($,a),{patched:$.length}},query(e){const r=I(e,"query");return r?(l(e,Y),r.query(e)):(l(e,Y),_n(o,n,e,c))},async rank(e,r,a){const p=I(e,"rank");if(p)return l(e,Y),p.rank(e,r,a);c(e,r,"rank");const $=n.tables[e];if(!$)throw new N("INTERNAL",`unknown table: ${e}`);const h=$.rankIndexes?.find(ne=>ne.name===r);if(!h)throw new N("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Je(e,$,h),a.restrictsCounts)throw new Ue(e);l(e,Y),We(e,h);const d=typeof a.row=="string"?a.row:a.row._id;if(!d)return null;const f=Ae(e,h.name),g=h.sortBy.map((ne,me)=>Se(me)),R=g.map(ne=>At(ne)).join(", "),y=v(o,t`SELECT ${t.identifier("__partition__")}, ${t.raw(R)} FROM ${t.identifier(f)} WHERE ${t.identifier("__id__")} = ${d}`).toArray(),[x]=y;if(x===void 0)return null;let z=x.__partition__;const K=oe(a.baseWhere,a.where);je(K,n,e,"rank");const C=ft(h,K);if(C){const ne=De(h.partitionBy??[],C);if(ne!==z)return null;z=ne}const ie=g.map(ne=>x[ne]),{before:ae,total:le}=at(o,f,g,h.sortBy,z,ie,d);return{position:ae+1,total:le}},async rankBefore(e,r,a){if(Z(e))throw new N("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const p=n.tables[e];if(!p)throw new N("INTERNAL",`unknown table: ${e}`);const $=p.rankIndexes?.find(g=>g.name===r);if(!$)throw new N("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Ue(e);l(e,Y),We(e,$);const h=Ae(e,$.name),d=$.sortBy.map((g,R)=>Se(R)),f=$.sortBy.map((g,R)=>ue(a.sortValues[R]??null));return at(o,h,d,$.sortBy,a.partitionKey,f,a.rowId)},async rankPage(e,r,a={}){je(oe(a.baseWhere,a.where),n,e,"rankPage");const p=I(e,"rankPage");if(p)return l(e,Y),p.rankPage(e,r,a);c(e,r,"rank");const{continueCursor:$,hasMore:h,rows:d}=et(ze,e,r,a);return{continueCursor:$,isDone:!h,page:d.map(f=>f.doc)}},async rankPageRows(e,r,a={}){je(oe(a.baseWhere,a.where),n,e,"rankPage"),c(e,r,"rank");const{directions:p,hasMore:$,rows:h}=et(ze,e,r,a);return{directions:p,hasMore:$,rows:h}},async restore(e,r){const a=$e(e,r);if(!a){const h=r===void 0?F():void 0;if(h?.restore){await h.restore(e);return}throw new N("INTERNAL",`document not found: ${e}`)}const p=n.tables[a.tableName]?.softDeleteMode?.field;if(!p)throw new N("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const $=a.row[p]!==null&&a.row[p]!==void 0;await J.patch(e,{[p]:null},r),$&&_e(a.tableName,e,void 0,a.row)},async replace(e,r,a,p){const $=$e(e,a);if(!$){const x=a===void 0?F():void 0;if(x){await x.replace(e,r,void 0,p);return}throw new N("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:d,tableName:f}=$,g=n.tables[f];if(!g)throw new N("INTERNAL",`unknown table: ${f}`);ot("replace",r);const R=p?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:_(),y={...r,_creationTime:R,_id:e};it(g,r,y,u),He(g,y),re(f,"before","update")&&await se("before","update",{doc:{...y},id:e,op:"update",previous:d,table:f}),be(f),ye(f),xe(o,f,t`UPDATE ${t.identifier(f)} SET _creationTime = ${R}, ${t.identifier(X)} = ${JSON.stringify(y)} WHERE id = ${e} AND ${t.identifier(X)} = ${h}`),ke(f,e,y),ve(f,e,y),Ie(f,d,y),_e(f,e,d,y),w?.invalidate(f,e),O(f,e,"update",y),s({key:e,op:"update",row:y,table:f}),re(f,"after","update")&&await se("after","update",{doc:y,id:e,op:"update",previous:d,table:f}),await E({doc:y,id:e,op:"update",table:f})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,p=Object.entries(n.tables).filter(([f,g])=>r.has(f)||a!==void 0&&!a.includes(f)?!1:g.shardMode?.kind!=="global").map(([f])=>f);if(a!==void 0){for(const f of a)if(!n.tables[f])throw new N("INTERNAL",`wipeShard: unknown table: ${f}`)}const $={};let h=0;const{deleteAll:d}=J;if(d===void 0)throw new N("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of p){const g=await d(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});$[f]=g.deleted,h+=g.deleted}return{deleted:h,tables:$}}},Et={db:J,scheduler:k};return i.enforceRls===!0?Ut(J,n,(e,r)=>$e(e,r)?.tableName):J};export{Qn as CDC_LOG_TABLE,dr as CLIENT_WATERMARK_TABLE,cr as GLOBAL_SHAPE_SNAPSHOT_TABLE,fr as IDEMPOTENCY_TABLE,En as NotUniqueError,ur as advanceClientWatermark,Xn as applyCdcChanges,tn as assertValidClientId,ar as backfillAggregateIndexes,sr as backfillRankIndexes,Zn as bumpCdcEpoch,Jn as createShardCtxDb,hr as deleteGlobalShapeSnapshot,$r as deleteGlobalShapeSnapshotsForConnection,pr as migrateClientWatermark,wr as migrateGlobalShapeSnapshot,er as minCdcSeq,nt as normalizeIdStructurally,tr as readCdcChanges,nr as readCdcCursor,rr as readCdcEpoch,mr as readClientWatermark,gr as readGlobalShapeSnapshot,Er as readIdempotent,Tr as runShardMigrations,Sr as selectShapeMemberIds,Ar as selectShapeRows,ir as trimCdcChanges,br as trimIdempotent,yr as writeGlobalShapeSnapshot,_r as writeIdempotent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as f}from"./serialize-sql-DiRzL7A4.mjs";const l=(r,t)=>r<t?-1:r>t?1:0,a=Symbol("not-resolvable"),c=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},u=(r,t)=>{if(r.length===0)return"";const n={};for(const e of[...r].toSorted(l))n[e]=t[e]??null;return JSON.stringify(n)},_="__id__",k=r=>`__sort_k${String(r)}__`,b=(r,t)=>{for(const[n,e]of Object.entries(t)){const s=r[n];if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const o=Object.keys(e);if(o.length===1&&o[0]==="eq"){if(s!==e.eq)return!1;continue}return!1}if(s!==e)return!1}return!0},m=(r,t)=>{const n=r.partitionBy??[],e=t??{};for(const o of Object.keys(e))if(o==="AND"||o==="OR"||o==="NOT")return;const s={};for(const o of n)if(o in e){const i=c(e[o]);if(i===a)return;s[o]=i}else if(r.where&&o in r.where)s[o]=r.where[o];else return;return s},h=(r,t)=>`${r}__rank_${t}`,p=(r,t)=>({partitionKey:u(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(n=>f(t[n.field]??null))});export{_ as RANK_TIEBREAK,u as encodePartitionKey,b as matchesRankStaticWhere,p as rankKeyFromDoc,h as rankTableName,m as resolveRankPartition,k as sortColumnName};
|