@lunora/do 1.0.0-alpha.49 → 1.0.0-alpha.50

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 CHANGED
@@ -1714,7 +1714,7 @@ interface DatabaseWriterLike {
1714
1714
  * Delete many rows by id in one call (a loop over `delete()`). The returned
1715
1715
  * `deleted` is the number of ids **requested**, not rows actually removed (an
1716
1716
  * unknown/duplicate id is a silent no-op). **Atomic within a mutation** — the
1717
- * DO wraps a mutation's dispatch in a BEGIN/COMMIT span, so a mid-batch throw
1717
+ * DO wraps a mutation's dispatch in a storage transaction, so a mid-batch throw
1718
1718
  * rolls the whole mutation back. (An action has no transaction span — there,
1719
1719
  * the prior deletes persist; the in-memory test harness mirrors the span.) Rejects a batch larger than
1720
1720
  * `options.limit` (default {@link DEFAULT_BATCH_LIMIT}).
@@ -1733,7 +1733,7 @@ interface DatabaseWriterLike {
1733
1733
  * Delete every row matching `where` in one call. Matching rows are resolved
1734
1734
  * first, then each row is deleted through the single-row delete pipeline so
1735
1735
  * companions, CDC, and broadcast stay correct. **Atomic within a mutation** —
1736
- * the DO wraps a mutation's dispatch in a BEGIN/COMMIT span, so a mid-batch
1736
+ * the DO wraps a mutation's dispatch in a storage transaction, so a mid-batch
1737
1737
  * throw rolls the whole mutation back. (An action has no transaction span.)
1738
1738
  */
1739
1739
  deleteWhere?: (tableName: string, where: WhereInput, options?: {
@@ -1780,7 +1780,7 @@ interface DatabaseWriterLike {
1780
1780
  * `options.skipDuplicates: true` to turn UNIQUE-constraint breaches into
1781
1781
  * `null` results for that row instead of failing the whole batch.
1782
1782
  * **Atomic within a mutation** — the DO wraps a mutation's dispatch in a
1783
- * BEGIN/COMMIT span, so a mid-batch throw rolls the whole mutation back. (An
1783
+ * storage transaction, so a mid-batch throw rolls the whole mutation back. (An
1784
1784
  * action has no transaction span — there, the prior inserts persist; the
1785
1785
  * in-memory test harness mirrors the span.)
1786
1786
  * Rejects a batch larger than `options.limit` (default {@link DEFAULT_BATCH_LIMIT}).
@@ -1831,7 +1831,7 @@ interface DatabaseWriterLike {
1831
1831
  patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
1832
1832
  /**
1833
1833
  * Patch many rows by id in one call (a loop over `patch()`). **Atomic within a
1834
- * mutation** — the DO wraps a mutation's dispatch in a BEGIN/COMMIT span, so a
1834
+ * mutation** — the DO wraps a mutation's dispatch in a storage transaction, so a
1835
1835
  * mid-batch throw rolls the whole mutation back. (An action has no transaction
1836
1836
  * span — there, the prior patches persist; the in-memory test harness mirrors
1837
1837
  * the span.)
@@ -1856,7 +1856,7 @@ interface DatabaseWriterLike {
1856
1856
  * Matching rows are resolved first, then each row is patched through the
1857
1857
  * single-row patch pipeline so companions, CDC, and broadcast stay correct.
1858
1858
  * **Atomic within a mutation** — the DO wraps a mutation's dispatch in a
1859
- * BEGIN/COMMIT span, so a mid-batch throw rolls the whole mutation back. (An
1859
+ * storage transaction, so a mid-batch throw rolls the whole mutation back. (An
1860
1860
  * action has no transaction span.)
1861
1861
  */
1862
1862
  patchWhere?: (tableName: string, args: {
@@ -2323,6 +2323,22 @@ interface MetricEvent {
2323
2323
  */
2324
2324
  value: number;
2325
2325
  }
2326
+ /** One eval verdict to turn into `gen_ai.evaluation.*` attributes. */
2327
+ interface EvaluationInput {
2328
+ /**
2329
+ * Optional categorical label (e.g. `"pass"` / `"fail"` / a rubric bucket),
2330
+ * emitted as the `.label` attribute. Omitted → no label attribute.
2331
+ */
2332
+ label?: string;
2333
+ /**
2334
+ * The scorer/evaluation name — becomes the key's name segment. Any character
2335
+ * outside `[A-Za-z0-9._-]` is replaced with `_` so a scorer name carrying a
2336
+ * colon (e.g. `"contains:shipped"`) still yields a well-formed attribute key.
2337
+ */
2338
+ name: string;
2339
+ /** The numeric score (typically `[0, 1]`), emitted as the `.score` attribute. */
2340
+ score: number;
2341
+ }
2326
2342
  /**
2327
2343
  * Severity of a `ctx.log.*` call. The five console method names (`log` is the
2328
2344
  * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
@@ -2474,6 +2490,16 @@ interface SpanHandle {
2474
2490
  * collapsing every producer into one giant trace.
2475
2491
  */
2476
2492
  addLink: (link: SpanLink) => void;
2493
+ /**
2494
+ * Attach an AI **evaluation** verdict to this (generation) span as the
2495
+ * `gen_ai.evaluation.<name>.score` / `.label` OpenTelemetry attributes, so a
2496
+ * scorer's grade rides the same trace as the generation it graded and the
2497
+ * collector reads it straight off the span. Convenience over
2498
+ * {@link SpanHandle.setAttributes} that owns the key format; privacy-safe —
2499
+ * only the name, score, and optional label are emitted, never the graded
2500
+ * prompt or completion. Throws on an empty name or a non-finite score.
2501
+ */
2502
+ recordEvaluation: (evaluation: EvaluationInput) => void;
2477
2503
  /**
2478
2504
  * Record a caught exception as the OTel-conventional `exception` span event
2479
2505
  * (`exception.type` / `exception.message` / `exception.stacktrace`).
@@ -4754,9 +4780,9 @@ interface ShardDOState {
4754
4780
  /**
4755
4781
  * Concurrency-blocking gate — `state.blockConcurrencyWhile(fn)` delays
4756
4782
  * the next fetch dispatch until `fn` resolves. Used by
4757
- * {@link ShardDO.runInTransaction} to serialize the BEGIN/COMMIT span
4758
- * against concurrent RPCs so a raw-SQL transaction is isolated from
4759
- * other in-flight handlers on the same DO.
4783
+ * {@link ShardDO.runInTransaction} to serialize the whole transaction span
4784
+ * against concurrent RPCs, so the handler's reads and writes are isolated
4785
+ * from other in-flight handlers on the same DO.
4760
4786
  */
4761
4787
  blockConcurrencyWhile?: <T>(callback: () => Promise<T>) => Promise<T>;
4762
4788
  getWebSockets: (tag?: string) => WebSocket[];
@@ -4793,9 +4819,9 @@ interface ShardDOState {
4793
4819
  */
4794
4820
  readonly databaseSize?: number;
4795
4821
  /**
4796
- * Run a SQL statement without parameters used by the
4797
- * transaction helper for BEGIN / COMMIT / ROLLBACK. The runtime
4798
- * exposes this as `state.storage.sql.exec(...)`.
4822
+ * Run a SQL statement without parameters. The runtime exposes this as
4823
+ * `state.storage.sql.exec(...)`; {@link ShardDO.runInTransaction} also
4824
+ * probes for it to confirm the handler will have a SQL connection.
4799
4825
  */
4800
4826
  exec?: (query: string) => unknown;
4801
4827
  };
@@ -5108,7 +5134,7 @@ declare abstract class ShardDO {
5108
5134
  */
5109
5135
  private drizzleHandle;
5110
5136
  /**
5111
- * Tracks BEGIN/COMMIT nesting so we can reject nested transactions —
5137
+ * Tracks transaction nesting so we can reject nested transactions —
5112
5138
  * SQLite-in-DO does not support them and the runtime would crash with
5113
5139
  * "cannot start a transaction within a transaction".
5114
5140
  */
@@ -5589,31 +5615,28 @@ declare abstract class ShardDO {
5589
5615
  * loudly rather than silently flattening them.
5590
5616
  *
5591
5617
  * Drizzle queries issued via `db` inside the handler participate
5592
- * in this transaction implicitly — drizzle and the BEGIN/COMMIT below
5593
- * both write through the same `state.storage.sql` handle, so the tx
5594
- * boundary is shared. Do **not** call `this.db.transaction(...)` from
5595
- * inside a handler; that would attempt a nested SQLite transaction.
5596
- *
5597
- * Why raw BEGIN/COMMIT/ROLLBACK strings instead of `this.db.transaction(handler)`?
5598
- * Two reasons, both verified against drizzle-orm 0.45.2's
5599
- * `durable-sqlite/session.js`:
5600
- *
5601
- * 1. The DO driver does NOT issue BEGIN/COMMIT/ROLLBACK SQL it
5602
- * delegates to `state.storage.transactionSync(callback)`, the
5603
- * DO platform's native transaction primitive. Swapping in
5604
- * `db.transaction()` would silently change the wire-level
5605
- * contract observed by tests and any tooling that intercepts
5606
- * `storage.sql`.
5607
- *
5608
- * 2. `transactionSync` invokes the callback synchronously and does
5609
- * not await its return value. Drizzle's `transaction()` matches
5610
- * that — it passes the tx handle through and then returns.
5611
- * Handing it an async handler would let the transaction commit
5612
- * before the handler resolves, breaking the `() => Promise&lt;T> | T`
5613
- * contract.
5614
- *
5615
- * The raw-SQL approach below is async-safe and gives the
5616
- * connection-scoped semantics SQLite-in-DO is designed for.
5618
+ * in this transaction implicitly — drizzle writes through the same
5619
+ * `state.storage.sql` handle the transaction below is opened on, and that
5620
+ * transaction is connection-scoped, so the boundary is shared without any
5621
+ * handle being threaded through. Do **not** call `this.db.transaction(...)`
5622
+ * from inside a handler; that would attempt a nested SQLite transaction.
5623
+ *
5624
+ * Why `state.storage.transaction(closure)` and not raw BEGIN/COMMIT SQL, and
5625
+ * not `this.db.transaction(handler)` either:
5626
+ *
5627
+ * 1. workerd FORBIDS raw `BEGIN`/`COMMIT`/`SAVEPOINT` inside a Durable Object
5628
+ * it answers "please use the state.storage.transaction() … APIs
5629
+ * instead", so issuing them fails every transactional mutation. (An
5630
+ * earlier revision of this method did use raw SQL; do not go back.)
5631
+ *
5632
+ * 2. `transactionSync` is synchronous: it invokes the callback and does not
5633
+ * await its return value, so an async handler would let the transaction
5634
+ * commit before the handler resolves. Drizzle's `db.transaction()` has the
5635
+ * same shape and the same problem.
5636
+ *
5637
+ * The async `state.storage.transaction(closure)` is the platform primitive
5638
+ * that fits: atomic, rolled back automatically when the closure throws, and
5639
+ * isolated from concurrent dispatch.
5617
5640
  */
5618
5641
  protected runInTransaction<T>(handler: () => Promise<T> | T): Promise<T>;
5619
5642
  /**
@@ -7812,9 +7835,13 @@ declare class ConflictError extends LunoraError {
7812
7835
  }
7813
7836
  /**
7814
7837
  * Minimal projection of the SQLite handle that the transaction helper needs.
7815
- * `state.storage.sql` in the Workers runtime exposes a query runner for
7816
- * BEGIN / COMMIT / ROLLBACK; declared structurally so unit tests can pass a
7817
- * stub without depending on the workers runtime.
7838
+ *
7839
+ * `ShardDO.runInTransaction` uses it as an availability probe: the transaction
7840
+ * itself is opened with `state.storage.transaction(closure)` (workerd forbids raw
7841
+ * BEGIN/COMMIT inside a Durable Object), but a handler's SQL still needs a
7842
+ * connection, so a state whose `storage.sql` has no `exec` is rejected up front
7843
+ * rather than failing mid-transaction. Declared structurally so unit tests can
7844
+ * pass a stub without depending on the workers runtime.
7818
7845
  */
7819
7846
  interface TransactionSqlLike {
7820
7847
  exec: (query: string) => unknown;
package/dist/index.d.ts CHANGED
@@ -1714,7 +1714,7 @@ interface DatabaseWriterLike {
1714
1714
  * Delete many rows by id in one call (a loop over `delete()`). The returned
1715
1715
  * `deleted` is the number of ids **requested**, not rows actually removed (an
1716
1716
  * unknown/duplicate id is a silent no-op). **Atomic within a mutation** — the
1717
- * DO wraps a mutation's dispatch in a BEGIN/COMMIT span, so a mid-batch throw
1717
+ * DO wraps a mutation's dispatch in a storage transaction, so a mid-batch throw
1718
1718
  * rolls the whole mutation back. (An action has no transaction span — there,
1719
1719
  * the prior deletes persist; the in-memory test harness mirrors the span.) Rejects a batch larger than
1720
1720
  * `options.limit` (default {@link DEFAULT_BATCH_LIMIT}).
@@ -1733,7 +1733,7 @@ interface DatabaseWriterLike {
1733
1733
  * Delete every row matching `where` in one call. Matching rows are resolved
1734
1734
  * first, then each row is deleted through the single-row delete pipeline so
1735
1735
  * companions, CDC, and broadcast stay correct. **Atomic within a mutation** —
1736
- * the DO wraps a mutation's dispatch in a BEGIN/COMMIT span, so a mid-batch
1736
+ * the DO wraps a mutation's dispatch in a storage transaction, so a mid-batch
1737
1737
  * throw rolls the whole mutation back. (An action has no transaction span.)
1738
1738
  */
1739
1739
  deleteWhere?: (tableName: string, where: WhereInput, options?: {
@@ -1780,7 +1780,7 @@ interface DatabaseWriterLike {
1780
1780
  * `options.skipDuplicates: true` to turn UNIQUE-constraint breaches into
1781
1781
  * `null` results for that row instead of failing the whole batch.
1782
1782
  * **Atomic within a mutation** — the DO wraps a mutation's dispatch in a
1783
- * BEGIN/COMMIT span, so a mid-batch throw rolls the whole mutation back. (An
1783
+ * storage transaction, so a mid-batch throw rolls the whole mutation back. (An
1784
1784
  * action has no transaction span — there, the prior inserts persist; the
1785
1785
  * in-memory test harness mirrors the span.)
1786
1786
  * Rejects a batch larger than `options.limit` (default {@link DEFAULT_BATCH_LIMIT}).
@@ -1831,7 +1831,7 @@ interface DatabaseWriterLike {
1831
1831
  patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
1832
1832
  /**
1833
1833
  * Patch many rows by id in one call (a loop over `patch()`). **Atomic within a
1834
- * mutation** — the DO wraps a mutation's dispatch in a BEGIN/COMMIT span, so a
1834
+ * mutation** — the DO wraps a mutation's dispatch in a storage transaction, so a
1835
1835
  * mid-batch throw rolls the whole mutation back. (An action has no transaction
1836
1836
  * span — there, the prior patches persist; the in-memory test harness mirrors
1837
1837
  * the span.)
@@ -1856,7 +1856,7 @@ interface DatabaseWriterLike {
1856
1856
  * Matching rows are resolved first, then each row is patched through the
1857
1857
  * single-row patch pipeline so companions, CDC, and broadcast stay correct.
1858
1858
  * **Atomic within a mutation** — the DO wraps a mutation's dispatch in a
1859
- * BEGIN/COMMIT span, so a mid-batch throw rolls the whole mutation back. (An
1859
+ * storage transaction, so a mid-batch throw rolls the whole mutation back. (An
1860
1860
  * action has no transaction span.)
1861
1861
  */
1862
1862
  patchWhere?: (tableName: string, args: {
@@ -2323,6 +2323,22 @@ interface MetricEvent {
2323
2323
  */
2324
2324
  value: number;
2325
2325
  }
2326
+ /** One eval verdict to turn into `gen_ai.evaluation.*` attributes. */
2327
+ interface EvaluationInput {
2328
+ /**
2329
+ * Optional categorical label (e.g. `"pass"` / `"fail"` / a rubric bucket),
2330
+ * emitted as the `.label` attribute. Omitted → no label attribute.
2331
+ */
2332
+ label?: string;
2333
+ /**
2334
+ * The scorer/evaluation name — becomes the key's name segment. Any character
2335
+ * outside `[A-Za-z0-9._-]` is replaced with `_` so a scorer name carrying a
2336
+ * colon (e.g. `"contains:shipped"`) still yields a well-formed attribute key.
2337
+ */
2338
+ name: string;
2339
+ /** The numeric score (typically `[0, 1]`), emitted as the `.score` attribute. */
2340
+ score: number;
2341
+ }
2326
2342
  /**
2327
2343
  * Severity of a `ctx.log.*` call. The five console method names (`log` is the
2328
2344
  * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
@@ -2474,6 +2490,16 @@ interface SpanHandle {
2474
2490
  * collapsing every producer into one giant trace.
2475
2491
  */
2476
2492
  addLink: (link: SpanLink) => void;
2493
+ /**
2494
+ * Attach an AI **evaluation** verdict to this (generation) span as the
2495
+ * `gen_ai.evaluation.<name>.score` / `.label` OpenTelemetry attributes, so a
2496
+ * scorer's grade rides the same trace as the generation it graded and the
2497
+ * collector reads it straight off the span. Convenience over
2498
+ * {@link SpanHandle.setAttributes} that owns the key format; privacy-safe —
2499
+ * only the name, score, and optional label are emitted, never the graded
2500
+ * prompt or completion. Throws on an empty name or a non-finite score.
2501
+ */
2502
+ recordEvaluation: (evaluation: EvaluationInput) => void;
2477
2503
  /**
2478
2504
  * Record a caught exception as the OTel-conventional `exception` span event
2479
2505
  * (`exception.type` / `exception.message` / `exception.stacktrace`).
@@ -4754,9 +4780,9 @@ interface ShardDOState {
4754
4780
  /**
4755
4781
  * Concurrency-blocking gate — `state.blockConcurrencyWhile(fn)` delays
4756
4782
  * the next fetch dispatch until `fn` resolves. Used by
4757
- * {@link ShardDO.runInTransaction} to serialize the BEGIN/COMMIT span
4758
- * against concurrent RPCs so a raw-SQL transaction is isolated from
4759
- * other in-flight handlers on the same DO.
4783
+ * {@link ShardDO.runInTransaction} to serialize the whole transaction span
4784
+ * against concurrent RPCs, so the handler's reads and writes are isolated
4785
+ * from other in-flight handlers on the same DO.
4760
4786
  */
4761
4787
  blockConcurrencyWhile?: <T>(callback: () => Promise<T>) => Promise<T>;
4762
4788
  getWebSockets: (tag?: string) => WebSocket[];
@@ -4793,9 +4819,9 @@ interface ShardDOState {
4793
4819
  */
4794
4820
  readonly databaseSize?: number;
4795
4821
  /**
4796
- * Run a SQL statement without parameters used by the
4797
- * transaction helper for BEGIN / COMMIT / ROLLBACK. The runtime
4798
- * exposes this as `state.storage.sql.exec(...)`.
4822
+ * Run a SQL statement without parameters. The runtime exposes this as
4823
+ * `state.storage.sql.exec(...)`; {@link ShardDO.runInTransaction} also
4824
+ * probes for it to confirm the handler will have a SQL connection.
4799
4825
  */
4800
4826
  exec?: (query: string) => unknown;
4801
4827
  };
@@ -5108,7 +5134,7 @@ declare abstract class ShardDO {
5108
5134
  */
5109
5135
  private drizzleHandle;
5110
5136
  /**
5111
- * Tracks BEGIN/COMMIT nesting so we can reject nested transactions —
5137
+ * Tracks transaction nesting so we can reject nested transactions —
5112
5138
  * SQLite-in-DO does not support them and the runtime would crash with
5113
5139
  * "cannot start a transaction within a transaction".
5114
5140
  */
@@ -5589,31 +5615,28 @@ declare abstract class ShardDO {
5589
5615
  * loudly rather than silently flattening them.
5590
5616
  *
5591
5617
  * Drizzle queries issued via `db` inside the handler participate
5592
- * in this transaction implicitly — drizzle and the BEGIN/COMMIT below
5593
- * both write through the same `state.storage.sql` handle, so the tx
5594
- * boundary is shared. Do **not** call `this.db.transaction(...)` from
5595
- * inside a handler; that would attempt a nested SQLite transaction.
5596
- *
5597
- * Why raw BEGIN/COMMIT/ROLLBACK strings instead of `this.db.transaction(handler)`?
5598
- * Two reasons, both verified against drizzle-orm 0.45.2's
5599
- * `durable-sqlite/session.js`:
5600
- *
5601
- * 1. The DO driver does NOT issue BEGIN/COMMIT/ROLLBACK SQL it
5602
- * delegates to `state.storage.transactionSync(callback)`, the
5603
- * DO platform's native transaction primitive. Swapping in
5604
- * `db.transaction()` would silently change the wire-level
5605
- * contract observed by tests and any tooling that intercepts
5606
- * `storage.sql`.
5607
- *
5608
- * 2. `transactionSync` invokes the callback synchronously and does
5609
- * not await its return value. Drizzle's `transaction()` matches
5610
- * that — it passes the tx handle through and then returns.
5611
- * Handing it an async handler would let the transaction commit
5612
- * before the handler resolves, breaking the `() => Promise&lt;T> | T`
5613
- * contract.
5614
- *
5615
- * The raw-SQL approach below is async-safe and gives the
5616
- * connection-scoped semantics SQLite-in-DO is designed for.
5618
+ * in this transaction implicitly — drizzle writes through the same
5619
+ * `state.storage.sql` handle the transaction below is opened on, and that
5620
+ * transaction is connection-scoped, so the boundary is shared without any
5621
+ * handle being threaded through. Do **not** call `this.db.transaction(...)`
5622
+ * from inside a handler; that would attempt a nested SQLite transaction.
5623
+ *
5624
+ * Why `state.storage.transaction(closure)` and not raw BEGIN/COMMIT SQL, and
5625
+ * not `this.db.transaction(handler)` either:
5626
+ *
5627
+ * 1. workerd FORBIDS raw `BEGIN`/`COMMIT`/`SAVEPOINT` inside a Durable Object
5628
+ * it answers "please use the state.storage.transaction() … APIs
5629
+ * instead", so issuing them fails every transactional mutation. (An
5630
+ * earlier revision of this method did use raw SQL; do not go back.)
5631
+ *
5632
+ * 2. `transactionSync` is synchronous: it invokes the callback and does not
5633
+ * await its return value, so an async handler would let the transaction
5634
+ * commit before the handler resolves. Drizzle's `db.transaction()` has the
5635
+ * same shape and the same problem.
5636
+ *
5637
+ * The async `state.storage.transaction(closure)` is the platform primitive
5638
+ * that fits: atomic, rolled back automatically when the closure throws, and
5639
+ * isolated from concurrent dispatch.
5617
5640
  */
5618
5641
  protected runInTransaction<T>(handler: () => Promise<T> | T): Promise<T>;
5619
5642
  /**
@@ -7812,9 +7835,13 @@ declare class ConflictError extends LunoraError {
7812
7835
  }
7813
7836
  /**
7814
7837
  * Minimal projection of the SQLite handle that the transaction helper needs.
7815
- * `state.storage.sql` in the Workers runtime exposes a query runner for
7816
- * BEGIN / COMMIT / ROLLBACK; declared structurally so unit tests can pass a
7817
- * stub without depending on the workers runtime.
7838
+ *
7839
+ * `ShardDO.runInTransaction` uses it as an availability probe: the transaction
7840
+ * itself is opened with `state.storage.transaction(closure)` (workerd forbids raw
7841
+ * BEGIN/COMMIT inside a Durable Object), but a handler's SQL still needs a
7842
+ * connection, so a state whose `storage.sql` has no `exec` is rejected up front
7843
+ * rather than failing mid-transaction. Declared structurally so unit tests can
7844
+ * pass a stub without depending on the workers runtime.
7818
7845
  */
7819
7846
  interface TransactionSqlLike {
7820
7847
  exec: (query: string) => unknown;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
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-BQoMfXLz.mjs";import{NotUniqueError as v,assertValidClientId as H,createShardCtxDb as w,normalizeIdStructurally as q}from"./packem_shared/NotUniqueError-GI79LNJB.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-okRCkZ6r.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-DqqGF-jB.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};
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-BFO0N_e4.mjs";import{NotUniqueError as v,assertValidClientId as H,createShardCtxDb as w,normalizeIdStructurally as q}from"./packem_shared/NotUniqueError-GI79LNJB.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-okRCkZ6r.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-oZjI_5uF.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};
@@ -1,4 +1,4 @@
1
- import{LunoraError as f,toErrorBody as C}from"@lunora/errors";import{drizzle as gt}from"drizzle-orm/durable-sqlite";import{c as j}from"./constant-time-equal-BVG05Guz.mjs";import{j as y}from"./json-response-wrh9TBPw.mjs";import{O as St,t as bt,n as Ie,r as K,A as Et,a as wt,b as Rt,c as Tt,d as vt,w as se,e as At}from"./context-telemetry-BQoMfXLz.mjs";import{f as w,c as O}from"./wire-codec-Ctnni0h6.mjs";import{parseExportShardArgs as It,parseImportShardArgs as _t}from"./exportShardRows-kt42wijd.mjs";import{recordAuthEvent as kt,readAuthMetrics as Mt}from"./AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{DATA_MIGRATION_STATE_TABLE as Nt,readMigrationStatus as Ct}from"./DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as _e,createDependencyTracker as Ot,tableFromDepKey as Lt}from"./SCAN_DEP-D_yR9EeV.mjs";import{readFunctionMetricsTotals as xt,readFunctionMetricIndexHits as $t,recordFunctionMetric as Pt,mergeScanAttribution as qt,readFunctionMetrics as Dt,readFunctionMetricBuckets as Ut}from"./FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{createFanoutCounters as ke,ADMIN_FUNCTION_PREFIX as k,RELATION_FUNCTION_PREFIX as Bt,selectMatchingIds as Ft,ADMIN_FUNCTIONS as h,findStorageReferences as Wt,listTables as Kt,summarizeSubscriptions as Ht,summarizeFanoutTopics as Qt,readTablePage as Gt,facetColumn as zt,FLAGS_FUNCTION_PREFIX as jt,recordFanoutPass as re,MAX_PAGE_SIZE as Jt}from"./ADMIN_FUNCTIONS-PxZ8Lr9e.mjs";import{LogBuffer as Xt}from"./LogBuffer-bIvCelI-.mjs";import{recordCapturedMail as Me,clearCapturedMail as Yt,readCapturedMail as Vt,MAIL_TABLE as Zt}from"./MAIL_RETENTION-KmozO2NQ.mjs";import{stableStringify as Ee}from"./stableStringify-BjLh4gvA.mjs";import{readBookmark as es,armRestore as ts}from"./armRestore-BNzdvQ_o.mjs";import{ReactiveCache as ss,reactiveCacheKey as Ne}from"./ReactiveCache-1_9Rs7J_.mjs";import{stableWireKey as $}from"./stableWireKey-YEHLaX6X.mjs";import{awaitWsDrain as M,trySendFrame as L,subscriptionListDeltas as rs,sendDeltaFrames as as}from"./subscriptionListDeltas-Bs69JbA8.mjs";import{fingerprintError as ns}from"@lunora/fingerprint";import{redact as is,standardRules as os}from"@visulima/redact";import{R as Ce,E as cs,_ as ds}from"./security-audit-BKUOgE0x.mjs";import{runReadonlySql as us}from"./MAX_SQL_ROWS-Bdu25ASB.mjs";import{ConflictError as ls}from"./ConflictError-C8GtJmjS.mjs";import{selectExpiredIds as hs}from"./selectExpiredIds-BGVP3d8-.mjs";import{p as ps,m as fs,T as ms,u as ys,b as ae,_ as gs,o as Ss,l as bs,d as Es,S as ws}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{CDC_LOG_TABLE as Oe,readCdcChanges as ne,readCdcCursor as Le,readCdcEpoch as xe,minCdcSeq as $e,bumpCdcEpoch as Rs}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{a as Ts,s as vs}from"./ctx-db-shapes-DzX_H5q8.mjs";const Pe=500,J=(a,e)=>{if(a.size<e)return;const t=a.keys().next().value;t!==void 0&&a.delete(t)},at=new TextEncoder,As=a=>{const e=a.replaceAll("-","+").replaceAll("_","/")+"===".slice((a.length+3)%4),t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)s[r]=t.codePointAt(r)??0;return s},Is=64,ie=new Map,_s=async a=>{const e=ie.get(a);if(e)return e;J(ie,Is);const t=crypto.subtle.importKey("raw",at.encode(a),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return ie.set(a,t),t},ks=async(a,e,t)=>{const s=await _s(a);return crypto.subtle.verify("HMAC",s,t,at.encode(e))},Ms="v1",Ns=async(a,e,t=Date.now())=>{if(a.length===0||e.length===0)return!1;const s=e.split(".");if(s.length!==3)return!1;const[r,n,i]=s;if(r!==Ms||i.length===0)return!1;const o=Number(n);if(!Number.isFinite(o)||o<=t)return!1;let c;try{c=As(i)}catch{return!1}return ks(a,`${r}.${n}`,c)},q="__lunora_audit__",X=(a,e,...t)=>a.exec.call(a,e,...t),we=a=>{X(a,`CREATE TABLE IF NOT EXISTS "${q}" (
1
+ import{LunoraError as f,toErrorBody as C}from"@lunora/errors";import{drizzle as gt}from"drizzle-orm/durable-sqlite";import{c as j}from"./constant-time-equal-BVG05Guz.mjs";import{j as y}from"./json-response-wrh9TBPw.mjs";import{O as St,t as bt,n as Ie,r as K,A as Et,a as wt,b as Rt,c as Tt,d as vt,w as se,e as At}from"./context-telemetry-BFO0N_e4.mjs";import{f as w,c as O}from"./wire-codec-Ctnni0h6.mjs";import{parseExportShardArgs as It,parseImportShardArgs as _t}from"./exportShardRows-kt42wijd.mjs";import{recordAuthEvent as kt,readAuthMetrics as Mt}from"./AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{DATA_MIGRATION_STATE_TABLE as Nt,readMigrationStatus as Ct}from"./DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as _e,createDependencyTracker as Ot,tableFromDepKey as Lt}from"./SCAN_DEP-D_yR9EeV.mjs";import{readFunctionMetricsTotals as xt,readFunctionMetricIndexHits as $t,recordFunctionMetric as Pt,mergeScanAttribution as qt,readFunctionMetrics as Dt,readFunctionMetricBuckets as Ut}from"./FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{createFanoutCounters as ke,ADMIN_FUNCTION_PREFIX as k,RELATION_FUNCTION_PREFIX as Bt,selectMatchingIds as Ft,ADMIN_FUNCTIONS as h,findStorageReferences as Wt,listTables as Kt,summarizeSubscriptions as Ht,summarizeFanoutTopics as Qt,readTablePage as Gt,facetColumn as zt,FLAGS_FUNCTION_PREFIX as jt,recordFanoutPass as re,MAX_PAGE_SIZE as Jt}from"./ADMIN_FUNCTIONS-PxZ8Lr9e.mjs";import{LogBuffer as Xt}from"./LogBuffer-bIvCelI-.mjs";import{recordCapturedMail as Me,clearCapturedMail as Yt,readCapturedMail as Vt,MAIL_TABLE as Zt}from"./MAIL_RETENTION-KmozO2NQ.mjs";import{stableStringify as Ee}from"./stableStringify-BjLh4gvA.mjs";import{readBookmark as es,armRestore as ts}from"./armRestore-BNzdvQ_o.mjs";import{ReactiveCache as ss,reactiveCacheKey as Ne}from"./ReactiveCache-1_9Rs7J_.mjs";import{stableWireKey as $}from"./stableWireKey-YEHLaX6X.mjs";import{awaitWsDrain as M,trySendFrame as L,subscriptionListDeltas as rs,sendDeltaFrames as as}from"./subscriptionListDeltas-Bs69JbA8.mjs";import{fingerprintError as ns}from"@lunora/fingerprint";import{redact as is,standardRules as os}from"@visulima/redact";import{R as Ce,E as cs,_ as ds}from"./security-audit-BKUOgE0x.mjs";import{runReadonlySql as us}from"./MAX_SQL_ROWS-Bdu25ASB.mjs";import{ConflictError as ls}from"./ConflictError-C8GtJmjS.mjs";import{selectExpiredIds as hs}from"./selectExpiredIds-BGVP3d8-.mjs";import{p as ps,m as fs,T as ms,u as ys,b as ae,_ as gs,o as Ss,l as bs,d as Es,S as ws}from"./ctx-db-idempotency-wiVoGnpQ.mjs";import{CDC_LOG_TABLE as Oe,readCdcChanges as ne,readCdcCursor as Le,readCdcEpoch as xe,minCdcSeq as $e,bumpCdcEpoch as Rs}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{a as Ts,s as vs}from"./ctx-db-shapes-DzX_H5q8.mjs";const Pe=500,J=(a,e)=>{if(a.size<e)return;const t=a.keys().next().value;t!==void 0&&a.delete(t)},at=new TextEncoder,As=a=>{const e=a.replaceAll("-","+").replaceAll("_","/")+"===".slice((a.length+3)%4),t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)s[r]=t.codePointAt(r)??0;return s},Is=64,ie=new Map,_s=async a=>{const e=ie.get(a);if(e)return e;J(ie,Is);const t=crypto.subtle.importKey("raw",at.encode(a),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return ie.set(a,t),t},ks=async(a,e,t)=>{const s=await _s(a);return crypto.subtle.verify("HMAC",s,t,at.encode(e))},Ms="v1",Ns=async(a,e,t=Date.now())=>{if(a.length===0||e.length===0)return!1;const s=e.split(".");if(s.length!==3)return!1;const[r,n,i]=s;if(r!==Ms||i.length===0)return!1;const o=Number(n);if(!Number.isFinite(o)||o<=t)return!1;let c;try{c=As(i)}catch{return!1}return ks(a,`${r}.${n}`,c)},q="__lunora_audit__",X=(a,e,...t)=>a.exec.call(a,e,...t),we=a=>{X(a,`CREATE TABLE IF NOT EXISTS "${q}" (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  op TEXT NOT NULL,
@@ -98,4 +98,4 @@ import{LunoraError as f,toErrorBody as C}from"@lunora/errors";import{drizzle as
98
98
  FROM "${I}" WHERE ${s.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray().map(n=>{const i={durationMs:n.duration_ms,functionPath:n.function_path,outcome:n.outcome==="error"?"error":"ok",seq:n.seq,subscriptionsReRun:n.subscriptions_rerun,tablesRead:ze(n.tables_read),tablesWritten:ze(n.tables_written),ts:n.ts};return n.shard_key!==null&&(i.shardKey=n.shard_key),n.user_id!==null&&(i.userId=n.user_id),n.identity!==null&&(i.identity=JSON.parse(n.identity)),n.args!==null&&(i.redactedArgs=JSON.parse(n.args)),n.error_message!==null&&(i.errorMessage=n.error_message),n.cache_hit!==null&&(i.cacheHit=n.cache_hit===1),i})},Lr=(a,e)=>{const t=Gs(a,[...e.keys()]);for(const s of e.values()){const r=t.get(s.hash);r!==void 0&&(s.stateUpdatedAt=r.updatedAt,r.assignee!==void 0&&(s.assignee=r.assignee),r.severity!==void 0&&(s.severity=r.severity),s.status=r.status==="resolved"&&s.lastSeen>r.updatedAt?"open":r.status)}},xr=(a,e={})=>{W(a);const t=Math.max(1,Math.min(e.limit??ve,1e4)),s=["outcome = 'error'"],r=[];e.functionPathPrefix!==void 0&&e.functionPathPrefix!==""&&(s.push(String.raw`function_path LIKE ? ESCAPE '\'`),r.push(`${ge(e.functionPathPrefix)}%`)),e.userId!==void 0&&e.userId!==""&&(s.push("user_id = ?"),r.push(e.userId)),e.shardKey!==void 0&&e.shardKey!==""&&(s.push("shard_key = ?"),r.push(e.shardKey)),r.push(t);const n=F(a,`SELECT function_path, error_message, ts
99
99
  FROM "${I}" WHERE ${s.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray(),i=new Map,o=new Map;for(const d of n){const u=d.error_message??"",{culprit:l,hash:m,title:p}=ns({functionPath:d.function_path,message:u}),g=i.get(m);if(g===void 0){i.set(m,{count:1,culprit:l,firstSeen:d.ts,hash:m,lastSeen:d.ts,sampleMessage:u,status:"open",title:p}),o.set(m,d.ts);continue}g.count+=1,g.firstSeen=Math.min(g.firstSeen,d.ts),g.lastSeen=Math.max(g.lastSeen,d.ts),d.ts>(o.get(m)??Number.NEGATIVE_INFINITY)&&(o.set(m,d.ts),g.sampleMessage=u,g.title=p)}Lr(a,i);const c=[...i.values()];return(e.status===void 0?c:c.filter(d=>d.status===e.status)).toSorted((d,u)=>u.lastSeen-d.lastSeen)},je=async(a,e,t=8)=>{let s=0;const r=async()=>{let n=a[s];for(s+=1;n!==void 0;){try{await e(n)}catch{}n=a[s],s+=1}};await Promise.all(Array.from({length:Math.min(t,a.length)},()=>r()))};class $r{buffer=[];capacity;constructor(e=500){this.capacity=e>0?Math.trunc(e):500}get size(){return this.buffer.length}clear(){this.buffer.length=0}entries(){return[...this.buffer]}hasTrace(e){return this.buffer.some(t=>t.traceId===e)}push(e){this.buffer.push(e),this.buffer.length>this.capacity&&this.buffer.shift()}}const Pr=50,qr=a=>{const e=new Map;for(const t of a){const s=e.get(t.traceId);s===void 0?e.set(t.traceId,[t]):s.push(t)}return e},Dr=(a,e)=>{const t=a.find(r=>r.dispatch===!0);if(t!==void 0)return t;const s=a.toSorted((r,n)=>r.startTs-n.startTs);return s.find(r=>!e.has(r.parentSpanId))??s[0]},Ur=(a,e)=>{const t=new Map([[a.spanId,0]]);return s=>{const r=[],n=new Set;let i=s,o=0;for(;;){const c=t.get(i.spanId);if(c!==void 0){o=c;break}if(n.has(i.spanId))break;n.add(i.spanId),r.push(i);const d=e.get(i.parentSpanId);if(d===void 0)break;i=d}for(const[c,d]of r.toReversed().entries())t.set(d.spanId,o+c+1);return t.get(s.spanId)??o}},Br=(a,e=Pr)=>{const t=qr(a),s=[...t.entries()].map(([n,i])=>({group:i,startTs:Math.min(...i.map(o=>o.startTs)),traceId:n})).toSorted((n,i)=>i.startTs-n.startTs).slice(0,e),r=[];for(const{group:n,traceId:i}of s){const o=new Map(n.map(p=>[p.spanId,p])),c=Dr(n,o);if(c===void 0)continue;const d=Ur(c,o),{startTs:u}=c,l=Math.max(...n.map(p=>p.startTs+p.durationMs)),m=n.map(p=>({...p.attributes===void 0?{}:{attributes:p.attributes},depth:d(p),durationMs:p.durationMs,...p.error===void 0?{}:{error:p.error},name:p.name,offsetMs:Math.max(0,p.startTs-u),ok:p.ok,parentSpanId:p.parentSpanId,spanId:p.spanId})).toSorted((p,g)=>p.offsetMs-g.offsetMs||p.depth-g.depth);r.push({durationMs:l-u,functionPath:c.functionPath,ok:n.every(p=>p.ok),rootName:c.name,...c.shardKey===void 0?{}:{shardKey:c.shardKey},spans:m,startTs:u,traceId:i})}return{total:t.size,traces:r.toSorted((n,i)=>i.startTs-n.startTs)}},Je="__doc__",Fr=a=>a.startsWith("sqlite_")||a.startsWith("_cf_")||a.startsWith("__miniflare")||a.startsWith("__lunora")||a.includes("__fts_"),Se=a=>`"${a.replaceAll('"','""')}"`,Wr=(a,e)=>Fr(e)?!1:a.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",e).toArray().length>0,Kr=(a,e)=>{const t=e.includes(a),s=e.includes(Je);if(!(!t&&!s))return t?{expression:Se(a),params:[]}:{expression:`json_extract(${Se(Je)}, ?)`,params:[`$."${a.replaceAll('"','""')}"`]}},Hr=(a,e,t,s,r,n,i)=>{const o=Kr(s,r);if(o===void 0)return;const c=a.exec(`SELECT id, ${o.expression} AS ref FROM ${e} WHERE ${o.expression} IS NOT NULL AND ${o.expression} <> '' LIMIT ?`,...o.params,...o.params,...o.params,5001).toArray();c.length>5e3&&(i.truncated=!0);for(const d of c.slice(0,5e3))if(i.scanned+=1,!n.has(d.ref)){if(i.references.length>=500){i.truncated=!0;continue}i.references.push({column:s,id:d.id,key:d.ref,table:t})}},Qr=(a,e,t)=>{const s=t instanceof Set?t:new Set(t),r={references:[],scanned:0,truncated:!1};for(const[n,i]of Object.entries(e)){if(!Wr(a,n))continue;const o=Se(n),c=a.exec(`PRAGMA table_info(${o})`).toArray().map(d=>d.name);for(const d of i)Hr(a,o,n,d,c,s,r)}return r},Gr="lunora-ping",zr="lunora-pong",jr=new Set(["1","enabled","on","true","yes"]);let Xe=!1,ce;const Jr=async()=>{if(!Xe){Xe=!0;try{const a=(await import("cloudflare:workers")).tracing;ce=a!==null&&typeof a=="object"&&typeof a.enterSpan=="function"?a:void 0}catch{ce=void 0}}return ce},Xr="<undelivered>",Yr=1073741824,Ye=1e4,Vr=864e5,Zr=36e5,z="__root__",b="*",Ve=(a,e)=>(a===void 0?"":`,"cursor":${String(a)}`)+(e===void 0?"":`,"epoch":${JSON.stringify(e)}`),ea=(a,e)=>{const[t,s]=a.size<=e.size?[a,e]:[e,a];for(const r of t)if(s.has(r))return!0;return!1},ta=a=>{const e=typeof a.id=="string"?a.id:"";if(e.trim()==="")throw new f("MIGRATION_ID_REQUIRED","runMigration: `id` is required",{status:400});return{batchSize:typeof a.batchSize=="number"?a.batchSize:void 0,direction:a.direction==="down"?"down":"up",dryRun:a.dryRun===!0,id:e,maxBatches:typeof a.maxBatches=="number"?a.maxBatches:void 0}},Ze=Jt,sa=200,ra=20,aa=3e4,na=a=>{const{op:e}=a,t=typeof a.table=="string"?a.table:"";if(e!=="insert"&&e!=="patch"&&e!=="replace"&&e!=="delete")throw new f("BAD_REQUEST","writeRow: `op` must be insert|patch|replace|delete");if(t.trim()==="")throw new f("BAD_REQUEST","writeRow: `table` is required");const s=typeof a.id=="string"?a.id:void 0,r=typeof a.doc=="object"&&a.doc!==null&&!Array.isArray(a.doc)?a.doc:void 0;if(e!=="insert"&&(s===void 0||s===""))throw new f("BAD_REQUEST",`writeRow: \`id\` is required for op "${e}"`);if(e!=="delete"&&r===void 0)throw new f("BAD_REQUEST",`writeRow: \`doc\` is required for op "${e}"`);return{doc:r,id:s,op:e,table:t}},ia=a=>typeof a=="string"&&Hs.includes(a),oa=a=>typeof a=="string"&&Qs.includes(a),ca=a=>{const e=typeof a.hash=="string"?a.hash.trim():"";if(e==="")throw new f("BAD_REQUEST","issue triage: `hash` is required");return e},mt=null,da=a=>{const e=a.assignee;if(e===null)return mt;if(typeof e=="string"&&e.trim()!=="")return e;throw new f("BAD_REQUEST","assignIssue: `assignee` must be a non-empty string (assign) or null (unassign)")},ua=a=>{const e=a.severity;if(e===null)return mt;if(oa(e))return e;throw new f("BAD_REQUEST","setIssueSeverity: `severity` must be one of critical|high|medium|low, or null to clear")},la=a=>{const e=typeof a.exportName=="string"?a.exportName.trim():"";if(e==="")throw new f("BAD_REQUEST","createWorkflowInstance: `exportName` is required");const t=typeof a.id=="string"&&a.id!==""?a.id:void 0;return{exportName:e,id:t,params:a.params}},ha=a=>{const e=typeof a.exportName=="string"?a.exportName.trim():"",t=typeof a.id=="string"?a.id.trim():"";if(e==="")throw new f("BAD_REQUEST","getWorkflowInstanceStatus: `exportName` is required");if(t==="")throw new f("BAD_REQUEST","getWorkflowInstanceStatus: `id` is required");return{exportName:e,id:t}},pa=new Set(["complete","errored","paused","queued","running","terminated","unknown","waiting","waitingForPause"]),et=a=>typeof a=="string"&&pa.has(a)?a:"unknown",fa=a=>{if(typeof a!="object"||a===null)return;const{message:e,name:t}=a;return{message:typeof e=="string"?e:"",name:typeof t=="string"?t:"Error"}},ma=new Set(["contains","eq","gt","gte","lt","lte","ne"]),be=a=>{if(!Array.isArray(a))return;const e=[];for(const t of a){if(typeof t!="object"||t===null)continue;const s=t,{column:r,operator:n}=s;typeof r!="string"||r===""||typeof n!="string"||!ma.has(n)||e.push({column:r,operator:n,value:s.value})}return e.length>0?e:void 0},ya=a=>{if(typeof a!="object"||a===null)return;const{column:e,direction:t}=a;if(!(typeof e!="string"||e===""))return{column:e,direction:t==="desc"?"desc":"asc"}},ga=a=>{const e=typeof a.table=="string"?a.table:"";if(e.trim()==="")throw new f("BAD_REQUEST","deleteRows: `table` is required");return{filters:be(a.filters),limit:typeof a.limit=="number"?a.limit:void 0,search:typeof a.search=="string"?a.search:void 0,table:e}},Sa=a=>{const e=typeof a.table=="string"?a.table:"";if(e.trim()==="")throw new f("BAD_REQUEST","clearTable: `table` is required");return{limit:typeof a.limit=="number"?a.limit:void 0,table:e}},ba=a=>{const{outcome:e}=a;if(e!=="ok"&&e!=="fail")throw new f("BAD_REQUEST",'recordAuthEvent: `outcome` must be "ok" or "fail"');return{outcome:e}},Ea=/\(exit (\d+)\)/,wa=a=>{const e=a.event;if(typeof e!="object"||e===null||Array.isArray(e))throw new f("BAD_REQUEST","recordContainerEvent: `event` must be an object");const t=e,s=typeof t.container=="string"?t.container:"",r=typeof t.event=="string"?t.event:"";if(s.trim()===""||r.trim()==="")throw new f("BAD_REQUEST","recordContainerEvent: `event.container` and `event.event` are required");const n=t.level==="error"?"error":"info",i=typeof t.message=="string"?t.message:void 0,o=typeof t.ts=="number"?t.ts:Date.now(),c=typeof t.instance=="string"&&t.instance!==""?t.instance:void 0,d=i===void 0?void 0:Ea.exec(i)?.[1];return{exitCode:d===void 0?void 0:Number.parseInt(d,10),functionPath:`container:${s}`,instance:c,level:n,message:i===void 0||i===""?r:`${r}: ${i}`,timestamp:o}},Ra=a=>{const e=typeof a.functionPath=="string"?a.functionPath:"",t=typeof a.userId=="string"?a.userId:"";if(e.trim()==="")throw new f("BAD_REQUEST","runAs: `functionPath` is required");if(e.startsWith(k))throw new f("BAD_REQUEST","runAs: cannot target a reserved admin function");if(t.trim()==="")throw new f("BAD_REQUEST","runAs: `userId` is required");const s=a.args;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))throw new f("BAD_REQUEST","runAs: `args` must be an object");const r=a.identity;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new f("BAD_REQUEST","runAs: `identity` must be an object");return{args:s===void 0?{}:s,functionPath:e,userId:t,...r===void 0?{}:{identity:r}}},Ta=a=>{const e=p=>{throw new f("BAD_REQUEST",`recordMail: ${p}`)},{bcc:t,cc:s,from:r,headers:n,html:i,replyTo:o,subject:c,text:d,to:u}=a;typeof c!="string"&&e("`subject` must be a string"),typeof u=="string"||Array.isArray(u)&&u.every(p=>typeof p=="string")||e("`to` must be a string or string[]");const l=(p,g)=>{if(p!==void 0)return(!Array.isArray(p)||!p.every(E=>typeof E=="string"))&&e(`\`${g}\` must be a string[]`),p},m=(p,g)=>(p!==void 0&&typeof p!="string"&&e(`\`${g}\` must be a string`),p);return{bcc:l(t,"bcc"),cc:l(s,"cc"),from:m(r,"from"),headers:n!==void 0&&typeof n=="object"&&n!==null?n:void 0,html:m(i,"html"),replyTo:m(o,"replyTo"),subject:c,text:m(d,"text"),to:u}},va="test@lunora.sh",Aa=a=>{const{to:e}=a;if(e!==void 0&&typeof e!="string")throw new f("BAD_REQUEST","sendTestMail: `to` must be a string");const t=e??va,s="https://example.test/verify?token=demo";return{from:"Lunora <noreply@lunora.sh>",html:`<p>This is a test email from the Lunora dev mail catcher.</p><p><a href="${s}">Verify your email</a></p>`,subject:"Lunora test email",text:`This is a test email from the Lunora dev mail catcher.
100
100
 
101
- Verify your email: ${s}`,to:t}},Ia=a=>{const e=r=>{throw new f("BAD_REQUEST",`recordQueueMessage: ${r}`)},t=a.messages;Array.isArray(t)||e("`messages` must be an array");const s=new Set(["ack","error","retry"]);return t.map((r,n)=>{(typeof r!="object"||r===null)&&e(`\`messages[${String(n)}]\` must be an object`);const i=r,o=typeof i.messageId=="string"?i.messageId:"",c=typeof i.queue=="string"?i.queue:"",d=typeof i.outcome=="string"?i.outcome:"";o===""&&e(`\`messages[${String(n)}].messageId\` is required`),c===""&&e(`\`messages[${String(n)}].queue\` is required`),s.has(d)||e(`\`messages[${String(n)}].outcome\` must be one of ack | error | retry`);const{attempts:u,timestamp:l}=i;return{attempts:typeof u=="number"&&Number.isFinite(u)?u:1,body:i.body,deadLettered:i.deadLettered===!0,error:typeof i.error=="string"?i.error:void 0,exportName:typeof i.exportName=="string"?i.exportName:void 0,messageId:o,outcome:d,queue:c,timestamp:typeof l=="number"&&Number.isFinite(l)?l:0}})},tt=100,R=a=>`${a.traceId}:${a.rootSpanId}`,de=256,_a=500,ue="lunora.dispatch",ka=a=>{const e=typeof a.exportName=="string"?a.exportName.trim():"";if(e==="")throw new f("BAD_REQUEST","sendQueueMessage: `exportName` is required");const t=a.delaySeconds;if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<0))throw new f("BAD_REQUEST","sendQueueMessage: `delaySeconds` must be a non-negative number");const s=Array.isArray(a.batch)?a.batch:void 0;if(s!==void 0&&(s.length===0||s.length>tt))throw new f("BAD_REQUEST",`sendQueueMessage: \`batch\` must contain between 1 and ${String(tt)} messages`);return{batch:s,body:a.body,contentType:typeof a.contentType=="string"?a.contentType:void 0,delaySeconds:t,exportName:e}},Ma=a=>{const e=typeof a.id=="string"?a.id.trim():"";if(e==="")throw new f("BAD_REQUEST","replayQueueMessage: `id` is required");const t=typeof a.target=="string"&&a.target.trim()!==""?a.target.trim():void 0;return{id:e,target:t}},Na=a=>{const e=typeof a.table=="string"?a.table:"",t=typeof a.index=="string"?a.index:"",s=typeof a.rowId=="string"?a.rowId:"";if(e.trim()==="")throw new f("BAD_REQUEST","rankBefore: `table` is required");if(t.trim()==="")throw new f("BAD_REQUEST","rankBefore: `index` is required");if(typeof a.partitionKey!="string")throw new f("BAD_REQUEST","rankBefore: `partitionKey` must be a string");if(s.trim()==="")throw new f("BAD_REQUEST","rankBefore: `rowId` is required");if(!Array.isArray(a.sortValues))throw new f("BAD_REQUEST","rankBefore: `sortValues` must be an array");return{index:t,partitionKey:a.partitionKey,rowId:s,sortValues:a.sortValues,table:e}},N=a=>{throw new f("BAD_REQUEST",a)},st=(a,e)=>((typeof a!="string"||a.trim()==="")&&N(`rankPage: \`${e}\` is required`),a),Ca=a=>{if(a===void 0)return;(typeof a!="object"||a===null||Array.isArray(a))&&N("rankPage: `after` must be an object");const e=a;return(typeof e.partitionKey!="string"||typeof e.rowId!="string"||!Array.isArray(e.sortValues))&&N("rankPage: `after` must have a string partitionKey, string rowId, and array sortValues"),{partitionKey:e.partitionKey,rowId:e.rowId,sortValues:e.sortValues}},Oa=a=>{const e=st(a.table,"table"),t=st(a.index,"index");a.take!==void 0&&typeof a.take!="number"&&N("rankPage: `take` must be a number"),a.cursor!==void 0&&a.cursor!==null&&typeof a.cursor!="string"&&N("rankPage: `cursor` must be a string or null"),a.partitionKey!==void 0&&typeof a.partitionKey!="string"&&N("rankPage: `partitionKey` must be a string"),a.directions!==void 0&&!Array.isArray(a.directions)&&N("rankPage: `directions` must be an array");const s=a.directions===void 0?void 0:a.directions.map(r=>r==="desc"?"desc":"asc");return{after:Ca(a.after),cursor:typeof a.cursor=="string"?a.cursor:void 0,directions:s,index:t,partitionKey:typeof a.partitionKey=="string"?a.partitionKey:void 0,take:typeof a.take=="number"?a.take:void 0,table:e}},La=a=>{try{const e=JSON.parse(a);if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{index:e[1],table:e[0]}}catch{}},xa=a=>{const e=a.changes;if(!Array.isArray(e))throw new f("BAD_REQUEST","applyCdc: `changes` must be an array");return{changes:e.map((t,s)=>{const r=t,{op:n}=r,i=typeof r.table=="string"?r.table:"",o=typeof r.id=="string"?r.id:"";if(i===""||o===""||n!=="insert"&&n!=="update"&&n!=="delete")throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}] must have a table, id, and op of insert|update|delete`);const c=r.doc;if(c!==void 0&&(typeof c!="object"||c===null||Array.isArray(c)))throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc must be an object`);const d=c;if(d!==void 0&&typeof d._id=="string"&&d._id!==o)throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc._id must match the entry id`);return{doc:d,id:o,op:n,seq:typeof r.seq=="number"?r.seq:0,table:i,ts:typeof r.ts=="number"?r.ts:0}})}},$a=a=>{const e=t=>{const s=typeof t=="number"?t:Number(t);return Number.isFinite(s)&&s>=0?Math.floor(s):void 0};return{limit:e(a.limit),sinceSeq:e(a.sinceSeq)??0}},_=a=>a?{"x-d1-bookmark":a}:void 0,rt=a=>{if(a)try{const e=JSON.parse(a);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}},Pa=a=>{if(!a)return;const e=Number(a);return Number.isInteger(e)&&e>0?e:void 0},qa=a=>{const e=new Set;for(const t of a){const s=Lt(t);s!==""&&e.add(s)}return e},Da=a=>{if(a===void 0)return;const e=Number.parseInt(a,10);return Number.isFinite(e)&&e>0?e:void 0},Ua=(a,e)=>a==="1"||a==="true"?!0:a==="0"||a==="false"?!1:e,Ba=a=>{if(a===void 0)return 1;const e=Number.parseFloat(a);return Number.isFinite(e)?Math.min(1,Math.max(0,e)):1},Fa=a=>a>=1?!0:a<=0?!1:Math.random()<a,le=a=>{if(!a)return;const[e,...t]=a.split(" ");if(e?.toLowerCase()!=="bearer")return;const s=t.join(" ").trim();return s.length>0?s:void 0};class S{static MAX_STREAMS_PER_SOCKET=8;static MAX_SUBSCRIPTIONS_PER_SOCKET=32;static GLOBAL_SHAPE_POLL_INTERVAL_MS=2e3;static GLOBAL_SHAPE_MAX_ROWS=5e4;static MAX_WHISPER_TOPICS_PER_SOCKET=64;static MAX_WHISPER_BYTES=4096;static WHISPER_RATE_BURST=50;static WHISPER_RATE_PER_SEC=25;static rootSizeWarned=!1;static resetRootSizeWarning(){S.rootSizeWarned=!1}static nextPollAlarmTarget(e,t,s,r){const n=[e>0?r+S.GLOBAL_SHAPE_POLL_INTERVAL_MS:void 0,t,s].filter(i=>i!==void 0).map(i=>Math.max(i,r));return n.length>0?Math.min(...n):void 0}state;env;reactiveCache;drizzleHandle;transactionDepth=0;currentRequestBookmark;currentResponseBookmark;currentRequestUserId;currentRequestIp;currentRequestTraceparent;currentRequestTrace;traceSampling=new Map;dispatchSpans=new Map;lastTelemetrySink;currentRequestMutationId;currentRequestClientId;currentRequestClientSeq;currentMutatorClass;mutationBookkeepingCommitted=!1;lastIdempotencyTrimAt=0;currentRequestIdentity;currentRequestSystem=!1;pendingChangedTables=void 0;pendingRefreshTables=void 0;refreshInFlight=!1;subMemos=new WeakMap;shapeMemos=new WeakMap;globalShapeSnapshots=new WeakMap;globalPollScheduled=!1;pokeSequence=0;whisperBuckets=new WeakMap;streamCancellers=new WeakMap;metrics={errors:0,requests:0,sinceMs:Date.now()};fanout={shapePoke:ke(),whisper:ke()};shardBinding;relay;usedIndexes=new Set;functionStats=new Map;logs=new Xt;spans=new $r;metricSeries=new js;currentTracker;currentScannedTables;currentIndexHits;currentRequestReadTables;currentStmtSamples;currentRequestCacheHit;constructor(e,t,s={}){this.state=e,this.env=t,s.reactiveCache&&(this.reactiveCache=new ss(s.reactiveCache));const r={buildShapeDiff:(n,i,o)=>this.buildShapeDiff(this.sql,n,i,o),computeOpLogShapeSeed:(n,i)=>this.computeOpLogShapeSeed(n,i),currentCdcEpoch:()=>this.currentCdcEpoch(),deliverWhisperLocal:(n,i,o)=>this.deliverWhisperLocal(n,i,o),doName:()=>this.state.id?.name,env:()=>this.env,getWebSockets:()=>this.state.getWebSockets(),maskMetadata:()=>this.maskMetadata(),nextPokeId:()=>(this.pokeSequence+=1,`poke-${String(this.pokeSequence)}`),readAttachment:n=>this.readAttachment(n),recordShapePokeFanout:(n,i,o)=>{this.fanout.shapePoke=re(this.fanout.shapePoke,n,i,o)},resolveShape:(n,i,o)=>this.resolveShape(n,i,o),rlsMetadata:()=>this.rlsMetadata(),shardBinding:()=>this.shardBinding,sql:()=>this.sql};this.relay=Tr(r),this.armWebSocketKeepalive()}async fetch(e){const t=new URL(e.url);this.shardBinding=e.headers.get("x-lunora-shard-binding")??this.shardBinding;const s=await this.routeNonRpc(t,e);if(s!==void 0)return s;if(t.pathname!=="/rpc"||e.method!=="POST")return new Response("Not found",{status:404});let r;try{r=await e.json()}catch{return y({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(r.functionPath.startsWith(k))return this.handleAdminRpc(e,r.functionPath,r.args??{});this.currentRequestBookmark=e.headers.get("x-d1-bookmark")??void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=e.headers.get("x-lunora-userid")??void 0,this.currentRequestMutationId=e.headers.get("x-lunora-mutation-id")??void 0,this.currentRequestClientId=e.headers.get("x-lunora-client-id")??void 0,this.currentRequestClientSeq=Pa(e.headers.get("x-lunora-client-seq")),this.currentMutatorClass=void 0,this.mutationBookkeepingCommitted=!1,this.currentRequestIdentity=rt(e.headers.get("x-lunora-identity")),this.currentRequestIp=e.headers.get("x-lunora-client-ip")??void 0,this.currentRequestSystem=e.headers.get("x-lunora-system")==="1",this.currentRequestTraceparent=e.headers.get("traceparent")??void 0,this.currentRequestTrace=K(this.currentRequestTraceparent);const n=this.currentRequestTrace;this.traceSampling.set(n.traceId,{keepErrors:e.headers.get("x-lunora-sample-errors")!=="0",sampled:Et(this.currentRequestTraceparent)?.sampled??!0}),this.currentRequestReadTables=void 0,this.currentRequestCacheHit=void 0,this.metrics.requests+=1;const i=Date.now();this.currentScannedTables=new Set,this.currentIndexHits=new Set,this.currentStmtSamples=[];let o;try{if(r.functionPath.startsWith(Bt)){const E=await this.runRelationFanoutRead(r.functionPath,r.args??{});return y(E,200,_(this.currentResponseBookmark))}const c=this.isCustomMutator(r.functionPath)?this.classifyClientMutation():void 0;this.currentMutatorClass=c;const d=this.rejectNonNextMutation(r.functionPath,c,i);if(d!==void 0)return d;const u=this.readIdempotentResult(this.currentRequestMutationId);if(u!==void 0)return this.respondFromIdempotencyCache(r.functionPath,i,c,u.value);const l=await this.handleRpc(r.functionPath,O(r.args??{}));this.recordPostDispatchBookkeeping(l,c),c?.kind==="next"&&this.advanceClientMutationWatermark();const m=Date.now()-i;this.recordFunctionCall(r.functionPath,m,void 0,this.currentScannedTables,this.currentIndexHits),this.flushStmtSamples();const p=[...this.pendingChangedTables??[]];this.recordRequestLog(r.functionPath,r.args??{},m,"ok",p),this.maybeWarnRootSize();const g=this.buildDispatchResponse(c,w(l));return await this.flushChangedTables(),g}catch(c){this.metrics.errors+=1,o={thrown:c};const d=Date.now()-i,u=c instanceof Error?c.message:String(c),l=c instanceof ls&&c.kind==="occ";return c?.code!=="FUNCTION_NOT_FOUND"&&this.recordFunctionCall(r.functionPath,d,u,this.currentScannedTables,this.currentIndexHits,l),this.flushStmtSamples(),this.recordRequestLog(r.functionPath,r.args??{},d,"error",[...this.pendingChangedTables??[]],u),this.logs.push({functionPath:r.functionPath,level:"error",message:u,timestamp:Date.now()}),this.recordChangedTable(I),await this.flushChangedTables(),this.errorToResponse(c)}finally{const c=this.dispatchSpans.get(R(n));if((this.spans.hasTrace(n.traceId)||c?.collector!==void 0)&&this.recordDispatchRootSpan(r.functionPath,i,o,n),this.dispatchSpans.delete(R(n)),c?.sink?.flush)try{c.sink.flush({waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}this.flushSampledOutTrace(n,o!==void 0),this.traceSampling.delete(n.traceId),this.currentRequestTrace=void 0,this.currentRequestBookmark=void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=void 0,this.currentRequestMutationId=void 0,this.currentRequestClientId=void 0,this.currentRequestClientSeq=void 0,this.currentMutatorClass=void 0,this.mutationBookkeepingCommitted=!1,this.currentRequestIdentity=void 0,this.currentRequestIp=void 0,this.currentRequestSystem=!1,this.currentRequestTraceparent=void 0,this.currentScannedTables=void 0,this.currentIndexHits=void 0,this.currentRequestReadTables=void 0,this.currentRequestCacheHit=void 0,this.currentStmtSamples=void 0}}async webSocketMessage(e,t){return this.handleWebSocketMessage(e,t)}async webSocketClose(e,t,s,r){const n=this.readAttachment(e);n.connectionId!==void 0&&await this.dispatchLifecycle("disconnect",this.lifecycleInfo(n));const i=this.streamCancellers.get(e);if(i){for(const o of i.values())o.abort();this.streamCancellers.delete(e)}if(this.subMemos.delete(e),this.shapeMemos.delete(e),this.globalShapeSnapshots.delete(e),n.connectionId!==void 0)try{ps(this.sql,n.connectionId)}catch{}e.serializeAttachment?.(void 0),await this.relay?.announceDrain(e)}webSocketError(e,t){}async alarm(){return this.withTriggerTrace("alarm",async()=>this.handleAlarmBody())}lifecycleHookPaths(e){return[]}async dispatchLifecycle(e,t){for(const s of this.lifecycleHookPaths(e))try{await this.withRequestIdentity(t.userId,t.identity,()=>this.withSystemDispatch(()=>this.handleRpc(s,t.event)))}catch(r){this.logs.push({functionPath:s,level:"error",message:r instanceof Error?r.message:String(r),timestamp:Date.now()})}}runRelationFanoutRead(e,t){throw new f("NOT_IMPLEMENTED","__lunora_relation__: no schema bound — the base ShardDO cannot serve cross-shard relation reads",{status:500})}get sql(){const e=this.state.storage.sql,t=this.currentStmtSamples;if(t===void 0)return e;const s=e.exec;if(typeof s!="function")return e;const r=(n,...i)=>{const o=Date.now(),c=s.call(e,n,...i);if(c!==null&&typeof c=="object"){const d=c;if(typeof d.toArray=="function"){const u=d.toArray.bind(d);d.toArray=()=>{const l=u(),m=Date.now()-o;return t.push([n,m,l.length,0]),l}}if(typeof d.one=="function"){const u=d.one.bind(d);d.one=()=>{const l=u(),m=Date.now()-o;return t.push([n,m,1,0]),l}}if(typeof d.toArray!="function"&&typeof d.one!="function"){const u=Date.now()-o;t.push([n,u,0,0])}}else{const d=Date.now()-o;t.push([n,d,0,0])}return c};return new Proxy(e,{get(n,i){return i==="exec"?r:Reflect.get(n,i,n)}})}get db(){return this.drizzleHandle?this.drizzleHandle:(this.drizzleHandle=gt(this.state.storage,{logger:!1}),this.drizzleHandle)}async runInTransaction(e){if(this.transactionDepth>0)throw new f("NESTED_TRANSACTION","nested transactions are not supported in SQLite-in-DO",{status:500});const t=this.state.storage.sql;if(!t||typeof t.exec!="function")throw new f("SQL_UNAVAILABLE","storage.sql is not available on this ShardDO state",{status:500});const s=this.state.storage,r=async()=>{this.transactionDepth=1;try{return typeof s?.transaction=="function"?await s.transaction(async()=>e()):await e()}finally{this.transactionDepth=0}};return typeof this.state.blockConcurrencyWhile=="function"?this.state.blockConcurrencyWhile(r):r()}getInboundBookmark(){return this.currentRequestBookmark}setOutboundBookmark(e){this.currentResponseBookmark=e}getCurrentUserId(){return this.currentRequestUserId}getCurrentIp(){return this.currentRequestIp}getCurrentTraceparent(){return this.currentRequestTraceparent}getCurrentTrace(){return this.currentRequestTrace}getCurrentIdentity(){return this.currentRequestIdentity}isSystemDispatch(){return this.currentRequestSystem}runShardDataMigration(e){return Promise.reject(new f("MIGRATION_NOT_FOUND",`data migration "${e.id}" is not registered`,{status:404}))}ensureMigrated(){}tableRefs(e){}tableIndexes(e){return[]}tableColumns(e){return[]}storageColumns(){return{}}advisories(){return[]}rlsMetadata(){return{policies:[],roles:[]}}maskMetadata(){return{columns:[]}}storageRulesMetadata(){return{rules:[]}}studioFeatures(){return{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1}}evaluateFlags(e){return Promise.resolve({configured:!1,flags:[]})}runFlagSubscriptionRead(e,t,s){return Promise.resolve(null)}queuesMetadata(){return{queues:[]}}workflowsMetadata(){return{workflows:[]}}runtimeAdvisories(){const e=new Set([...this.usedIndexes].map(s=>s.slice(0,s.indexOf(":")))),t=[];for(const s of e)for(const r of this.tableIndexes(s))r.type==="vector"||this.usedIndexes.has(`${s}:${r.name}`)||t.push({cacheKey:`unused_index:${s}:${r.name}`,categories:["PERFORMANCE"],description:"A declared index has not been exercised by any query since this shard instance started. An unused index costs storage and is maintained on every write for no read benefit.",detail:`Index "${r.name}" on table "${s}" has not been used since this instance woke, though other indexes on "${s}" have — it may be redundant.`,facing:"INTERNAL",level:"INFO",metadata:{index:r.name,indexKind:r.type,since:"instance-woke",table:s},name:"unused_index",remediation:"Confirm over a representative window, then drop the index if no query needs it.",title:"Unused index"});return t}runShardExport(e){return Promise.resolve([])}runShardImport(e){return Promise.resolve({conflicts:0,errors:[],inserted:{}})}runShardWrite(e){return Promise.reject(new f("UNKNOWN_TABLE",`unknown table: ${e.table}`,{status:404}))}deleteRowThroughWriter(e,t){return Promise.reject(new f("UNKNOWN_TABLE",`unknown table: ${e}`,{status:404}))}async runShardBulkDelete(e){const t=Math.min(Math.max(Math.trunc(e.limit??Ze),1),Ze),{hasMore:s,ids:r}=Ft(this.sql,{filters:e.filters,limit:t,search:e.search,table:e.table});let n=0;for(const i of r)await this.deleteRowThroughWriter(e.table,i),n+=1;return{deleted:n,hasMore:s}}runShardRankBefore(e){return Promise.reject(new f("NOT_IMPLEMENTED","rankBefore is not implemented in base ShardDO",{status:500}))}runShardRankPage(e){return Promise.reject(new f("NOT_IMPLEMENTED","rankPage is not implemented in base ShardDO",{status:500}))}runShardCdcSync(e){const t=this.sql;return t.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",Oe).toArray().length>0?ne(t,{limit:e.limit,sinceSeq:e.sinceSeq}):{changes:[],cursor:e.sinceSeq}}currentCdcCursor(){return this.cdcEnabled()?Le(this.sql):void 0}currentCdcEpoch(){return this.cdcEnabled()?xe(this.sql):void 0}evaluateResume(e,t,s){const r=this.sql;if(!this.cdcEnabled())return{cursor:void 0,epoch:void 0,resumable:!1};const n=Le(r),i=xe(r);if(s!==i)return{cursor:n,epoch:i,resumable:!1};if(e>n)return{cursor:n,epoch:i,resumable:!1};if(e===n)return{cursor:n,epoch:i,resumable:!0};const o=$e(r);if(o===void 0||o>e+1)return{cursor:n,epoch:i,resumable:!1};if(t.size===0)return{cursor:n,epoch:i,resumable:!1};const{changes:c}=ne(r,{limit:Ye,sinceSeq:e});if(c.length>=Ye)return{cursor:n,epoch:i,resumable:!1};const d=c.some(u=>t.has(u.table));return{cursor:n,epoch:i,resumable:!d}}readIdempotentResult(e){if(e!==void 0)try{const t=fs(this.sql,this.currentRequestUserId??"",e);return t===void 0?void 0:{value:JSON.parse(t.resultJson)}}catch{return}}persistIdempotentResult(e){if(this.currentRequestMutationId===void 0)return;const t=Date.now();try{ms(this.sql,this.currentRequestUserId??"",this.currentRequestMutationId,JSON.stringify(w(e)),t),t-this.lastIdempotencyTrimAt>Zr&&(ys(this.sql,t-Vr),this.lastIdempotencyTrimAt=t)}catch{}}isCustomMutator(e){return!1}classifyClientMutation(){const e=this.currentRequestClientId,t=this.currentRequestClientSeq;if(e===void 0||t===void 0)return;const s=this.currentRequestUserId??"";let r;try{r=ae(this.sql,s,e)}catch{try{gs(this.sql),r=ae(this.sql,s,e)}catch{return}}const n=r+1;return t<=r?{expected:n,kind:"already"}:t===n?{expected:n,kind:"next"}:{expected:n,kind:"gap"}}rejectNonNextMutation(e,t,s){if(!(t===void 0||t.kind==="next"))return this.recordFunctionCall(e,Date.now()-s,void 0,this.currentScannedTables,this.currentIndexHits),t.kind==="already"?y({lastMutationId:t.expected-1,result:null},200,_(this.currentResponseBookmark)):y({error:{code:"OUT_OF_ORDER",expectedMutationId:t.expected,message:`out-of-order mutation; expected sequence ${String(t.expected)}`}},409,_(this.currentResponseBookmark))}respondFromIdempotencyCache(e,t,s,r){if(this.recordFunctionCall(e,Date.now()-t,void 0,this.currentScannedTables,this.currentIndexHits),s?.kind==="next")return this.advanceClientMutationWatermark(),this.buildDispatchResponse(s,r);const n=this.mutationCommitCursor();return y(n===void 0?{result:r}:{commitCursor:n,result:r},200,_(this.currentResponseBookmark))}mutationCommitCursor(){return this.currentRequestMutationId===void 0?void 0:this.currentCdcCursor()}buildDispatchResponse(e,t){if(e?.kind==="next")return y({lastMutationId:this.currentRequestClientSeq,result:t},200,_(this.currentResponseBookmark));const s=this.mutationCommitCursor();return y(s===void 0?{result:t}:{commitCursor:s,result:t},200,_(this.currentResponseBookmark))}commitMutationBookkeeping(e){this.persistIdempotentResult(e),this.currentMutatorClass?.kind==="next"&&this.advanceClientMutationWatermark({strict:!0}),this.mutationBookkeepingCommitted=!0}recordPostDispatchBookkeeping(e,t){this.mutationBookkeepingCommitted||(this.persistIdempotentResult(e),t?.kind==="next"&&this.advanceClientMutationWatermark())}advanceClientMutationWatermark(e){const t=this.currentRequestClientId,s=this.currentRequestClientSeq;if(!(t===void 0||s===void 0))try{Ss(this.sql,this.currentRequestUserId??"",t,s)}catch(r){if(e?.strict)throw r}}runShardApplyCdc(e){return Promise.reject(new f("NOT_IMPLEMENTED","applyCdc is not implemented in base ShardDO",{status:500}))}subscribe(e,t,s){const r=this.readAttachment(e);if(Object.keys(r.subs).length>=S.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";r.subs[t]=s;try{e.serializeAttachment?.(r)}catch{return delete r.subs[t],"serialize_failed"}return"ok"}unsubscribe(e,t){const s=this.readAttachment(e),r=s.subs[t];delete s.subs[t];try{e.serializeAttachment?.(s)}catch{r!==void 0&&(s.subs[t]=r);return}this.subMemos.get(e)?.delete(t)}shapeSubscribe(e,t,s){const r=this.readAttachment(e),n=r.shapes??{};if(Object.keys(r.subs).length+Object.keys(n).length>=S.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";n[t]=s,r.shapes=n;try{e.serializeAttachment?.(r)}catch{return delete r.shapes[t],"serialize_failed"}return"ok"}shapeUnsubscribe(e,t){const s=this.readAttachment(e),{shapes:r}=s;if(!r)return;const n=r[t];delete r[t];try{e.serializeAttachment?.(s)}catch{n!==void 0&&(r[t]=n);return}if(this.shapeMemos.get(e)?.delete(t),this.globalShapeSnapshots.get(e)?.delete(t),s.connectionId!==void 0)try{bs(this.sql,s.connectionId,t)}catch{}}matchesSubscription(e,t){if(e.table!==t.table)return!1;const{args:s}=e;if(!s)return!0;const{row:r}=t;if(!r)return!0;for(const[n,i]of Object.entries(s))if(r[n]!==i)return!1;return!0}broadcastDelta(e){const t=this.state.getWebSockets(),s=JSON.stringify(e);for(const r of t){const n=this.readAttachment(r);for(const[i,o]of Object.entries(n.subs))this.matchesSubscription(o,e)&&L(r,`{"type":"delta","id":${JSON.stringify(i)},"delta":${s}}`)}}executeSubscription(e,t,s){return Promise.resolve(null)}resolveShape(e,t,s){}isShapeRelayUniform(e,t){return this.relay?.isShapeRelayUniform(e,t)??!1}readGlobalShapeRows(e,t){return Promise.resolve([])}pollExternalSources(){return Promise.resolve(void 0)}scheduleSourcePoll(){return this.scheduleGlobalPoll()}ttlSweeps(){return[]}async pollTtlSweeps(){const e=this.ttlSweeps();if(e.length===0)return;const t=this.sql,s=Date.now();for(const r of e){let n=0,i=!0;for(;i&&n<ra;){const o=hs(t,r,s,sa);for(const c of o.ids)await this.deleteRowThroughWriter(r.table,c);i=o.hasMore,n+=1}}return s+aa}scheduleTtlSweep(){return this.scheduleGlobalPoll()}currentShardKey(){return this.state.id?.name??z}recordExternalSourceError(e,t){this.recordShapeError(`source:${e}`,t)}executeStream(e,t){return null}async runCachedQuery(e,t,s){if(!this.reactiveCache)return s();const r=this.currentTracker,n=Ot();this.currentTracker=n;const i=this.reactiveCache.stats().hits,o=this.getCurrentUserId(),c=this.getCurrentIdentity(),d=o===void 0&&c===void 0?null:Ee({claims:c??null,userId:o??null});try{const u=await this.reactiveCache.run(Ne(e,t,d),n.collect(),s);return this.currentRequestCacheHit=this.reactiveCache.stats().hits>i,this.currentRequestReadTables=qa(n.collect()),u}finally{this.currentTracker=r}}getCtxDbReadHook(){return(e,t)=>{this.currentTracker?.recordRead(e,t??_e),t===_e&&this.currentScannedTables?.add(e)}}getCtxDbIndexUseHook(){return(e,t)=>{this.usedIndexes.add(`${e}:${t}`),this.currentIndexHits?.add(JSON.stringify([e,t]))}}recordChangedTable(e){this.pendingChangedTables??=new Set,this.pendingChangedTables.add(e)}async flushMigrationProgress(){this.recordChangedTable(Nt),await this.flushChangedTables()}recordUserLog(e,t,s,r,n,i,o,c){const d=c??this.currentRequestTrace,u={args:s,...o===void 0?{}:{eventName:o},fields:n,functionPath:e,level:t,message:r,shardKey:this.state.id?.name,spanId:d?.rootSpanId,traceId:d?.traceId,ts:Date.now(),userId:this.getCurrentUserId()};this.logs.push({fields:n,functionPath:e,level:t,message:r,timestamp:u.ts});try{Cr(u)}catch{}if(i?.onLog)try{i.onLog(u,{waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}makeLogger(e,t,s){const r=(n,i)=>{const{fields:o,message:c}=Nr(i,s);this.recordUserLog(e,n,i,c,o,t)};return{debug:(...n)=>{r("debug",n)},error:(...n)=>{r("error",n)},event:(n,i)=>{this.recordUserLog(e,"info",[n],n,s?{...s,...i}:i,t,n)},fatal:(...n)=>{r("fatal",n)},info:(...n)=>{r("info",n)},log:(...n)=>{r("log",n)},trace:(...n)=>{r("trace",n)},warn:(...n)=>{r("warn",n)},with:n=>this.makeLogger(e,t,s?{...s,...n}:n)}}makeTracer(e,t,s){const r=s??K(void 0);return wt({anchor:r,fuseCloudflareSpans:t?.fuseCloudflareTraces===!0,functionPath:e,record:n=>{this.recordSpan(n,t,r.sampled)},resolveCloudflareTracing:Jr,shardKey:this.state.id?.name,userId:()=>this.getCurrentUserId()})}resolveDispatchAnchor(e){return(e?void 0:this.getCurrentTrace())??K(void 0)}instrumentDb(e,t,s,r){const n=r===void 0?"off":r.instrumentDatabase??"summary";return n==="off"?e:Fs(e,{anchor:s,functionPath:t,mode:n,record:i=>{this.recordSpan(i,r,s.sampled)},shardKey:this.state.id?.name,tally:this.dispatchTally(s),userId:()=>this.getCurrentUserId()})}makeFetch(e,t,s){const r=(n,i)=>globalThis.fetch(n,i);return s===void 0||s.traceFetch===!1?r:Rt({anchor:t,functionPath:e,...typeof s.traceFetch=="object"&&s.traceFetch.propagate!==void 0?{propagate:s.traceFetch.propagate}:{},record:n=>{this.recordSpan(n,s,t.sampled)},shardKey:this.state.id?.name,userId:()=>this.getCurrentUserId()},r)}makeDispatchSpan(e,t){this.lastTelemetrySink=t??this.lastTelemetrySink,t!==void 0&&(J(this.dispatchSpans,de),this.dispatchSpans.set(R(e),this.dispatchSpans.get(R(e))??{sink:t}));const s=()=>{J(this.dispatchSpans,de);const r=R(e),n=this.dispatchSpans.get(r)??{sink:t};return n.collector??=At({spanId:e.rootSpanId,traceId:e.traceId}),this.dispatchSpans.set(r,n),n.collector};return{addEvent:(r,n)=>{s().handle.addEvent(r,n)},spanContext:()=>({spanId:e.rootSpanId,traceId:e.traceId}),addLink:r=>{s().handle.addLink(r)},recordException:r=>{s().handle.recordException(r)},setAttribute:(r,n)=>{s().handle.setAttribute(r,n)},setAttributes:r=>{s().handle.setAttributes(r)}}}makeMetrics(e,t){return Tt({functionPath:e,record:s=>{this.recordMetric(s,t)},shardKey:this.state.id?.name})}recordMetric(e,t){const s=this.currentRequestTrace?.traceId,r=s===void 0?e:{...e,traceId:s},n=o=>{try{o()}catch{}};n(()=>{this.metricSeries.push(r)});const i=t?.metricHistory;if(i!==void 0&&i!==!1){const o=this.state.storage.sql,c=typeof i=="object"?i:{};n(()=>{er(o,r,s,c)})}t?.onMetric&&n(()=>t.onMetric?.(r,{waitUntil:this.state.waitUntil?.bind(this.state)}))}async handleWebSocketMessage(e,t){if(this.isSocketExpired(e)){this.dropExpiredSocket(e);return}const s=typeof t=="string"?t:new TextDecoder().decode(t);let r;try{r=JSON.parse(s)}catch{e.send(JSON.stringify({message:"invalid envelope",type:"error"}));return}if(r.type==="connect"){const n=this.readAttachment(e);if(n.connected===!0)return;r.context!==void 0&&(n.context=r.context),r.clientId!==void 0&&(n.clientId=r.clientId),n.connected=!0;try{e.serializeAttachment?.(n)}catch{}await this.dispatchLifecycle("connect",this.lifecycleInfo(n));return}if(r.type==="subscribe"&&r.query){const{functionPath:n}=r.query,i=n?.startsWith(k)===!0;if(i&&this.readAttachment(e).admin!==!0){e.send(JSON.stringify({id:r.id,message:"admin subscription requires admin authorization",type:"error"}));return}let o;try{o=r.query.args===void 0?r.query:{...r.query,args:O(r.query.args)}}catch{try{e.send(JSON.stringify({code:"BAD_SUBSCRIPTION_ARGS",error:{code:"BAD_SUBSCRIPTION_ARGS",message:"subscription args failed wire decoding"},id:r.id,type:"error"}))}catch{}return}const c=this.subscribe(e,r.id,o);if(c!=="ok"){const d=c==="too_many"?"TOO_MANY_SUBSCRIPTIONS":"SUBSCRIPTION_PERSIST_FAILED",u=c==="too_many"?`subscription cap of ${String(S.MAX_SUBSCRIPTIONS_PER_SOCKET)} reached on this socket`:"failed to persist subscription attachment";try{e.send(JSON.stringify({code:d,error:{code:d,message:u},id:r.id,type:"error"}))}catch{}return}e.send(JSON.stringify({id:r.id,type:"ack"})),n&&await this.seedSubscription(e,r.id,o,n,i);return}if(r.type==="shape_subscribe"&&r.shape){let n;try{n=r.shape.args===void 0?void 0:O(r.shape.args)}catch{this.sendShapeSubscribeError(e,r.id,"BAD_SUBSCRIPTION_ARGS","shape args failed wire decoding");return}await this.handleShapeSubscribe(e,r.id,{args:n,name:r.shape.name,sinceEpoch:r.sinceEpoch,sinceSeq:r.sinceCheckpoint});return}if(r.type==="shape_unsubscribe"){this.shapeUnsubscribe(e,r.id),e.send(JSON.stringify({id:r.id,type:"ack"}));return}if(r.type==="stream"&&r.query?.functionPath){if(r.query.functionPath.startsWith(k)){e.send(JSON.stringify({id:r.id,message:"streams must be public",type:"error"}));return}this.handleStream(e,r.id,r.query.functionPath,O(r.query.args??{})).catch(()=>{});return}if(r.type==="whisper_subscribe"||r.type==="whisper_unsubscribe"){if(typeof r.topic=="string"&&r.topic.length>0){const n=r.type==="whisper_subscribe";this.setWhisperMembership(e,r.topic,n),n&&await this.relay?.announce()}return}if(r.type==="whisper"){typeof r.topic=="string"&&r.topic.length>0&&await this.broadcastWhisper(e,r.topic,r.data);return}if(r.type==="unsubscribe"){const n=this.streamCancellers.get(e),i=n?.get(r.id);i&&(i.abort(),n?.delete(r.id)),this.unsubscribe(e,r.id),e.send(JSON.stringify({id:r.id,type:"ack"}))}}async handleAlarmBody(){this.globalPollScheduled=!1;let e;try{e=await this.pollGlobalShapes()}catch(n){this.recordShapeError("shape:poll",n),e=1}let t;try{t=await this.pollExternalSources()}catch(n){this.recordShapeError("source:poll",n),t=Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS}let s;try{s=await this.pollTtlSweeps()}catch(n){this.recordShapeError("ttl:sweep",n),s=Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS}await this.flushChangedTables();const r=S.nextPollAlarmTarget(e,t,s,Date.now());r!==void 0&&await this.scheduleGlobalPoll(r)}dispatchTally(e){J(this.dispatchSpans,de);const t=R(e),s=this.dispatchSpans.get(t)??{};return s.dbTally??=Ws(),this.dispatchSpans.set(t,s),s.dbTally}async withTriggerTrace(e,t){const s=K(void 0),r=Date.now(),n=this.currentRequestTrace===void 0;n&&(this.currentRequestTrace=s);let i;try{return await t()}catch(o){throw i={thrown:o},o}finally{n&&this.currentRequestTrace===s&&(this.currentRequestTrace=void 0),(this.spans.hasTrace(s.traceId)||this.dispatchSpans.get(R(s))?.collector!==void 0)&&this.recordDispatchRootSpan(e,r,i,s),this.dispatchSpans.delete(R(s)),this.flushTelemetry()}}flushTelemetry(){try{this.lastTelemetrySink?.flush?.({waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}recordDispatchRootSpan(e,t,s,r){const n=this.dispatchSpans.get(R(r)),i=Date.now()-t,o=n?.dbTally===void 0||n.dbTally.calls===0?void 0:Ks(n.dbTally),c=n?.collector===void 0?void 0:{...n.collector.collected,attributes:{...o,...n.collector.collected.attributes}};try{this.spans.push(vt({anchor:r,...c===void 0?{}:{collected:c},durationMs:i,failure:s,functionPath:e,shardKey:this.state.id?.name,startTs:t,userId:this.getCurrentUserId()}))}catch{}n?.collector!==void 0&&this.exportWideEvent(e,i,s,r,{collected:c??n.collector.collected,sink:n.sink})}exportWideEvent(e,t,s,r,n){try{const{attributes:i}=n.collected;this.recordUserLog(e,s===void 0?"info":"error",[ue],ue,{...i,[se.durationMs]:t,[se.functionPath]:e,[se.ok]:s===void 0},n.sink,ue,r)}catch{}}recordSpan(e,t,s){try{this.spans.push(e)}catch{}if(!t?.onSpan)return;const r=this.traceSampling.get(e.traceId);if(r!==void 0){if(!r.sampled){if(r.sink=t,e.dispatch!==!0){const n=r.held??(r.held=[]);n.push(e),n.length>_a&&n.shift()}return}this.emitSpan(e,t);return}s!==!1&&this.emitSpan(e,t)}emitSpan(e,t){if(t.onSpan)try{t.onSpan(e,{waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}flushSampledOutTrace(e,t){const s=this.traceSampling.get(e.traceId);if(!s||s.sampled||!s.keepErrors)return;const{held:r,sink:n}=s;if(!(!n?.onSpan||r===void 0||r.length===0||!(t||r.some(i=>!i.ok))))for(const i of r)this.emitSpan(i,n)}lifecycleInfo(e){return{event:{connectionId:e.connectionId??"",shardKey:this.state.id?.name??z,userId:e.userId??null,...e.context===void 0?{}:{context:e.context}},identity:e.identity,userId:e.userId}}async withSystemDispatch(e){const t=this.currentRequestSystem;this.currentRequestSystem=!0;try{return await e()}finally{this.currentRequestSystem=t}}collectMetrics(){const e=this.state.storage.sql?.databaseSize;let{requests:t}=this.metrics,{errors:s}=this.metrics;try{const i=xt(this.state.storage.sql);t=i.requests,s=i.errors}catch{}let r=[];try{r=$t(this.state.storage.sql)}catch{}let n=[];try{n=nr(this.state.storage.sql)}catch{}return{cache:this.reactiveCache?this.reactiveCache.stats():null,databaseSize:typeof e=="number"?e:null,errors:s,functions:this.collectFunctionStats().functions,history:this.collectFunctionMetricBuckets(),indexHits:r,queryStats:n,requests:t,shard:this.state.id?.name??z,sinceMs:this.metrics.sinceMs,uptimeMs:Date.now()-this.metrics.sinceMs}}recordFunctionCall(e,t,s,r,n,i=!1){const o=Date.now(),c=r?[...r]:[],d=n?[...n].map(m=>La(m)).filter(m=>m!==void 0):[];try{Pt(this.state.storage.sql,{conflicted:i,durationMs:t,errored:s!==void 0,errorMessage:s,indexHits:d,path:e,scannedTables:c,ts:o})}catch{}const u=this.functionStats.get(e),l=u??{calls:0,conflicts:0,errors:0,lastCalledAt:o,lastErrorAt:null,lastErrorMessage:null,maxDurationMs:0,path:e,scannedTables:[],scans:0,totalDurationMs:0};l.calls+=1,l.totalDurationMs+=t,l.maxDurationMs=Math.max(l.maxDurationMs,t),l.lastCalledAt=o,c.length>0&&(l.scans+=c.length,qt(l.scannedTables,c)),s!==void 0&&(l.errors+=1,l.lastErrorAt=o,l.lastErrorMessage=s),i&&(l.conflicts+=1),u===void 0&&this.functionStats.set(e,l)}flushStmtSamples(){const e=this.currentStmtSamples;if(!(!e||e.length===0))try{const t=this.state.storage.sql;for(const[s,r,n,i]of e)try{ar(t,s,r,n,i)}catch{}}catch{}}collectFunctionStats(){try{return{functions:Dt(this.state.storage.sql),sinceMs:this.metrics.sinceMs}}catch{return{functions:[...this.functionStats.values()].toSorted((e,t)=>t.lastCalledAt-e.lastCalledAt),sinceMs:this.metrics.sinceMs}}}collectFunctionMetricBuckets(){try{return Ut(this.state.storage.sql)}catch{return[]}}maybeWarnRootSize(){if(S.rootSizeWarned||this.state.id?.name!==z)return;const e=this.state.storage.sql?.databaseSize;typeof e!="number"||e<Yr||(S.rootSizeWarned=!0,console.warn(`[@lunora/do] __root__ Durable Object SQLite size is ${String(e)} bytes (>= 1 GiB, 10% of the 10 GiB per-DO ceiling). Plan a \`.shardBy()\` migration before you hit the wall. See https://lunora.sh/docs/concepts/sharding for guidance.`))}errorToResponse(e){const{body:t,redacted:s,status:r}=C(e,{encodeData:w,fallbackCode:"RPC_FAILED",redactedMessage:"internal error"});return s&&console.error("[@lunora/do] internal error:",e),y({error:t},r)}async handleBatchRpc(e){let t;try{t=await e.json()}catch{return y({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(!Array.isArray(t.calls))return y({error:{code:"BAD_REQUEST",message:"batch `calls` must be an array"}},400);if(t.calls.length>Pe)return y({error:{code:"BAD_REQUEST",message:`batch exceeds the ${String(Pe)}-call limit`}},400);const s=[];let r;for(const n of t.calls){const i=await this.dispatchBatchEntry(e,n);i.bookmark!==void 0&&(r=i.bookmark),s.push({body:i.body,id:i.id,status:i.status})}return y({results:s},200,_(r))}async dispatchBatchEntry(e,t){try{const s=await this.fetch(xs(e,t));return{body:await s.json(),bookmark:s.headers.get("x-d1-bookmark")??void 0,id:t.id,status:s.status}}catch(s){const{body:r,status:n}=C(s,{fallbackCode:"BATCH_ENTRY_FAILED"});return{body:{error:r},bookmark:void 0,id:t?.id,status:n}}}async handleAdminRpc(e,t,s){if(!this.isAdminAuthorized(e))return y({error:{code:"ADMIN_FORBIDDEN",message:"admin introspection is disabled or the bearer token is invalid"}},403);try{const r=this.readAdminOp(t,s);if(r)return y({result:r.result},200);if(t===h.runMigration){const i=ta(s),o=await this.runShardDataMigration(i);return await this.flushChangedTables(),this.recordAudit("runMigration",{id:i.id,detail:{changed:o.changed,direction:o.direction,dryRun:o.dryRun,processed:o.processed}}),y({result:o},200)}if(t===h.exportShard){const i=It(s),o=await this.runShardExport({batchSize:i.batchSize,tables:i.tables});return y({result:{rows:o}},200)}if(t===h.importShard){const i=_t(s),o=await this.runShardImport({rows:i.rows,startLine:i.startLine});return await this.flushChangedTables(),this.recordAudit("importShard",{detail:{conflicts:o.conflicts,errors:o.errors.length,inserted:o.inserted}}),y({result:o},200)}if(t===h.writeRow){const i=na(s),o=await this.runShardWrite(i);return await this.flushChangedTables(),this.recordAudit("writeRow",{table:i.table,id:o.id??i.id,detail:{op:o.op}}),y({result:o},200)}if(t===h.deleteRows){const i=ga(s),o=await this.runShardBulkDelete(i);return await this.flushChangedTables(),this.recordAudit("deleteRows",{table:i.table,detail:{deleted:o.deleted,hasMore:o.hasMore}}),y({result:o},200)}if(t===h.clearTable){const i=Sa(s),o=await this.runShardBulkDelete(i);return await this.flushChangedTables(),this.recordAudit("clearTable",{table:i.table,detail:{deleted:o.deleted,hasMore:o.hasMore}}),y({result:o},200)}if(t===h.rankBefore){const i=await this.runShardRankBefore(Na(s));return y({result:i},200)}if(t===h.rankPage){const i=await this.runShardRankPage(Oa(s));return y({result:i},200)}if(t===h.cdcSync){const i=this.runShardCdcSync($a(s));return y({result:i},200)}if(t===h.applyCdc){const i=await this.runShardApplyCdc(xa(s));return await this.flushChangedTables(),this.recordAudit("applyCdc",{detail:{applied:i.applied}}),y({result:i},200)}return t===h.runAs?this.handleRunAs(s):await this.handleExtraAdminOp(t,s)||y({error:{code:"UNKNOWN_ADMIN_OP",message:`unknown admin op: ${t}`}},404)}catch(r){return this.errorToResponse(r)}}async handleExtraAdminOp(e,t){if(e===h.recordAuthEvent)return this.handleRecordAuthEvent(t);if(e===h.recordContainerEvent)return this.handleRecordContainerEvent(t);if(e===h.recordMail)return this.handleRecordMail(t);if(e===h.clearCapturedMail)return this.handleClearCapturedMail();if(e===h.sendTestMail)return this.handleSendTestMail(t);if(e===h.recordQueueMessage)return this.handleRecordQueueMessage(t);if(e===h.clearQueueMessages)return this.handleClearQueueMessages();if(e===h.sendQueueMessage)return this.handleSendQueueMessage(t);if(e===h.replayQueueMessage)return this.handleReplayQueueMessage(t);if(e===h.createWorkflowInstance)return this.handleCreateWorkflowInstance(t);if(e===h.getWorkflowInstanceStatus)return this.handleGetWorkflowInstanceStatus(t);if(e===h.listFlags)return this.handleListFlags(t);const s=await this.handleIssueTriageOp(e,t);return s!==void 0?s:this.handlePitrAdminOp(e,t)}async handleIssueTriageOp(e,t){const s=this.parseIssueTriagePatch(e,t);if(s===void 0)return;const r=ca(t),n=typeof t.updatedBy=="string"?t.updatedBy:void 0,i=this.state.storage.sql,o=zs(i,r,s,Date.now(),n);return this.recordChangedTable(B),await this.flushChangedTables(),this.recordAudit(e.slice(k.length),{detail:{...s,hash:r}}),y({result:{state:o}},200)}parseIssueTriagePatch(e,t){if(e===h.resolveIssue)return{status:"resolved"};if(e===h.ignoreIssue)return{status:"ignored"};if(e===h.assignIssue)return{assignee:da(t),status:"open"};if(e===h.setIssueSeverity)return{severity:ua(t)}}handleRecordAuthEvent(e){const t=ba(e);try{kt(this.state.storage.sql,{outcome:t.outcome,ts:Date.now()})}catch{}return y({result:{recorded:!0}},200)}async handleRecordContainerEvent(e){const t=wa(e);if(this.logs.push(t),t.level==="error"||t.exitCode!==void 0&&t.exitCode!==0){const s={durationMs:0,errorMessage:t.message,functionPath:t.functionPath,outcome:"error",shardKey:this.state.id?.name,ts:t.timestamp};this.persistRequestLog(s,this.requestLogConfig()),this.recordChangedTable(I),await this.flushChangedTables()}return y({result:{recorded:!0}},200)}async handleRunAs(e){const t=Ra(e),s=await this.withRequestIdentity(t.userId,t.identity,()=>this.handleRpc(t.functionPath,t.args));return await this.flushChangedTables(),this.recordAudit("runAs",{detail:{functionPath:t.functionPath,runAsUserId:t.userId}}),y({result:s},200)}resolveWorkflowBinding(e){const t=this.workflowsMetadata().workflows.find(r=>r.exportName===e);if(!t)throw new f("BAD_REQUEST",`workflow "${e}" is not declared`);const s=this.env?.[t.binding];if(typeof s!="object"||s===null||typeof s.create!="function"||typeof s.get!="function")throw new f("BAD_REQUEST",`workflow binding "${t.binding}" is not available on this deployment`);return s}async handleCreateWorkflowInstance(e){const t=la(e),s=await this.resolveWorkflowBinding(t.exportName).create({id:t.id,params:t.params}),r=await s.status(),n={id:s.id,status:et(r.status)};return this.recordAudit("createWorkflowInstance",{id:s.id,detail:{exportName:t.exportName}}),y({result:n},200)}async handleGetWorkflowInstanceStatus(e){const t=ha(e),s=await(await this.resolveWorkflowBinding(t.exportName).get(t.id)).status(),r={error:fa(s.error),id:t.id,output:s.output,status:et(s.status)};return y({result:r},200)}async handleListFlags(e){const t=e.context,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0,r=await this.evaluateFlags(s);return y({result:r},200)}async withRequestIdentity(e,t,s){const r=this.currentRequestUserId,n=this.currentRequestIdentity;this.currentRequestUserId=e,this.currentRequestIdentity=t;try{return await s()}finally{this.currentRequestUserId=r,this.currentRequestIdentity=n}}handleRecordMail(e){const t=Ta(e),s=Me(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleClearCapturedMail(){const e=Yt(this.state.storage.sql);return y({result:e},200)}handleSendTestMail(e){const t=Aa(e),s=Me(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleRecordQueueMessage(e){const t=Ia(e),s=dr(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleClearQueueMessages(){const e=hr(this.state.storage.sql);return y({result:e},200)}async handleSendQueueMessage(e){const t=ka(e),{binding:s}=this.resolveQueueBinding(t.exportName);let r;return t.batch===void 0?(await s.send(t.body,{contentType:t.contentType,delaySeconds:t.delaySeconds}),r=1):(await s.sendBatch(t.batch.map(n=>({body:n,contentType:t.contentType,delaySeconds:t.delaySeconds}))),r=t.batch.length),this.recordAudit("sendQueueMessage",{detail:{count:r,exportName:t.exportName}}),y({result:{sent:r}},200)}async handleReplayQueueMessage(e){const t=Ma(e),s=lr(this.state.storage.sql,t.id);if(s===void 0)throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" was not found`,{status:404});if(or(s.body))throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has a truncated or unserializable body and can't be replayed faithfully`,{status:422});const r=t.target??this.resolveReplayTarget(s.queue)??s.exportName;if(typeof r!="string"||r==="")throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has no declared producer to replay onto (pass \`target\`)`);const{binding:n}=this.resolveQueueBinding(r);return await n.send(s.body),this.recordAudit("replayQueueMessage",{detail:{messageId:s.messageId,target:r},id:t.id}),y({result:{sent:1,target:r}},200)}resolveQueueBinding(e){const t=this.queuesMetadata().queues.find(r=>r.exportName===e);if(!t)throw new f("BAD_REQUEST",`queue "${e}" is not declared`);const s=this.env?.[t.binding];if(typeof s!="object"||s===null||typeof s.send!="function")throw new f("BAD_REQUEST",`queue binding "${t.binding}" is not available on this deployment`);return{binding:s,metadata:t}}resolveReplayTarget(e){const{queues:t}=this.queuesMetadata(),s=t.find(r=>r.deadLetterQueue===e);return s!==void 0?s.exportName:t.find(r=>r.name===e)?.exportName}recordAudit(e,t={}){const s=this.state.storage.sql,r=this.getCurrentUserId(),n=r===void 0?t.detail:{...t.detail,userId:r};Cs(s,{detail:n,id:t.id,op:e,table:t.table,ts:Date.now()})}recordRequestLog(e,t,s,r,n,i){const o=this.requestLogConfig();if(r==="ok"&&!Fa(o.sampleRate))return;const c={cacheHit:this.currentRequestCacheHit,durationMs:s,errorMessage:i,functionPath:e,identity:this.currentRequestIdentity,outcome:r,redactedArgs:Object.keys(t).length===0?void 0:t,shardKey:this.state.id?.name,tablesRead:this.currentRequestReadTables===void 0?[]:[...this.currentRequestReadTables],tablesWritten:n,ts:Date.now(),userId:this.getCurrentUserId()};this.persistRequestLog(c,o)}persistRequestLog(e,t){const s={captureRaw:t.captureRaw,retention:t.retention};try{Ar(this.state.storage.sql,e,s)}catch{}if(t.emit||e.outcome==="error")try{Ir(e,s)}catch{}}requestLogConfig(){const e=this.env??{};return{captureRaw:Ce(this.env),emit:Ua(e.LUNORA_REQUEST_LOG_EMIT,Ce(this.env)),retention:Da(e.LUNORA_REQUEST_LOG_RETENTION),sampleRate:Ba(e.LUNORA_REQUEST_LOG_SAMPLE)}}async handlePitrAdminOp(e,t){const s=typeof t.time=="number"||typeof t.time=="string"?t.time:void 0;if(e===h.getPitrBookmark)return y({result:await es(this.state.storage,s)},200);if(e!==h.pitrRestore)return;const r=t.restart===!0,n=typeof t.bookmark=="string"?t.bookmark:void 0,i=await ts(this.state.storage,{bookmark:n,time:s});this.cdcEnabled()&&Rs(this.sql),this.recordAudit("pitrRestore",{detail:{restart:r,restoredTo:i.restoredTo,undoBookmark:i.undoBookmark}});const o=y({result:{...i,restarted:r}},200);return r&&this.state.abort?.("lunora PITR restore"),o}readAdminOp(e,t){this.ensureMigrated();const s=this.state.storage.sql,r=this.readAdminWildcardOp(e);if(r!==void 0)return{result:r,tables:new Set([b])};if(e===h.getAuditLog)return this.readAdminAuditLog(s,t);if(e===h.getRequestLog)return this.readAdminRequestLog(s,t);if(e===h.getIssues)return this.readAdminIssues(s,t);const n=this.readAdminDurableSignal(e,s,t);if(n)return n;if(e===h.readTablePage)return this.readAdminTablePage(s,t);if(e===h.facetColumn)return this.readAdminFacetColumn(s,t);if(e===h.runSql)return this.readAdminRunSql(s,t);const i=this.readAdminTableSignal(e,s,t);return i||this.readAdminStorageSignal(e,s,t)||null}readAdminTableSignal(e,t,s){if(e===h.listTableIndexes||e===h.describeTable){const r=typeof s.table=="string"?s.table:"";return{result:e===h.describeTable?{columns:this.tableColumns(r)}:{indexes:this.tableIndexes(r)},tables:new Set([r===""?b:r])}}if(e===h.describeTables){const r=Array.isArray(s.tables)?s.tables.filter(n=>typeof n=="string"):[];return{result:{columnsByTable:Object.fromEntries(r.map(n=>[n,this.tableColumns(n)]))},tables:new Set(r.length===0?[b]:r)}}if(e===h.migrationStatus){const r=typeof s.id=="string"?s.id:void 0;return{result:{migrations:Ct(t,r)},tables:new Set([b])}}}readAdminStorageSignal(e,t,s){if(e===h.storageReferences)return this.readAdminStorageReferences(t,s);if(e===h.storageOrphans)return this.readAdminStorageOrphans(t,s)}readAdminStorageReferences(e,t){const s=Array.isArray(t.keys)?t.keys.filter(r=>typeof r=="string"):[];return{result:Wt(e,this.storageColumns(),s),tables:new Set([b])}}readAdminStorageOrphans(e,t){const s=Array.isArray(t.liveKeys)?t.liveKeys.filter(n=>typeof n=="string"):[],r=Qr(e,this.storageColumns(),s);return r.truncated&&console.warn(`[@lunora/do] storageOrphans scan truncated after checking ${String(r.scanned)} storage references; reporting the first ${String(r.references.length)} dangling reference(s).`),{result:r,tables:new Set([b])}}readAdminWildcardOp(e){if(e===h.listTables)return Kt(this.state.storage.sql);if(e===h.getMetrics)return this.collectMetrics();if(e===h.getFunctionStats)return this.collectFunctionStats();if(e===h.listSubscriptions)return this.collectSubscriptions();if(e===h.getFanoutMetrics)return this.collectFanoutMetrics();if(e===h.getLogs)return{entries:this.logs.entries()};if(e===h.getTraces){const t=Br(this.spans.entries());return{total:t.total,traces:t.traces}}if(e===h.getMetricSeries)return{series:this.metricSeries.entries()};if(e===h.getMetricHistory)return sr(this.sql);if(e===h.getSettings)return cs(this.env);if(e===h.getSecurityAudit)return ds(this.env);if(e===h.getAdvisories)return{advisories:[...this.advisories(),...this.runtimeAdvisories()]};if(e===h.rlsPolicies)return this.rlsMetadata();if(e===h.maskPolicies)return this.maskMetadata();if(e===h.storageRules)return this.storageRulesMetadata();if(e===h.studioFeatures)return this.studioFeatures();if(e===h.listWorkflows)return this.workflowsMetadata();if(e===h.listQueues)return this.queuesMetadata()}collectSubscriptions(){return Ht(this.state.getWebSockets().map(e=>this.readAttachment(e)))}collectFanoutMetrics(){const e=Qt(this.state.getWebSockets().map(s=>this.readAttachment(s))),t=this.relay?.relayCount()??0;return{...e,maxRelays:this.relay?.maxRelays()??Te,promoted:t>0,relayCount:t,shapePoke:this.fanout.shapePoke,sinceMs:this.metrics.sinceMs,whisper:this.fanout.whisper}}readAdminAuditLog(e,t){we(e);const s=typeof t.limit=="number"?t.limit:void 0,r=typeof t.sinceSeq=="number"?t.sinceSeq:void 0;return{result:{entries:Os(e,{limit:s,sinceSeq:r})},tables:new Set([b])}}readAdminRequestLog(e,t){W(e);const s=t.outcome==="ok"||t.outcome==="error"?t.outcome:void 0;return{result:{entries:Or(e,{functionPathPrefix:typeof t.functionPathPrefix=="string"?t.functionPathPrefix:void 0,limit:typeof t.limit=="number"?t.limit:void 0,outcome:s,shardKey:typeof t.shardKey=="string"?t.shardKey:void 0,sinceSeq:typeof t.sinceSeq=="number"?t.sinceSeq:void 0,tableTouched:typeof t.tableTouched=="string"?t.tableTouched:void 0,userId:typeof t.userId=="string"?t.userId:void 0})},tables:new Set([b])}}readAdminIssues(e,t){return W(e),{result:{issues:xr(e,{functionPathPrefix:typeof t.functionPathPrefix=="string"?t.functionPathPrefix:void 0,limit:typeof t.limit=="number"?t.limit:void 0,shardKey:typeof t.shardKey=="string"?t.shardKey:void 0,status:ia(t.status)?t.status:void 0,userId:typeof t.userId=="string"?t.userId:void 0})},tables:new Set([b])}}readAdminDurableSignal(e,t,s){if(e===h.getAuthMetrics)return this.readAdminAuthMetrics(t);if(e===h.getCapturedMail)return this.readAdminCapturedMail(t,s);if(e===h.getQueueMessages)return this.readAdminQueueMessages(t,s)}readAdminAuthMetrics(e){let t;try{t=Mt(e)}catch{t={attempts:0,failureRate:0,failures:0,history:[],sinceMs:0}}return{result:t,tables:new Set([b])}}readAdminCapturedMail(e,t){const s=typeof t.limit=="number"?t.limit:void 0;let r;try{r=Vt(e,{limit:s})}catch{r={entries:[]}}return{result:r,tables:new Set([Zt])}}readAdminQueueMessages(e,t){const s=typeof t.limit=="number"?t.limit:void 0,r=typeof t.queue=="string"?t.queue:void 0;let n;try{n=ur(e,{limit:s,queue:r})}catch{n={entries:[]}}return{result:n,tables:new Set([A])}}readAdminTablePage(e,t){const s=typeof t.table=="string"?t.table:"";return{result:Gt(e,{filters:be(t.filters),limit:typeof t.limit=="number"?t.limit:void 0,offset:typeof t.offset=="number"?t.offset:void 0,orderBy:ya(t.orderBy),refs:this.tableRefs(s),search:typeof t.search=="string"?t.search:void 0,skipCount:typeof t.skipCount=="boolean"?t.skipCount:void 0,table:s}),tables:new Set([s===""?b:s])}}readAdminFacetColumn(e,t){const s=typeof t.table=="string"?t.table:"";return{result:zt(e,{column:typeof t.column=="string"?t.column:"",filters:be(t.filters),limit:typeof t.limit=="number"?t.limit:void 0,search:typeof t.search=="string"?t.search:void 0,table:s}),tables:new Set([s===""?b:s])}}readAdminRunSql(e,t){const s=typeof t.sql=="string"?t.sql:"";return{result:us(e,s),tables:new Set([b])}}executeAdminSubscription(e,t){const s=this.readAdminOp(e,t);return s?{result:s.result,tables:s.tables}:null}async resolveReactiveOutcome(e,t,s,r){if(s)return this.executeAdminSubscription(e,t);if(e.startsWith(jt)){const n=await this.runFlagSubscriptionRead(e,t,r);return n===null?null:{result:n,tables:new Set([b])}}return this.executeSubscription(e,t,r)}isIdentityIndependent(e){return e.startsWith(k)}resolveReactiveOutcomeDeduped(e,t,s,r,n){if(!this.isIdentityIndependent(e))return this.resolveReactiveOutcome(e,t,s,r);const i=Ne(e,t,null),o=n.get(i);if(o!==void 0)return o;const c=this.resolveReactiveOutcome(e,t,s,r);return n.set(i,c),c}isAdminAuthorized(e){const t=(this.env??{}).LUNORA_ADMIN_TOKEN;if(!t||t.length===0)return!1;const s=le(e.headers.get("authorization"));return s!==void 0&&j(s,t)}async handleStream(e,t,s,r){const n=this.executeStream(s,r);if(!n){e.send(JSON.stringify({error:{code:"NOT_FOUND",message:`stream not registered: ${s}`},id:t,type:"error"}));return}let i=this.streamCancellers.get(e);if(i||(i=new Map,this.streamCancellers.set(e,i)),i.size>=S.MAX_STREAMS_PER_SOCKET){try{e.send(JSON.stringify({error:{code:"TOO_MANY_STREAMS",message:`stream cap of ${String(S.MAX_STREAMS_PER_SOCKET)} reached on this socket`},id:t,type:"error"}))}catch{}return}const o=new AbortController;i.set(t,o),e.send(JSON.stringify({id:t,type:"ack"}));try{for await(const c of n.iterator(o.signal)){if(o.signal.aborted)break;await M(e),e.send(JSON.stringify({data:w(c),id:t,type:"chunk"}))}o.signal.aborted||e.send(JSON.stringify({id:t,type:"complete"}))}catch(c){const{body:d,redacted:u}=C(c,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});u&&console.error("[@lunora/do] unhandled stream error:",c),e.send(JSON.stringify({error:{code:d.code,message:d.message},id:t,type:"error"}))}finally{i.delete(t),i.size===0&&this.streamCancellers.delete(e)}}async flushChangedTables(){const e=this.pendingChangedTables;if(this.pendingChangedTables=void 0,!(!e||e.size===0)){if(this.pendingRefreshTables)for(const t of e)this.pendingRefreshTables.add(t);else this.pendingRefreshTables=e;if(!this.refreshInFlight){if(typeof this.state.waitUntil=="function"){this.state.waitUntil(this.drainSubscriptionRefreshes());return}await this.drainSubscriptionRefreshes()}}}async drainSubscriptionRefreshes(){if(!this.refreshInFlight){this.refreshInFlight=!0;try{let e=this.pendingRefreshTables;for(;e&&e.size>0;){this.pendingRefreshTables=void 0;const t=this.currentCdcCursor(),s=this.currentCdcEpoch();await Promise.all([this.refreshSubscriptions(e),this.pokeShapeSubscribers(e,t,s),this.relay?.onFlush(e,t??0)]),e=this.pendingRefreshTables}}finally{this.refreshInFlight=!1}}}async refreshSubscriptions(e){const t=[...this.state.getWebSockets()],s=this.currentCdcCursor(),r=this.currentCdcEpoch(),n=new Map;await je(t,async i=>{if(this.isSocketExpired(i)){this.dropExpiredSocket(i);return}const o=this.readAttachment(i);for(const[c,d]of Object.entries(o.subs)){const{functionPath:u}=d;if(!u)continue;const l=u.startsWith(k),m=this.subMemos.get(i)?.get(c);if(!(m&&!m.tables.has(b)&&!ea(m.tables,e)))try{const p=await this.resolveReactiveOutcomeDeduped(u,d.args??{},l,{identity:o.identity,userId:o.userId},n);if(!p)continue;await M(i),this.pushSubscriptionData(i,c,p,s,r)}catch{continue}}})}async seedSubscription(e,t,s,r,n){const i=s.args??{},o=this.readAttachment(e),c=await this.resolveReactiveOutcome(r,i,n,{identity:o.identity,userId:o.userId});if(!c)return;const{sinceEpoch:d,sinceSeq:u}=s,l=n||u===void 0?void 0:this.evaluateResume(u,c.tables,d),m=n?void 0:l?.epoch??this.currentCdcEpoch();if(l?.resumable){this.seedSubscriptionMemo(e,t,c);try{e.send(`{"type":"resume","id":${JSON.stringify(t)}${Ve(l.cursor??0,m)}}`)}catch{}return}this.pushSubscriptionData(e,t,c,l?.cursor??this.currentCdcCursor(),m)}async handleShapeSubscribe(e,t,s){const r=this.shapeSubscribe(e,t,s);if(r!=="ok"){const i=r==="too_many"?"TOO_MANY_SUBSCRIPTIONS":"SUBSCRIPTION_PERSIST_FAILED",o=r==="too_many"?`subscription cap of ${String(S.MAX_SUBSCRIPTIONS_PER_SOCKET)} reached on this socket`:"failed to persist shape subscription attachment";this.sendShapeSubscribeError(e,t,i,o);return}const n=await this.seedShapeSubscription(e,t,s);if(n!=="ok"){this.shapeUnsubscribe(e,t),this.sendShapeSubscribeError(e,t,n.code,n.message);return}try{e.send(JSON.stringify({id:t,type:"ack"}))}catch{}}sendShapeSubscribeError(e,t,s,r){try{e.send(JSON.stringify({code:s,error:{code:s,message:r},id:t,type:"error"}))}catch{}}async seedShapeSubscription(e,t,s){const r=this.readAttachment(e),n={identity:r.identity,userId:r.userId},i=await this.relay?.seedRelayShape(e,t,s,n);if(i!==void 0)return i;let o;try{o=this.resolveShape(s.name,s.args??{},n)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=C(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{code:d.code,message:d.message}}if(!o)return{code:"SHAPE_NOT_FOUND",message:`shape "${s.name}" not found or not permitted`};try{return o.global?await this.seedGlobalShape(e,t,o,n,r.connectionId??""):await this.seedOpLogShape(e,t,s,o)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=C(c,{fallbackCode:"SHAPE_SEED_FAILED",redactedMessage:"shape seed failed"});return{code:d.code,message:d.message}}}async seedOpLogShape(e,t,s,r){const{baseCheckpoint:n,cursor:i,epoch:o,rowsPatch:c}=this.computeOpLogShapeSeed(s,r);return await M(e),this.sendPoke(e,[{rowsPatch:c,shapeId:t}],i,o,n)&&this.recordShapeMemo(e,t,i),"ok"}computeOpLogShapeSeed(e,t){const s=this.sql,r=this.currentCdcCursor()??0,n=this.currentCdcEpoch(),i=this.cdcEnabled()?$e(s):void 0,o=this.cdcEnabled()&&e.sinceSeq!==void 0&&e.sinceEpoch===n&&e.sinceSeq<=r&&(e.sinceSeq===r||i!==void 0&&i<=e.sinceSeq+1),c=o&&e.sinceSeq!==void 0?this.buildShapeDiff(s,t,e.sinceSeq,r):this.buildShapeSeed(s,t);return{baseCheckpoint:o?e.sinceSeq:void 0,cursor:r,epoch:n,rowsPatch:c}}async pokeShapeSubscribers(e,t,s){const r=[...this.state.getWebSockets()],n=t??this.currentCdcCursor()??0,i=this.sql,o=new Map;let c=0;const d=async l=>{if(this.isSocketExpired(l)){this.dropExpiredSocket(l);return}const m=this.readAttachment(l),{shapes:p}=m;if(p)try{const g={identity:m.identity,userId:m.userId},{emptyAdvanced:E,partAdvanced:yt,parts:Ae}=this.collectShapePokeParts(l,p,g,e,n,i,o);for(const te of E)this.recordShapeMemo(l,te,n);if(Ae.length>0&&(await M(l),this.sendPoke(l,Ae,n,s,void 0))){c+=1;for(const te of yt)this.recordShapeMemo(l,te,n)}}catch{}},u=Date.now();await je(r,d),this.fanout.shapePoke=re(this.fanout.shapePoke,r.length,c,Date.now()-u)}collectShapePokeParts(e,t,s,r,n,i,o){const c=[],d=[],u=[];for(const[l,m]of Object.entries(t))try{const p=this.resolveShape(m.name,m.args??{},s);if(!p||p.global||!r.has(p.table))continue;const g=this.shapeMemos.get(e)?.get(l)?.cursor??0,E=this.buildShapeDiff(i,p,g,n,o);E.length>0?(c.push({rowsPatch:E,shapeId:l}),u.push(l)):d.push(l)}catch(p){this.recordShapeError(`shape:poke:${l}`,p)}return{emptyAdvanced:d,partAdvanced:u,parts:c}}readShapeOpRange(e,t,s,r,n){const i=`${t}\0${String(s)}\0${String(r)}`,o=n?.get(i);if(o!==void 0)return o;const c=new Map,d=new Set([t]);let u=s;for(;;){const{changes:l,cursor:m}=this.readShapeCdcPage(e,u,d);for(const p of l)c.set(p.id,p);if(l.length===0||m===u||m>=r)break;u=m}return n?.set(i,c),c}readShapeCdcPage(e,t,s){return ne(e,{sinceSeq:t,tables:s})}buildShapeDiff(e,t,s,r,n){const i=this.readShapeOpRange(e,t.table,s,r,n);if(i.size===0)return[];const o=[...i.keys()],c=Ts(e,t.table,t.effectiveWhere,o),d=[];for(const[u,l]of i){if(c.has(u)){l.doc!==void 0&&d.push({key:u,op:l.op,table:t.table,value:me(l.doc,t.columns)});continue}l.op!=="insert"&&d.push({key:u,op:"delete",table:t.table})}return d}buildShapeSeed(e,t){return vs(e,t.table,t.effectiveWhere).map(s=>({key:s.id,op:"insert",table:t.table,value:me(s.doc,t.columns)}))}async seedGlobalShape(e,t,s,r,n){const i=await this.readGlobalShapeRows(s,r);if(!this.withinGlobalShapeBound(i.length,`shape:seed:${t}`,s.table))return{code:"SHAPE_GLOBAL_TOO_LARGE",message:`global shape membership for "${s.table}" exceeds the ${String(S.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`};const{next:o,rowsPatch:c}=We(i,new Map,{columns:s.columns,table:s.table});return await M(e),this.sendPoke(e,[{rowsPatch:c,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)&&(this.recordGlobalSnapshot(e,t,o),this.saveGlobalSnapshot(n,t,o)),await this.scheduleGlobalPoll(),"ok"}async refreshGlobalShape(e,t,s,r,n){const i=await this.readGlobalShapeRows(s,r);if(!this.withinGlobalShapeBound(i.length,`shape:poll:${t}`,s.table))return;const o=this.readGlobalSnapshot(e,t,n),{next:c,rowsPatch:d}=We(i,o,{columns:s.columns,table:s.table});if(d.length===0){this.recordGlobalSnapshot(e,t,c);return}await M(e),this.sendPoke(e,[{rowsPatch:d,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)&&(this.recordGlobalSnapshot(e,t,c),this.saveGlobalSnapshot(n,t,c))}readGlobalSnapshot(e,t,s){const r=this.globalShapeSnapshots.get(e)?.get(t);if(r)return r;const n=this.loadGlobalSnapshot(s,t);return this.recordGlobalSnapshot(e,t,n),n}recordGlobalSnapshot(e,t,s){let r=this.globalShapeSnapshots.get(e);r||(r=new Map,this.globalShapeSnapshots.set(e,r)),r.set(t,s)}loadGlobalSnapshot(e,t){if(e==="")return new Map;try{return Es(this.sql,e,t)}catch{return new Map}}saveGlobalSnapshot(e,t,s){if(e!=="")try{ws(this.sql,e,t,s)}catch{}}async scheduleGlobalPoll(e){if(this.globalPollScheduled)return;const{setAlarm:t}=this.state.storage;if(t){this.globalPollScheduled=!0;try{await t.call(this.state.storage,e??Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS)}catch{this.globalPollScheduled=!1}}}recordShapeError(e,t){this.logs.push({functionPath:e,level:"error",message:t instanceof Error?t.message:String(t),timestamp:Date.now()})}withinGlobalShapeBound(e,t,s){return e<=S.GLOBAL_SHAPE_MAX_ROWS?!0:(this.recordShapeError(t,new Error(`global shape membership for "${s}" (${String(e)} rows) exceeds the ${String(S.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`)),!1)}async pollGlobalShapes(){const e=[...this.state.getWebSockets()];let t=0;for(const s of e){if(this.isSocketExpired(s)){this.dropExpiredSocket(s);continue}const r=this.readAttachment(s),{shapes:n}=r;if(!n)continue;const i={identity:r.identity,userId:r.userId};t+=await this.pollSocketGlobalShapes(s,n,i,r.connectionId??"")}return t}async pollSocketGlobalShapes(e,t,s,r){let n=0;for(const[i,o]of Object.entries(t)){let c;try{c=this.resolveShape(o.name,o.args??{},s)}catch(d){n+=1,this.recordShapeError(`shape:poll:${i}`,d);continue}if(c?.global){n+=1;try{await this.refreshGlobalShape(e,i,c,s,r)}catch(d){this.recordShapeError(`shape:poll:${i}`,d)}}}return n}sendPoke(e,t,s,r,n){this.pokeSequence+=1;const i=`poke-${String(this.pokeSequence)}`,o=Re(t,{baseCheckpoint:n,checkpoint:s,epoch:r,lastMutationId:this.socketClientWatermark(e),pokeId:i});try{for(const c of o)e.send(c);return!0}catch{return!1}}socketClientWatermark(e){const t=this.readAttachment(e),{clientId:s}=t;if(s!==void 0)try{return ae(this.sql,t.userId??"",s)}catch{return}}recordShapeMemo(e,t,s){let r=this.shapeMemos.get(e);r||(r=new Map,this.shapeMemos.set(e,r)),r.set(t,{cursor:s})}seedSubscriptionMemo(e,t,s){let r=this.subMemos.get(e);r||(r=new Map,this.subMemos.set(e,r)),r.set(t,{lastJson:JSON.stringify(w(s.result??null)),tables:s.tables})}pushSubscriptionData(e,t,s,r,n){let i=this.subMemos.get(e);i||(i=new Map,this.subMemos.set(e,i));const o=Ve(r,n),c=JSON.stringify(w(s.result??null)),d=i.get(t);if(d?.lastJson===c){d.tables=s.tables;const m=this.socketClientWatermark(e),p=m===void 0?"":`,"lastMutationId":${String(m)}`;L(e,`{"type":"settled","id":${JSON.stringify(t)}${p}${o}}`);return}const u=[],l=(d===void 0?void 0:rs(d.lastJson,s.result,s.tables.values().next().value??"",u))===void 0?L(e,`{"type":"data","id":${JSON.stringify(t)},"data":${c}${o}}`):as(e,t,u,o);i.set(t,{lastJson:l?c:d?.lastJson??Xr,tables:s.tables})}async isUpgradeAllowed(e){const t=this.env??{},s=t.LUNORA_ALLOWED_ORIGINS;if(s&&s.trim()!==""){const n=e.headers.get("origin");if(!n||!s.split(",").map(i=>i.trim()).filter(i=>i.length>0).includes(n))return!1}const r=t.LUNORA_WS_BEARER;if(r&&r.length>0){const n=this.suppliedWsToken(e);if(!n||!j(n,r)&&!await this.isAdminSocket(e))return!1}return!0}suppliedWsToken(e){const t=le(e.headers.get("authorization"));return t!==void 0?t:new URL(e.url).searchParams.get("token")??void 0}async isAdminSocket(e){const t=this.env??{},s=t.LUNORA_ADMIN_TOKEN;if(!s||s.length===0)return!1;const r=this.suppliedWsToken(e);if(r===void 0)return!1;if(await Ns(s,r))return!0;const n=le(e.headers.get("authorization"))===void 0,i=jr.has((t.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN??"").trim().toLowerCase());return n&&i?!1:j(r,s)}armWebSocketKeepalive(){const e=this.state.setWebSocketAutoResponse;typeof e!="function"||typeof WebSocketRequestResponsePair>"u"||e.call(this.state,new WebSocketRequestResponsePair(Gr,zr))}async routeNonRpc(e,t){if(e.pathname==="/_lunora/relay"&&t.method==="POST")return this.relay?await this.relay.handleControl(t):new Response("relay tier inactive",{status:404});if(e.pathname==="/_lunora/route"&&t.method==="GET")return y({relayCount:this.relay?.relayCount()??0});if(e.pathname==="/rpc-batch"&&t.method==="POST")return this.handleBatchRpc(t);if(t.headers.get("Upgrade")==="websocket")return this.handleWebSocketUpgrade(t)}async handleWebSocketUpgrade(e){if(!await this.isUpgradeAllowed(e))return new Response("Forbidden",{status:403});const t=await this.isAdminSocket(e),s=new WebSocketPair,r=s[0],n=s[1];this.state.acceptWebSocket(n);const i=e.headers.get("x-lunora-userid")??void 0,o=rt(e.headers.get("x-lunora-identity")),c=Number(e.headers.get("x-lunora-identity-exp")),d=Number.isFinite(c)&&c>0?c:void 0;return n.serializeAttachment?.({admin:t,connectionId:crypto.randomUUID(),subs:{},...d===void 0?{}:{expiresAt:d},...o===void 0?{}:{identity:o},...i===void 0?{}:{userId:i}}),new Response(null,{status:101,webSocket:r})}cdcEnabled(){try{return this.sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",Oe).toArray().length>0}catch{return!1}}isSocketExpired(e){const{expiresAt:t}=this.readAttachment(e);return typeof t=="number"&&Date.now()>=t}dropExpiredSocket(e){try{e.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},type:"error"})),e.close(4001,"token_expired")}catch{}}setWhisperMembership(e,t,s){const r=this.readAttachment(e),n=r.whispers??[],i=n.includes(t);if(s){if(i||n.length>=S.MAX_WHISPER_TOPICS_PER_SOCKET)return;r.whispers=[...n,t]}else{if(!i)return;const o=n.filter(c=>c!==t);o.length===0?delete r.whispers:r.whispers=o}try{e.serializeAttachment?.(r)}catch{}}allowWhisper(e){const t=Date.now(),s=this.whisperBuckets.get(e)??{last:t,tokens:S.WHISPER_RATE_BURST},r=Math.min(S.WHISPER_RATE_BURST,s.tokens+(t-s.last)/1e3*S.WHISPER_RATE_PER_SEC);return r<1?(this.whisperBuckets.set(e,{last:t,tokens:r}),!1):(this.whisperBuckets.set(e,{last:t,tokens:r-1}),!0)}async broadcastWhisper(e,t,s){if(!this.allowWhisper(e))return;const r=JSON.stringify(s??null);if(r.length>S.MAX_WHISPER_BYTES)return;const n=this.readAttachment(e).userId,i=n===void 0?"":`,"from":${JSON.stringify(n)}`,o=`{"type":"whisper","topic":${JSON.stringify(t)},"data":${r}${i}}`;this.deliverWhisperLocal(t,o,e),await this.relay?.forwardWhisper(t,o)}deliverWhisperLocal(e,t,s){let r=0,n=0;for(const i of this.state.getWebSockets())r+=1,!(i===s||this.readAttachment(i).whispers?.includes(e)!==!0)&&(L(i,t),n+=1);return this.fanout.whisper=re(this.fanout.whisper,r,n,0),n}readAttachment(e){const t=e.deserializeAttachment?.();return t&&typeof t=="object"&&"subs"in t&&t.subs?t:{subs:{}}}}export{Yr as ROOT_DO_SIZE_WARN_BYTES,z as ROOT_SHARD_NAME,S as ShardDO,rs as subscriptionListDeltas};
101
+ Verify your email: ${s}`,to:t}},Ia=a=>{const e=r=>{throw new f("BAD_REQUEST",`recordQueueMessage: ${r}`)},t=a.messages;Array.isArray(t)||e("`messages` must be an array");const s=new Set(["ack","error","retry"]);return t.map((r,n)=>{(typeof r!="object"||r===null)&&e(`\`messages[${String(n)}]\` must be an object`);const i=r,o=typeof i.messageId=="string"?i.messageId:"",c=typeof i.queue=="string"?i.queue:"",d=typeof i.outcome=="string"?i.outcome:"";o===""&&e(`\`messages[${String(n)}].messageId\` is required`),c===""&&e(`\`messages[${String(n)}].queue\` is required`),s.has(d)||e(`\`messages[${String(n)}].outcome\` must be one of ack | error | retry`);const{attempts:u,timestamp:l}=i;return{attempts:typeof u=="number"&&Number.isFinite(u)?u:1,body:i.body,deadLettered:i.deadLettered===!0,error:typeof i.error=="string"?i.error:void 0,exportName:typeof i.exportName=="string"?i.exportName:void 0,messageId:o,outcome:d,queue:c,timestamp:typeof l=="number"&&Number.isFinite(l)?l:0}})},tt=100,R=a=>`${a.traceId}:${a.rootSpanId}`,de=256,_a=500,ue="lunora.dispatch",ka=a=>{const e=typeof a.exportName=="string"?a.exportName.trim():"";if(e==="")throw new f("BAD_REQUEST","sendQueueMessage: `exportName` is required");const t=a.delaySeconds;if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<0))throw new f("BAD_REQUEST","sendQueueMessage: `delaySeconds` must be a non-negative number");const s=Array.isArray(a.batch)?a.batch:void 0;if(s!==void 0&&(s.length===0||s.length>tt))throw new f("BAD_REQUEST",`sendQueueMessage: \`batch\` must contain between 1 and ${String(tt)} messages`);return{batch:s,body:a.body,contentType:typeof a.contentType=="string"?a.contentType:void 0,delaySeconds:t,exportName:e}},Ma=a=>{const e=typeof a.id=="string"?a.id.trim():"";if(e==="")throw new f("BAD_REQUEST","replayQueueMessage: `id` is required");const t=typeof a.target=="string"&&a.target.trim()!==""?a.target.trim():void 0;return{id:e,target:t}},Na=a=>{const e=typeof a.table=="string"?a.table:"",t=typeof a.index=="string"?a.index:"",s=typeof a.rowId=="string"?a.rowId:"";if(e.trim()==="")throw new f("BAD_REQUEST","rankBefore: `table` is required");if(t.trim()==="")throw new f("BAD_REQUEST","rankBefore: `index` is required");if(typeof a.partitionKey!="string")throw new f("BAD_REQUEST","rankBefore: `partitionKey` must be a string");if(s.trim()==="")throw new f("BAD_REQUEST","rankBefore: `rowId` is required");if(!Array.isArray(a.sortValues))throw new f("BAD_REQUEST","rankBefore: `sortValues` must be an array");return{index:t,partitionKey:a.partitionKey,rowId:s,sortValues:a.sortValues,table:e}},N=a=>{throw new f("BAD_REQUEST",a)},st=(a,e)=>((typeof a!="string"||a.trim()==="")&&N(`rankPage: \`${e}\` is required`),a),Ca=a=>{if(a===void 0)return;(typeof a!="object"||a===null||Array.isArray(a))&&N("rankPage: `after` must be an object");const e=a;return(typeof e.partitionKey!="string"||typeof e.rowId!="string"||!Array.isArray(e.sortValues))&&N("rankPage: `after` must have a string partitionKey, string rowId, and array sortValues"),{partitionKey:e.partitionKey,rowId:e.rowId,sortValues:e.sortValues}},Oa=a=>{const e=st(a.table,"table"),t=st(a.index,"index");a.take!==void 0&&typeof a.take!="number"&&N("rankPage: `take` must be a number"),a.cursor!==void 0&&a.cursor!==null&&typeof a.cursor!="string"&&N("rankPage: `cursor` must be a string or null"),a.partitionKey!==void 0&&typeof a.partitionKey!="string"&&N("rankPage: `partitionKey` must be a string"),a.directions!==void 0&&!Array.isArray(a.directions)&&N("rankPage: `directions` must be an array");const s=a.directions===void 0?void 0:a.directions.map(r=>r==="desc"?"desc":"asc");return{after:Ca(a.after),cursor:typeof a.cursor=="string"?a.cursor:void 0,directions:s,index:t,partitionKey:typeof a.partitionKey=="string"?a.partitionKey:void 0,take:typeof a.take=="number"?a.take:void 0,table:e}},La=a=>{try{const e=JSON.parse(a);if(Array.isArray(e)&&typeof e[0]=="string"&&typeof e[1]=="string")return{index:e[1],table:e[0]}}catch{}},xa=a=>{const e=a.changes;if(!Array.isArray(e))throw new f("BAD_REQUEST","applyCdc: `changes` must be an array");return{changes:e.map((t,s)=>{const r=t,{op:n}=r,i=typeof r.table=="string"?r.table:"",o=typeof r.id=="string"?r.id:"";if(i===""||o===""||n!=="insert"&&n!=="update"&&n!=="delete")throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}] must have a table, id, and op of insert|update|delete`);const c=r.doc;if(c!==void 0&&(typeof c!="object"||c===null||Array.isArray(c)))throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc must be an object`);const d=c;if(d!==void 0&&typeof d._id=="string"&&d._id!==o)throw new f("BAD_REQUEST",`applyCdc: changes[${String(s)}].doc._id must match the entry id`);return{doc:d,id:o,op:n,seq:typeof r.seq=="number"?r.seq:0,table:i,ts:typeof r.ts=="number"?r.ts:0}})}},$a=a=>{const e=t=>{const s=typeof t=="number"?t:Number(t);return Number.isFinite(s)&&s>=0?Math.floor(s):void 0};return{limit:e(a.limit),sinceSeq:e(a.sinceSeq)??0}},_=a=>a?{"x-d1-bookmark":a}:void 0,rt=a=>{if(a)try{const e=JSON.parse(a);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}},Pa=a=>{if(!a)return;const e=Number(a);return Number.isInteger(e)&&e>0?e:void 0},qa=a=>{const e=new Set;for(const t of a){const s=Lt(t);s!==""&&e.add(s)}return e},Da=a=>{if(a===void 0)return;const e=Number.parseInt(a,10);return Number.isFinite(e)&&e>0?e:void 0},Ua=(a,e)=>a==="1"||a==="true"?!0:a==="0"||a==="false"?!1:e,Ba=a=>{if(a===void 0)return 1;const e=Number.parseFloat(a);return Number.isFinite(e)?Math.min(1,Math.max(0,e)):1},Fa=a=>a>=1?!0:a<=0?!1:Math.random()<a,le=a=>{if(!a)return;const[e,...t]=a.split(" ");if(e?.toLowerCase()!=="bearer")return;const s=t.join(" ").trim();return s.length>0?s:void 0};class S{static MAX_STREAMS_PER_SOCKET=8;static MAX_SUBSCRIPTIONS_PER_SOCKET=32;static GLOBAL_SHAPE_POLL_INTERVAL_MS=2e3;static GLOBAL_SHAPE_MAX_ROWS=5e4;static MAX_WHISPER_TOPICS_PER_SOCKET=64;static MAX_WHISPER_BYTES=4096;static WHISPER_RATE_BURST=50;static WHISPER_RATE_PER_SEC=25;static rootSizeWarned=!1;static resetRootSizeWarning(){S.rootSizeWarned=!1}static nextPollAlarmTarget(e,t,s,r){const n=[e>0?r+S.GLOBAL_SHAPE_POLL_INTERVAL_MS:void 0,t,s].filter(i=>i!==void 0).map(i=>Math.max(i,r));return n.length>0?Math.min(...n):void 0}state;env;reactiveCache;drizzleHandle;transactionDepth=0;currentRequestBookmark;currentResponseBookmark;currentRequestUserId;currentRequestIp;currentRequestTraceparent;currentRequestTrace;traceSampling=new Map;dispatchSpans=new Map;lastTelemetrySink;currentRequestMutationId;currentRequestClientId;currentRequestClientSeq;currentMutatorClass;mutationBookkeepingCommitted=!1;lastIdempotencyTrimAt=0;currentRequestIdentity;currentRequestSystem=!1;pendingChangedTables=void 0;pendingRefreshTables=void 0;refreshInFlight=!1;subMemos=new WeakMap;shapeMemos=new WeakMap;globalShapeSnapshots=new WeakMap;globalPollScheduled=!1;pokeSequence=0;whisperBuckets=new WeakMap;streamCancellers=new WeakMap;metrics={errors:0,requests:0,sinceMs:Date.now()};fanout={shapePoke:ke(),whisper:ke()};shardBinding;relay;usedIndexes=new Set;functionStats=new Map;logs=new Xt;spans=new $r;metricSeries=new js;currentTracker;currentScannedTables;currentIndexHits;currentRequestReadTables;currentStmtSamples;currentRequestCacheHit;constructor(e,t,s={}){this.state=e,this.env=t,s.reactiveCache&&(this.reactiveCache=new ss(s.reactiveCache));const r={buildShapeDiff:(n,i,o)=>this.buildShapeDiff(this.sql,n,i,o),computeOpLogShapeSeed:(n,i)=>this.computeOpLogShapeSeed(n,i),currentCdcEpoch:()=>this.currentCdcEpoch(),deliverWhisperLocal:(n,i,o)=>this.deliverWhisperLocal(n,i,o),doName:()=>this.state.id?.name,env:()=>this.env,getWebSockets:()=>this.state.getWebSockets(),maskMetadata:()=>this.maskMetadata(),nextPokeId:()=>(this.pokeSequence+=1,`poke-${String(this.pokeSequence)}`),readAttachment:n=>this.readAttachment(n),recordShapePokeFanout:(n,i,o)=>{this.fanout.shapePoke=re(this.fanout.shapePoke,n,i,o)},resolveShape:(n,i,o)=>this.resolveShape(n,i,o),rlsMetadata:()=>this.rlsMetadata(),shardBinding:()=>this.shardBinding,sql:()=>this.sql};this.relay=Tr(r),this.armWebSocketKeepalive()}async fetch(e){const t=new URL(e.url);this.shardBinding=e.headers.get("x-lunora-shard-binding")??this.shardBinding;const s=await this.routeNonRpc(t,e);if(s!==void 0)return s;if(t.pathname!=="/rpc"||e.method!=="POST")return new Response("Not found",{status:404});let r;try{r=await e.json()}catch{return y({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(r.functionPath.startsWith(k))return this.handleAdminRpc(e,r.functionPath,r.args??{});this.currentRequestBookmark=e.headers.get("x-d1-bookmark")??void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=e.headers.get("x-lunora-userid")??void 0,this.currentRequestMutationId=e.headers.get("x-lunora-mutation-id")??void 0,this.currentRequestClientId=e.headers.get("x-lunora-client-id")??void 0,this.currentRequestClientSeq=Pa(e.headers.get("x-lunora-client-seq")),this.currentMutatorClass=void 0,this.mutationBookkeepingCommitted=!1,this.currentRequestIdentity=rt(e.headers.get("x-lunora-identity")),this.currentRequestIp=e.headers.get("x-lunora-client-ip")??void 0,this.currentRequestSystem=e.headers.get("x-lunora-system")==="1",this.currentRequestTraceparent=e.headers.get("traceparent")??void 0,this.currentRequestTrace=K(this.currentRequestTraceparent);const n=this.currentRequestTrace;this.traceSampling.set(n.traceId,{keepErrors:e.headers.get("x-lunora-sample-errors")!=="0",sampled:Et(this.currentRequestTraceparent)?.sampled??!0}),this.currentRequestReadTables=void 0,this.currentRequestCacheHit=void 0,this.metrics.requests+=1;const i=Date.now();this.currentScannedTables=new Set,this.currentIndexHits=new Set,this.currentStmtSamples=[];let o;try{if(r.functionPath.startsWith(Bt)){const E=await this.runRelationFanoutRead(r.functionPath,r.args??{});return y(E,200,_(this.currentResponseBookmark))}const c=this.isCustomMutator(r.functionPath)?this.classifyClientMutation():void 0;this.currentMutatorClass=c;const d=this.rejectNonNextMutation(r.functionPath,c,i);if(d!==void 0)return d;const u=this.readIdempotentResult(this.currentRequestMutationId);if(u!==void 0)return this.respondFromIdempotencyCache(r.functionPath,i,c,u.value);const l=await this.handleRpc(r.functionPath,O(r.args??{}));this.recordPostDispatchBookkeeping(l,c),c?.kind==="next"&&this.advanceClientMutationWatermark();const m=Date.now()-i;this.recordFunctionCall(r.functionPath,m,void 0,this.currentScannedTables,this.currentIndexHits),this.flushStmtSamples();const p=[...this.pendingChangedTables??[]];this.recordRequestLog(r.functionPath,r.args??{},m,"ok",p),this.maybeWarnRootSize();const g=this.buildDispatchResponse(c,w(l));return await this.flushChangedTables(),g}catch(c){this.metrics.errors+=1,o={thrown:c};const d=Date.now()-i,u=c instanceof Error?c.message:String(c),l=c instanceof ls&&c.kind==="occ";return c?.code!=="FUNCTION_NOT_FOUND"&&this.recordFunctionCall(r.functionPath,d,u,this.currentScannedTables,this.currentIndexHits,l),this.flushStmtSamples(),this.recordRequestLog(r.functionPath,r.args??{},d,"error",[...this.pendingChangedTables??[]],u),this.logs.push({functionPath:r.functionPath,level:"error",message:u,timestamp:Date.now()}),this.recordChangedTable(I),await this.flushChangedTables(),this.errorToResponse(c)}finally{const c=this.dispatchSpans.get(R(n));if((this.spans.hasTrace(n.traceId)||c?.collector!==void 0)&&this.recordDispatchRootSpan(r.functionPath,i,o,n),this.dispatchSpans.delete(R(n)),c?.sink?.flush)try{c.sink.flush({waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}this.flushSampledOutTrace(n,o!==void 0),this.traceSampling.delete(n.traceId),this.currentRequestTrace=void 0,this.currentRequestBookmark=void 0,this.currentResponseBookmark=void 0,this.currentRequestUserId=void 0,this.currentRequestMutationId=void 0,this.currentRequestClientId=void 0,this.currentRequestClientSeq=void 0,this.currentMutatorClass=void 0,this.mutationBookkeepingCommitted=!1,this.currentRequestIdentity=void 0,this.currentRequestIp=void 0,this.currentRequestSystem=!1,this.currentRequestTraceparent=void 0,this.currentScannedTables=void 0,this.currentIndexHits=void 0,this.currentRequestReadTables=void 0,this.currentRequestCacheHit=void 0,this.currentStmtSamples=void 0}}async webSocketMessage(e,t){return this.handleWebSocketMessage(e,t)}async webSocketClose(e,t,s,r){const n=this.readAttachment(e);n.connectionId!==void 0&&await this.dispatchLifecycle("disconnect",this.lifecycleInfo(n));const i=this.streamCancellers.get(e);if(i){for(const o of i.values())o.abort();this.streamCancellers.delete(e)}if(this.subMemos.delete(e),this.shapeMemos.delete(e),this.globalShapeSnapshots.delete(e),n.connectionId!==void 0)try{ps(this.sql,n.connectionId)}catch{}e.serializeAttachment?.(void 0),await this.relay?.announceDrain(e)}webSocketError(e,t){}async alarm(){return this.withTriggerTrace("alarm",async()=>this.handleAlarmBody())}lifecycleHookPaths(e){return[]}async dispatchLifecycle(e,t){for(const s of this.lifecycleHookPaths(e))try{await this.withRequestIdentity(t.userId,t.identity,()=>this.withSystemDispatch(()=>this.handleRpc(s,t.event)))}catch(r){this.logs.push({functionPath:s,level:"error",message:r instanceof Error?r.message:String(r),timestamp:Date.now()})}}runRelationFanoutRead(e,t){throw new f("NOT_IMPLEMENTED","__lunora_relation__: no schema bound — the base ShardDO cannot serve cross-shard relation reads",{status:500})}get sql(){const e=this.state.storage.sql,t=this.currentStmtSamples;if(t===void 0)return e;const s=e.exec;if(typeof s!="function")return e;const r=(n,...i)=>{const o=Date.now(),c=s.call(e,n,...i);if(c!==null&&typeof c=="object"){const d=c;if(typeof d.toArray=="function"){const u=d.toArray.bind(d);d.toArray=()=>{const l=u(),m=Date.now()-o;return t.push([n,m,l.length,0]),l}}if(typeof d.one=="function"){const u=d.one.bind(d);d.one=()=>{const l=u(),m=Date.now()-o;return t.push([n,m,1,0]),l}}if(typeof d.toArray!="function"&&typeof d.one!="function"){const u=Date.now()-o;t.push([n,u,0,0])}}else{const d=Date.now()-o;t.push([n,d,0,0])}return c};return new Proxy(e,{get(n,i){return i==="exec"?r:Reflect.get(n,i,n)}})}get db(){return this.drizzleHandle?this.drizzleHandle:(this.drizzleHandle=gt(this.state.storage,{logger:!1}),this.drizzleHandle)}async runInTransaction(e){if(this.transactionDepth>0)throw new f("NESTED_TRANSACTION","nested transactions are not supported in SQLite-in-DO",{status:500});const t=this.state.storage.sql;if(!t||typeof t.exec!="function")throw new f("SQL_UNAVAILABLE","storage.sql is not available on this ShardDO state",{status:500});const s=this.state.storage,r=async()=>{this.transactionDepth=1;try{return typeof s?.transaction=="function"?await s.transaction(async()=>e()):await e()}finally{this.transactionDepth=0}};return typeof this.state.blockConcurrencyWhile=="function"?this.state.blockConcurrencyWhile(r):r()}getInboundBookmark(){return this.currentRequestBookmark}setOutboundBookmark(e){this.currentResponseBookmark=e}getCurrentUserId(){return this.currentRequestUserId}getCurrentIp(){return this.currentRequestIp}getCurrentTraceparent(){return this.currentRequestTraceparent}getCurrentTrace(){return this.currentRequestTrace}getCurrentIdentity(){return this.currentRequestIdentity}isSystemDispatch(){return this.currentRequestSystem}runShardDataMigration(e){return Promise.reject(new f("MIGRATION_NOT_FOUND",`data migration "${e.id}" is not registered`,{status:404}))}ensureMigrated(){}tableRefs(e){}tableIndexes(e){return[]}tableColumns(e){return[]}storageColumns(){return{}}advisories(){return[]}rlsMetadata(){return{policies:[],roles:[]}}maskMetadata(){return{columns:[]}}storageRulesMetadata(){return{rules:[]}}studioFeatures(){return{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1}}evaluateFlags(e){return Promise.resolve({configured:!1,flags:[]})}runFlagSubscriptionRead(e,t,s){return Promise.resolve(null)}queuesMetadata(){return{queues:[]}}workflowsMetadata(){return{workflows:[]}}runtimeAdvisories(){const e=new Set([...this.usedIndexes].map(s=>s.slice(0,s.indexOf(":")))),t=[];for(const s of e)for(const r of this.tableIndexes(s))r.type==="vector"||this.usedIndexes.has(`${s}:${r.name}`)||t.push({cacheKey:`unused_index:${s}:${r.name}`,categories:["PERFORMANCE"],description:"A declared index has not been exercised by any query since this shard instance started. An unused index costs storage and is maintained on every write for no read benefit.",detail:`Index "${r.name}" on table "${s}" has not been used since this instance woke, though other indexes on "${s}" have — it may be redundant.`,facing:"INTERNAL",level:"INFO",metadata:{index:r.name,indexKind:r.type,since:"instance-woke",table:s},name:"unused_index",remediation:"Confirm over a representative window, then drop the index if no query needs it.",title:"Unused index"});return t}runShardExport(e){return Promise.resolve([])}runShardImport(e){return Promise.resolve({conflicts:0,errors:[],inserted:{}})}runShardWrite(e){return Promise.reject(new f("UNKNOWN_TABLE",`unknown table: ${e.table}`,{status:404}))}deleteRowThroughWriter(e,t){return Promise.reject(new f("UNKNOWN_TABLE",`unknown table: ${e}`,{status:404}))}async runShardBulkDelete(e){const t=Math.min(Math.max(Math.trunc(e.limit??Ze),1),Ze),{hasMore:s,ids:r}=Ft(this.sql,{filters:e.filters,limit:t,search:e.search,table:e.table});let n=0;for(const i of r)await this.deleteRowThroughWriter(e.table,i),n+=1;return{deleted:n,hasMore:s}}runShardRankBefore(e){return Promise.reject(new f("NOT_IMPLEMENTED","rankBefore is not implemented in base ShardDO",{status:500}))}runShardRankPage(e){return Promise.reject(new f("NOT_IMPLEMENTED","rankPage is not implemented in base ShardDO",{status:500}))}runShardCdcSync(e){const t=this.sql;return t.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",Oe).toArray().length>0?ne(t,{limit:e.limit,sinceSeq:e.sinceSeq}):{changes:[],cursor:e.sinceSeq}}currentCdcCursor(){return this.cdcEnabled()?Le(this.sql):void 0}currentCdcEpoch(){return this.cdcEnabled()?xe(this.sql):void 0}evaluateResume(e,t,s){const r=this.sql;if(!this.cdcEnabled())return{cursor:void 0,epoch:void 0,resumable:!1};const n=Le(r),i=xe(r);if(s!==i)return{cursor:n,epoch:i,resumable:!1};if(e>n)return{cursor:n,epoch:i,resumable:!1};if(e===n)return{cursor:n,epoch:i,resumable:!0};const o=$e(r);if(o===void 0||o>e+1)return{cursor:n,epoch:i,resumable:!1};if(t.size===0)return{cursor:n,epoch:i,resumable:!1};const{changes:c}=ne(r,{limit:Ye,sinceSeq:e});if(c.length>=Ye)return{cursor:n,epoch:i,resumable:!1};const d=c.some(u=>t.has(u.table));return{cursor:n,epoch:i,resumable:!d}}readIdempotentResult(e){if(e!==void 0)try{const t=fs(this.sql,this.currentRequestUserId??"",e);return t===void 0?void 0:{value:JSON.parse(t.resultJson)}}catch{return}}persistIdempotentResult(e){if(this.currentRequestMutationId===void 0)return;const t=Date.now();try{ms(this.sql,this.currentRequestUserId??"",this.currentRequestMutationId,JSON.stringify(w(e)),t),t-this.lastIdempotencyTrimAt>Zr&&(ys(this.sql,t-Vr),this.lastIdempotencyTrimAt=t)}catch{}}isCustomMutator(e){return!1}classifyClientMutation(){const e=this.currentRequestClientId,t=this.currentRequestClientSeq;if(e===void 0||t===void 0)return;const s=this.currentRequestUserId??"";let r;try{r=ae(this.sql,s,e)}catch{try{gs(this.sql),r=ae(this.sql,s,e)}catch{return}}const n=r+1;return t<=r?{expected:n,kind:"already"}:t===n?{expected:n,kind:"next"}:{expected:n,kind:"gap"}}rejectNonNextMutation(e,t,s){if(!(t===void 0||t.kind==="next"))return this.recordFunctionCall(e,Date.now()-s,void 0,this.currentScannedTables,this.currentIndexHits),t.kind==="already"?y({lastMutationId:t.expected-1,result:null},200,_(this.currentResponseBookmark)):y({error:{code:"OUT_OF_ORDER",expectedMutationId:t.expected,message:`out-of-order mutation; expected sequence ${String(t.expected)}`}},409,_(this.currentResponseBookmark))}respondFromIdempotencyCache(e,t,s,r){if(this.recordFunctionCall(e,Date.now()-t,void 0,this.currentScannedTables,this.currentIndexHits),s?.kind==="next")return this.advanceClientMutationWatermark(),this.buildDispatchResponse(s,r);const n=this.mutationCommitCursor();return y(n===void 0?{result:r}:{commitCursor:n,result:r},200,_(this.currentResponseBookmark))}mutationCommitCursor(){return this.currentRequestMutationId===void 0?void 0:this.currentCdcCursor()}buildDispatchResponse(e,t){if(e?.kind==="next")return y({lastMutationId:this.currentRequestClientSeq,result:t},200,_(this.currentResponseBookmark));const s=this.mutationCommitCursor();return y(s===void 0?{result:t}:{commitCursor:s,result:t},200,_(this.currentResponseBookmark))}commitMutationBookkeeping(e){this.persistIdempotentResult(e),this.currentMutatorClass?.kind==="next"&&this.advanceClientMutationWatermark({strict:!0}),this.mutationBookkeepingCommitted=!0}recordPostDispatchBookkeeping(e,t){this.mutationBookkeepingCommitted||(this.persistIdempotentResult(e),t?.kind==="next"&&this.advanceClientMutationWatermark())}advanceClientMutationWatermark(e){const t=this.currentRequestClientId,s=this.currentRequestClientSeq;if(!(t===void 0||s===void 0))try{Ss(this.sql,this.currentRequestUserId??"",t,s)}catch(r){if(e?.strict)throw r}}runShardApplyCdc(e){return Promise.reject(new f("NOT_IMPLEMENTED","applyCdc is not implemented in base ShardDO",{status:500}))}subscribe(e,t,s){const r=this.readAttachment(e);if(Object.keys(r.subs).length>=S.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";r.subs[t]=s;try{e.serializeAttachment?.(r)}catch{return delete r.subs[t],"serialize_failed"}return"ok"}unsubscribe(e,t){const s=this.readAttachment(e),r=s.subs[t];delete s.subs[t];try{e.serializeAttachment?.(s)}catch{r!==void 0&&(s.subs[t]=r);return}this.subMemos.get(e)?.delete(t)}shapeSubscribe(e,t,s){const r=this.readAttachment(e),n=r.shapes??{};if(Object.keys(r.subs).length+Object.keys(n).length>=S.MAX_SUBSCRIPTIONS_PER_SOCKET)return"too_many";n[t]=s,r.shapes=n;try{e.serializeAttachment?.(r)}catch{return delete r.shapes[t],"serialize_failed"}return"ok"}shapeUnsubscribe(e,t){const s=this.readAttachment(e),{shapes:r}=s;if(!r)return;const n=r[t];delete r[t];try{e.serializeAttachment?.(s)}catch{n!==void 0&&(r[t]=n);return}if(this.shapeMemos.get(e)?.delete(t),this.globalShapeSnapshots.get(e)?.delete(t),s.connectionId!==void 0)try{bs(this.sql,s.connectionId,t)}catch{}}matchesSubscription(e,t){if(e.table!==t.table)return!1;const{args:s}=e;if(!s)return!0;const{row:r}=t;if(!r)return!0;for(const[n,i]of Object.entries(s))if(r[n]!==i)return!1;return!0}broadcastDelta(e){const t=this.state.getWebSockets(),s=JSON.stringify(e);for(const r of t){const n=this.readAttachment(r);for(const[i,o]of Object.entries(n.subs))this.matchesSubscription(o,e)&&L(r,`{"type":"delta","id":${JSON.stringify(i)},"delta":${s}}`)}}executeSubscription(e,t,s){return Promise.resolve(null)}resolveShape(e,t,s){}isShapeRelayUniform(e,t){return this.relay?.isShapeRelayUniform(e,t)??!1}readGlobalShapeRows(e,t){return Promise.resolve([])}pollExternalSources(){return Promise.resolve(void 0)}scheduleSourcePoll(){return this.scheduleGlobalPoll()}ttlSweeps(){return[]}async pollTtlSweeps(){const e=this.ttlSweeps();if(e.length===0)return;const t=this.sql,s=Date.now();for(const r of e){let n=0,i=!0;for(;i&&n<ra;){const o=hs(t,r,s,sa);for(const c of o.ids)await this.deleteRowThroughWriter(r.table,c);i=o.hasMore,n+=1}}return s+aa}scheduleTtlSweep(){return this.scheduleGlobalPoll()}currentShardKey(){return this.state.id?.name??z}recordExternalSourceError(e,t){this.recordShapeError(`source:${e}`,t)}executeStream(e,t){return null}async runCachedQuery(e,t,s){if(!this.reactiveCache)return s();const r=this.currentTracker,n=Ot();this.currentTracker=n;const i=this.reactiveCache.stats().hits,o=this.getCurrentUserId(),c=this.getCurrentIdentity(),d=o===void 0&&c===void 0?null:Ee({claims:c??null,userId:o??null});try{const u=await this.reactiveCache.run(Ne(e,t,d),n.collect(),s);return this.currentRequestCacheHit=this.reactiveCache.stats().hits>i,this.currentRequestReadTables=qa(n.collect()),u}finally{this.currentTracker=r}}getCtxDbReadHook(){return(e,t)=>{this.currentTracker?.recordRead(e,t??_e),t===_e&&this.currentScannedTables?.add(e)}}getCtxDbIndexUseHook(){return(e,t)=>{this.usedIndexes.add(`${e}:${t}`),this.currentIndexHits?.add(JSON.stringify([e,t]))}}recordChangedTable(e){this.pendingChangedTables??=new Set,this.pendingChangedTables.add(e)}async flushMigrationProgress(){this.recordChangedTable(Nt),await this.flushChangedTables()}recordUserLog(e,t,s,r,n,i,o,c){const d=c??this.currentRequestTrace,u={args:s,...o===void 0?{}:{eventName:o},fields:n,functionPath:e,level:t,message:r,shardKey:this.state.id?.name,spanId:d?.rootSpanId,traceId:d?.traceId,ts:Date.now(),userId:this.getCurrentUserId()};this.logs.push({fields:n,functionPath:e,level:t,message:r,timestamp:u.ts});try{Cr(u)}catch{}if(i?.onLog)try{i.onLog(u,{waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}makeLogger(e,t,s){const r=(n,i)=>{const{fields:o,message:c}=Nr(i,s);this.recordUserLog(e,n,i,c,o,t)};return{debug:(...n)=>{r("debug",n)},error:(...n)=>{r("error",n)},event:(n,i)=>{this.recordUserLog(e,"info",[n],n,s?{...s,...i}:i,t,n)},fatal:(...n)=>{r("fatal",n)},info:(...n)=>{r("info",n)},log:(...n)=>{r("log",n)},trace:(...n)=>{r("trace",n)},warn:(...n)=>{r("warn",n)},with:n=>this.makeLogger(e,t,s?{...s,...n}:n)}}makeTracer(e,t,s){const r=s??K(void 0);return wt({anchor:r,fuseCloudflareSpans:t?.fuseCloudflareTraces===!0,functionPath:e,record:n=>{this.recordSpan(n,t,r.sampled)},resolveCloudflareTracing:Jr,shardKey:this.state.id?.name,userId:()=>this.getCurrentUserId()})}resolveDispatchAnchor(e){return(e?void 0:this.getCurrentTrace())??K(void 0)}instrumentDb(e,t,s,r){const n=r===void 0?"off":r.instrumentDatabase??"summary";return n==="off"?e:Fs(e,{anchor:s,functionPath:t,mode:n,record:i=>{this.recordSpan(i,r,s.sampled)},shardKey:this.state.id?.name,tally:this.dispatchTally(s),userId:()=>this.getCurrentUserId()})}makeFetch(e,t,s){const r=(n,i)=>globalThis.fetch(n,i);return s===void 0||s.traceFetch===!1?r:Rt({anchor:t,functionPath:e,...typeof s.traceFetch=="object"&&s.traceFetch.propagate!==void 0?{propagate:s.traceFetch.propagate}:{},record:n=>{this.recordSpan(n,s,t.sampled)},shardKey:this.state.id?.name,userId:()=>this.getCurrentUserId()},r)}makeDispatchSpan(e,t){this.lastTelemetrySink=t??this.lastTelemetrySink,t!==void 0&&(J(this.dispatchSpans,de),this.dispatchSpans.set(R(e),this.dispatchSpans.get(R(e))??{sink:t}));const s=()=>{J(this.dispatchSpans,de);const r=R(e),n=this.dispatchSpans.get(r)??{sink:t};return n.collector??=At({spanId:e.rootSpanId,traceId:e.traceId}),this.dispatchSpans.set(r,n),n.collector};return{addEvent:(r,n)=>{s().handle.addEvent(r,n)},spanContext:()=>({spanId:e.rootSpanId,traceId:e.traceId}),addLink:r=>{s().handle.addLink(r)},recordEvaluation:r=>{s().handle.recordEvaluation(r)},recordException:r=>{s().handle.recordException(r)},setAttribute:(r,n)=>{s().handle.setAttribute(r,n)},setAttributes:r=>{s().handle.setAttributes(r)}}}makeMetrics(e,t){return Tt({functionPath:e,record:s=>{this.recordMetric(s,t)},shardKey:this.state.id?.name})}recordMetric(e,t){const s=this.currentRequestTrace?.traceId,r=s===void 0?e:{...e,traceId:s},n=o=>{try{o()}catch{}};n(()=>{this.metricSeries.push(r)});const i=t?.metricHistory;if(i!==void 0&&i!==!1){const o=this.state.storage.sql,c=typeof i=="object"?i:{};n(()=>{er(o,r,s,c)})}t?.onMetric&&n(()=>t.onMetric?.(r,{waitUntil:this.state.waitUntil?.bind(this.state)}))}async handleWebSocketMessage(e,t){if(this.isSocketExpired(e)){this.dropExpiredSocket(e);return}const s=typeof t=="string"?t:new TextDecoder().decode(t);let r;try{r=JSON.parse(s)}catch{e.send(JSON.stringify({message:"invalid envelope",type:"error"}));return}if(r.type==="connect"){const n=this.readAttachment(e);if(n.connected===!0)return;r.context!==void 0&&(n.context=r.context),r.clientId!==void 0&&(n.clientId=r.clientId),n.connected=!0;try{e.serializeAttachment?.(n)}catch{}await this.dispatchLifecycle("connect",this.lifecycleInfo(n));return}if(r.type==="subscribe"&&r.query){const{functionPath:n}=r.query,i=n?.startsWith(k)===!0;if(i&&this.readAttachment(e).admin!==!0){e.send(JSON.stringify({id:r.id,message:"admin subscription requires admin authorization",type:"error"}));return}let o;try{o=r.query.args===void 0?r.query:{...r.query,args:O(r.query.args)}}catch{try{e.send(JSON.stringify({code:"BAD_SUBSCRIPTION_ARGS",error:{code:"BAD_SUBSCRIPTION_ARGS",message:"subscription args failed wire decoding"},id:r.id,type:"error"}))}catch{}return}const c=this.subscribe(e,r.id,o);if(c!=="ok"){const d=c==="too_many"?"TOO_MANY_SUBSCRIPTIONS":"SUBSCRIPTION_PERSIST_FAILED",u=c==="too_many"?`subscription cap of ${String(S.MAX_SUBSCRIPTIONS_PER_SOCKET)} reached on this socket`:"failed to persist subscription attachment";try{e.send(JSON.stringify({code:d,error:{code:d,message:u},id:r.id,type:"error"}))}catch{}return}e.send(JSON.stringify({id:r.id,type:"ack"})),n&&await this.seedSubscription(e,r.id,o,n,i);return}if(r.type==="shape_subscribe"&&r.shape){let n;try{n=r.shape.args===void 0?void 0:O(r.shape.args)}catch{this.sendShapeSubscribeError(e,r.id,"BAD_SUBSCRIPTION_ARGS","shape args failed wire decoding");return}await this.handleShapeSubscribe(e,r.id,{args:n,name:r.shape.name,sinceEpoch:r.sinceEpoch,sinceSeq:r.sinceCheckpoint});return}if(r.type==="shape_unsubscribe"){this.shapeUnsubscribe(e,r.id),e.send(JSON.stringify({id:r.id,type:"ack"}));return}if(r.type==="stream"&&r.query?.functionPath){if(r.query.functionPath.startsWith(k)){e.send(JSON.stringify({id:r.id,message:"streams must be public",type:"error"}));return}this.handleStream(e,r.id,r.query.functionPath,O(r.query.args??{})).catch(()=>{});return}if(r.type==="whisper_subscribe"||r.type==="whisper_unsubscribe"){if(typeof r.topic=="string"&&r.topic.length>0){const n=r.type==="whisper_subscribe";this.setWhisperMembership(e,r.topic,n),n&&await this.relay?.announce()}return}if(r.type==="whisper"){typeof r.topic=="string"&&r.topic.length>0&&await this.broadcastWhisper(e,r.topic,r.data);return}if(r.type==="unsubscribe"){const n=this.streamCancellers.get(e),i=n?.get(r.id);i&&(i.abort(),n?.delete(r.id)),this.unsubscribe(e,r.id),e.send(JSON.stringify({id:r.id,type:"ack"}))}}async handleAlarmBody(){this.globalPollScheduled=!1;let e;try{e=await this.pollGlobalShapes()}catch(n){this.recordShapeError("shape:poll",n),e=1}let t;try{t=await this.pollExternalSources()}catch(n){this.recordShapeError("source:poll",n),t=Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS}let s;try{s=await this.pollTtlSweeps()}catch(n){this.recordShapeError("ttl:sweep",n),s=Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS}await this.flushChangedTables();const r=S.nextPollAlarmTarget(e,t,s,Date.now());r!==void 0&&await this.scheduleGlobalPoll(r)}dispatchTally(e){J(this.dispatchSpans,de);const t=R(e),s=this.dispatchSpans.get(t)??{};return s.dbTally??=Ws(),this.dispatchSpans.set(t,s),s.dbTally}async withTriggerTrace(e,t){const s=K(void 0),r=Date.now(),n=this.currentRequestTrace===void 0;n&&(this.currentRequestTrace=s);let i;try{return await t()}catch(o){throw i={thrown:o},o}finally{n&&this.currentRequestTrace===s&&(this.currentRequestTrace=void 0),(this.spans.hasTrace(s.traceId)||this.dispatchSpans.get(R(s))?.collector!==void 0)&&this.recordDispatchRootSpan(e,r,i,s),this.dispatchSpans.delete(R(s)),this.flushTelemetry()}}flushTelemetry(){try{this.lastTelemetrySink?.flush?.({waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}recordDispatchRootSpan(e,t,s,r){const n=this.dispatchSpans.get(R(r)),i=Date.now()-t,o=n?.dbTally===void 0||n.dbTally.calls===0?void 0:Ks(n.dbTally),c=n?.collector===void 0?void 0:{...n.collector.collected,attributes:{...o,...n.collector.collected.attributes}};try{this.spans.push(vt({anchor:r,...c===void 0?{}:{collected:c},durationMs:i,failure:s,functionPath:e,shardKey:this.state.id?.name,startTs:t,userId:this.getCurrentUserId()}))}catch{}n?.collector!==void 0&&this.exportWideEvent(e,i,s,r,{collected:c??n.collector.collected,sink:n.sink})}exportWideEvent(e,t,s,r,n){try{const{attributes:i}=n.collected;this.recordUserLog(e,s===void 0?"info":"error",[ue],ue,{...i,[se.durationMs]:t,[se.functionPath]:e,[se.ok]:s===void 0},n.sink,ue,r)}catch{}}recordSpan(e,t,s){try{this.spans.push(e)}catch{}if(!t?.onSpan)return;const r=this.traceSampling.get(e.traceId);if(r!==void 0){if(!r.sampled){if(r.sink=t,e.dispatch!==!0){const n=r.held??(r.held=[]);n.push(e),n.length>_a&&n.shift()}return}this.emitSpan(e,t);return}s!==!1&&this.emitSpan(e,t)}emitSpan(e,t){if(t.onSpan)try{t.onSpan(e,{waitUntil:this.state.waitUntil?.bind(this.state)})}catch{}}flushSampledOutTrace(e,t){const s=this.traceSampling.get(e.traceId);if(!s||s.sampled||!s.keepErrors)return;const{held:r,sink:n}=s;if(!(!n?.onSpan||r===void 0||r.length===0||!(t||r.some(i=>!i.ok))))for(const i of r)this.emitSpan(i,n)}lifecycleInfo(e){return{event:{connectionId:e.connectionId??"",shardKey:this.state.id?.name??z,userId:e.userId??null,...e.context===void 0?{}:{context:e.context}},identity:e.identity,userId:e.userId}}async withSystemDispatch(e){const t=this.currentRequestSystem;this.currentRequestSystem=!0;try{return await e()}finally{this.currentRequestSystem=t}}collectMetrics(){const e=this.state.storage.sql?.databaseSize;let{requests:t}=this.metrics,{errors:s}=this.metrics;try{const i=xt(this.state.storage.sql);t=i.requests,s=i.errors}catch{}let r=[];try{r=$t(this.state.storage.sql)}catch{}let n=[];try{n=nr(this.state.storage.sql)}catch{}return{cache:this.reactiveCache?this.reactiveCache.stats():null,databaseSize:typeof e=="number"?e:null,errors:s,functions:this.collectFunctionStats().functions,history:this.collectFunctionMetricBuckets(),indexHits:r,queryStats:n,requests:t,shard:this.state.id?.name??z,sinceMs:this.metrics.sinceMs,uptimeMs:Date.now()-this.metrics.sinceMs}}recordFunctionCall(e,t,s,r,n,i=!1){const o=Date.now(),c=r?[...r]:[],d=n?[...n].map(m=>La(m)).filter(m=>m!==void 0):[];try{Pt(this.state.storage.sql,{conflicted:i,durationMs:t,errored:s!==void 0,errorMessage:s,indexHits:d,path:e,scannedTables:c,ts:o})}catch{}const u=this.functionStats.get(e),l=u??{calls:0,conflicts:0,errors:0,lastCalledAt:o,lastErrorAt:null,lastErrorMessage:null,maxDurationMs:0,path:e,scannedTables:[],scans:0,totalDurationMs:0};l.calls+=1,l.totalDurationMs+=t,l.maxDurationMs=Math.max(l.maxDurationMs,t),l.lastCalledAt=o,c.length>0&&(l.scans+=c.length,qt(l.scannedTables,c)),s!==void 0&&(l.errors+=1,l.lastErrorAt=o,l.lastErrorMessage=s),i&&(l.conflicts+=1),u===void 0&&this.functionStats.set(e,l)}flushStmtSamples(){const e=this.currentStmtSamples;if(!(!e||e.length===0))try{const t=this.state.storage.sql;for(const[s,r,n,i]of e)try{ar(t,s,r,n,i)}catch{}}catch{}}collectFunctionStats(){try{return{functions:Dt(this.state.storage.sql),sinceMs:this.metrics.sinceMs}}catch{return{functions:[...this.functionStats.values()].toSorted((e,t)=>t.lastCalledAt-e.lastCalledAt),sinceMs:this.metrics.sinceMs}}}collectFunctionMetricBuckets(){try{return Ut(this.state.storage.sql)}catch{return[]}}maybeWarnRootSize(){if(S.rootSizeWarned||this.state.id?.name!==z)return;const e=this.state.storage.sql?.databaseSize;typeof e!="number"||e<Yr||(S.rootSizeWarned=!0,console.warn(`[@lunora/do] __root__ Durable Object SQLite size is ${String(e)} bytes (>= 1 GiB, 10% of the 10 GiB per-DO ceiling). Plan a \`.shardBy()\` migration before you hit the wall. See https://lunora.sh/docs/concepts/sharding for guidance.`))}errorToResponse(e){const{body:t,redacted:s,status:r}=C(e,{encodeData:w,fallbackCode:"RPC_FAILED",redactedMessage:"internal error"});return s&&console.error("[@lunora/do] internal error:",e),y({error:t},r)}async handleBatchRpc(e){let t;try{t=await e.json()}catch{return y({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}if(!Array.isArray(t.calls))return y({error:{code:"BAD_REQUEST",message:"batch `calls` must be an array"}},400);if(t.calls.length>Pe)return y({error:{code:"BAD_REQUEST",message:`batch exceeds the ${String(Pe)}-call limit`}},400);const s=[];let r;for(const n of t.calls){const i=await this.dispatchBatchEntry(e,n);i.bookmark!==void 0&&(r=i.bookmark),s.push({body:i.body,id:i.id,status:i.status})}return y({results:s},200,_(r))}async dispatchBatchEntry(e,t){try{const s=await this.fetch(xs(e,t));return{body:await s.json(),bookmark:s.headers.get("x-d1-bookmark")??void 0,id:t.id,status:s.status}}catch(s){const{body:r,status:n}=C(s,{fallbackCode:"BATCH_ENTRY_FAILED"});return{body:{error:r},bookmark:void 0,id:t?.id,status:n}}}async handleAdminRpc(e,t,s){if(!this.isAdminAuthorized(e))return y({error:{code:"ADMIN_FORBIDDEN",message:"admin introspection is disabled or the bearer token is invalid"}},403);try{const r=this.readAdminOp(t,s);if(r)return y({result:r.result},200);if(t===h.runMigration){const i=ta(s),o=await this.runShardDataMigration(i);return await this.flushChangedTables(),this.recordAudit("runMigration",{id:i.id,detail:{changed:o.changed,direction:o.direction,dryRun:o.dryRun,processed:o.processed}}),y({result:o},200)}if(t===h.exportShard){const i=It(s),o=await this.runShardExport({batchSize:i.batchSize,tables:i.tables});return y({result:{rows:o}},200)}if(t===h.importShard){const i=_t(s),o=await this.runShardImport({rows:i.rows,startLine:i.startLine});return await this.flushChangedTables(),this.recordAudit("importShard",{detail:{conflicts:o.conflicts,errors:o.errors.length,inserted:o.inserted}}),y({result:o},200)}if(t===h.writeRow){const i=na(s),o=await this.runShardWrite(i);return await this.flushChangedTables(),this.recordAudit("writeRow",{table:i.table,id:o.id??i.id,detail:{op:o.op}}),y({result:o},200)}if(t===h.deleteRows){const i=ga(s),o=await this.runShardBulkDelete(i);return await this.flushChangedTables(),this.recordAudit("deleteRows",{table:i.table,detail:{deleted:o.deleted,hasMore:o.hasMore}}),y({result:o},200)}if(t===h.clearTable){const i=Sa(s),o=await this.runShardBulkDelete(i);return await this.flushChangedTables(),this.recordAudit("clearTable",{table:i.table,detail:{deleted:o.deleted,hasMore:o.hasMore}}),y({result:o},200)}if(t===h.rankBefore){const i=await this.runShardRankBefore(Na(s));return y({result:i},200)}if(t===h.rankPage){const i=await this.runShardRankPage(Oa(s));return y({result:i},200)}if(t===h.cdcSync){const i=this.runShardCdcSync($a(s));return y({result:i},200)}if(t===h.applyCdc){const i=await this.runShardApplyCdc(xa(s));return await this.flushChangedTables(),this.recordAudit("applyCdc",{detail:{applied:i.applied}}),y({result:i},200)}return t===h.runAs?this.handleRunAs(s):await this.handleExtraAdminOp(t,s)||y({error:{code:"UNKNOWN_ADMIN_OP",message:`unknown admin op: ${t}`}},404)}catch(r){return this.errorToResponse(r)}}async handleExtraAdminOp(e,t){if(e===h.recordAuthEvent)return this.handleRecordAuthEvent(t);if(e===h.recordContainerEvent)return this.handleRecordContainerEvent(t);if(e===h.recordMail)return this.handleRecordMail(t);if(e===h.clearCapturedMail)return this.handleClearCapturedMail();if(e===h.sendTestMail)return this.handleSendTestMail(t);if(e===h.recordQueueMessage)return this.handleRecordQueueMessage(t);if(e===h.clearQueueMessages)return this.handleClearQueueMessages();if(e===h.sendQueueMessage)return this.handleSendQueueMessage(t);if(e===h.replayQueueMessage)return this.handleReplayQueueMessage(t);if(e===h.createWorkflowInstance)return this.handleCreateWorkflowInstance(t);if(e===h.getWorkflowInstanceStatus)return this.handleGetWorkflowInstanceStatus(t);if(e===h.listFlags)return this.handleListFlags(t);const s=await this.handleIssueTriageOp(e,t);return s!==void 0?s:this.handlePitrAdminOp(e,t)}async handleIssueTriageOp(e,t){const s=this.parseIssueTriagePatch(e,t);if(s===void 0)return;const r=ca(t),n=typeof t.updatedBy=="string"?t.updatedBy:void 0,i=this.state.storage.sql,o=zs(i,r,s,Date.now(),n);return this.recordChangedTable(B),await this.flushChangedTables(),this.recordAudit(e.slice(k.length),{detail:{...s,hash:r}}),y({result:{state:o}},200)}parseIssueTriagePatch(e,t){if(e===h.resolveIssue)return{status:"resolved"};if(e===h.ignoreIssue)return{status:"ignored"};if(e===h.assignIssue)return{assignee:da(t),status:"open"};if(e===h.setIssueSeverity)return{severity:ua(t)}}handleRecordAuthEvent(e){const t=ba(e);try{kt(this.state.storage.sql,{outcome:t.outcome,ts:Date.now()})}catch{}return y({result:{recorded:!0}},200)}async handleRecordContainerEvent(e){const t=wa(e);if(this.logs.push(t),t.level==="error"||t.exitCode!==void 0&&t.exitCode!==0){const s={durationMs:0,errorMessage:t.message,functionPath:t.functionPath,outcome:"error",shardKey:this.state.id?.name,ts:t.timestamp};this.persistRequestLog(s,this.requestLogConfig()),this.recordChangedTable(I),await this.flushChangedTables()}return y({result:{recorded:!0}},200)}async handleRunAs(e){const t=Ra(e),s=await this.withRequestIdentity(t.userId,t.identity,()=>this.handleRpc(t.functionPath,t.args));return await this.flushChangedTables(),this.recordAudit("runAs",{detail:{functionPath:t.functionPath,runAsUserId:t.userId}}),y({result:s},200)}resolveWorkflowBinding(e){const t=this.workflowsMetadata().workflows.find(r=>r.exportName===e);if(!t)throw new f("BAD_REQUEST",`workflow "${e}" is not declared`);const s=this.env?.[t.binding];if(typeof s!="object"||s===null||typeof s.create!="function"||typeof s.get!="function")throw new f("BAD_REQUEST",`workflow binding "${t.binding}" is not available on this deployment`);return s}async handleCreateWorkflowInstance(e){const t=la(e),s=await this.resolveWorkflowBinding(t.exportName).create({id:t.id,params:t.params}),r=await s.status(),n={id:s.id,status:et(r.status)};return this.recordAudit("createWorkflowInstance",{id:s.id,detail:{exportName:t.exportName}}),y({result:n},200)}async handleGetWorkflowInstanceStatus(e){const t=ha(e),s=await(await this.resolveWorkflowBinding(t.exportName).get(t.id)).status(),r={error:fa(s.error),id:t.id,output:s.output,status:et(s.status)};return y({result:r},200)}async handleListFlags(e){const t=e.context,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0,r=await this.evaluateFlags(s);return y({result:r},200)}async withRequestIdentity(e,t,s){const r=this.currentRequestUserId,n=this.currentRequestIdentity;this.currentRequestUserId=e,this.currentRequestIdentity=t;try{return await s()}finally{this.currentRequestUserId=r,this.currentRequestIdentity=n}}handleRecordMail(e){const t=Ta(e),s=Me(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleClearCapturedMail(){const e=Yt(this.state.storage.sql);return y({result:e},200)}handleSendTestMail(e){const t=Aa(e),s=Me(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleRecordQueueMessage(e){const t=Ia(e),s=dr(this.state.storage.sql,t,Date.now());return y({result:s},200)}handleClearQueueMessages(){const e=hr(this.state.storage.sql);return y({result:e},200)}async handleSendQueueMessage(e){const t=ka(e),{binding:s}=this.resolveQueueBinding(t.exportName);let r;return t.batch===void 0?(await s.send(t.body,{contentType:t.contentType,delaySeconds:t.delaySeconds}),r=1):(await s.sendBatch(t.batch.map(n=>({body:n,contentType:t.contentType,delaySeconds:t.delaySeconds}))),r=t.batch.length),this.recordAudit("sendQueueMessage",{detail:{count:r,exportName:t.exportName}}),y({result:{sent:r}},200)}async handleReplayQueueMessage(e){const t=Ma(e),s=lr(this.state.storage.sql,t.id);if(s===void 0)throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" was not found`,{status:404});if(or(s.body))throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has a truncated or unserializable body and can't be replayed faithfully`,{status:422});const r=t.target??this.resolveReplayTarget(s.queue)??s.exportName;if(typeof r!="string"||r==="")throw new f("BAD_REQUEST",`replayQueueMessage: captured message "${t.id}" has no declared producer to replay onto (pass \`target\`)`);const{binding:n}=this.resolveQueueBinding(r);return await n.send(s.body),this.recordAudit("replayQueueMessage",{detail:{messageId:s.messageId,target:r},id:t.id}),y({result:{sent:1,target:r}},200)}resolveQueueBinding(e){const t=this.queuesMetadata().queues.find(r=>r.exportName===e);if(!t)throw new f("BAD_REQUEST",`queue "${e}" is not declared`);const s=this.env?.[t.binding];if(typeof s!="object"||s===null||typeof s.send!="function")throw new f("BAD_REQUEST",`queue binding "${t.binding}" is not available on this deployment`);return{binding:s,metadata:t}}resolveReplayTarget(e){const{queues:t}=this.queuesMetadata(),s=t.find(r=>r.deadLetterQueue===e);return s!==void 0?s.exportName:t.find(r=>r.name===e)?.exportName}recordAudit(e,t={}){const s=this.state.storage.sql,r=this.getCurrentUserId(),n=r===void 0?t.detail:{...t.detail,userId:r};Cs(s,{detail:n,id:t.id,op:e,table:t.table,ts:Date.now()})}recordRequestLog(e,t,s,r,n,i){const o=this.requestLogConfig();if(r==="ok"&&!Fa(o.sampleRate))return;const c={cacheHit:this.currentRequestCacheHit,durationMs:s,errorMessage:i,functionPath:e,identity:this.currentRequestIdentity,outcome:r,redactedArgs:Object.keys(t).length===0?void 0:t,shardKey:this.state.id?.name,tablesRead:this.currentRequestReadTables===void 0?[]:[...this.currentRequestReadTables],tablesWritten:n,ts:Date.now(),userId:this.getCurrentUserId()};this.persistRequestLog(c,o)}persistRequestLog(e,t){const s={captureRaw:t.captureRaw,retention:t.retention};try{Ar(this.state.storage.sql,e,s)}catch{}if(t.emit||e.outcome==="error")try{Ir(e,s)}catch{}}requestLogConfig(){const e=this.env??{};return{captureRaw:Ce(this.env),emit:Ua(e.LUNORA_REQUEST_LOG_EMIT,Ce(this.env)),retention:Da(e.LUNORA_REQUEST_LOG_RETENTION),sampleRate:Ba(e.LUNORA_REQUEST_LOG_SAMPLE)}}async handlePitrAdminOp(e,t){const s=typeof t.time=="number"||typeof t.time=="string"?t.time:void 0;if(e===h.getPitrBookmark)return y({result:await es(this.state.storage,s)},200);if(e!==h.pitrRestore)return;const r=t.restart===!0,n=typeof t.bookmark=="string"?t.bookmark:void 0,i=await ts(this.state.storage,{bookmark:n,time:s});this.cdcEnabled()&&Rs(this.sql),this.recordAudit("pitrRestore",{detail:{restart:r,restoredTo:i.restoredTo,undoBookmark:i.undoBookmark}});const o=y({result:{...i,restarted:r}},200);return r&&this.state.abort?.("lunora PITR restore"),o}readAdminOp(e,t){this.ensureMigrated();const s=this.state.storage.sql,r=this.readAdminWildcardOp(e);if(r!==void 0)return{result:r,tables:new Set([b])};if(e===h.getAuditLog)return this.readAdminAuditLog(s,t);if(e===h.getRequestLog)return this.readAdminRequestLog(s,t);if(e===h.getIssues)return this.readAdminIssues(s,t);const n=this.readAdminDurableSignal(e,s,t);if(n)return n;if(e===h.readTablePage)return this.readAdminTablePage(s,t);if(e===h.facetColumn)return this.readAdminFacetColumn(s,t);if(e===h.runSql)return this.readAdminRunSql(s,t);const i=this.readAdminTableSignal(e,s,t);return i||this.readAdminStorageSignal(e,s,t)||null}readAdminTableSignal(e,t,s){if(e===h.listTableIndexes||e===h.describeTable){const r=typeof s.table=="string"?s.table:"";return{result:e===h.describeTable?{columns:this.tableColumns(r)}:{indexes:this.tableIndexes(r)},tables:new Set([r===""?b:r])}}if(e===h.describeTables){const r=Array.isArray(s.tables)?s.tables.filter(n=>typeof n=="string"):[];return{result:{columnsByTable:Object.fromEntries(r.map(n=>[n,this.tableColumns(n)]))},tables:new Set(r.length===0?[b]:r)}}if(e===h.migrationStatus){const r=typeof s.id=="string"?s.id:void 0;return{result:{migrations:Ct(t,r)},tables:new Set([b])}}}readAdminStorageSignal(e,t,s){if(e===h.storageReferences)return this.readAdminStorageReferences(t,s);if(e===h.storageOrphans)return this.readAdminStorageOrphans(t,s)}readAdminStorageReferences(e,t){const s=Array.isArray(t.keys)?t.keys.filter(r=>typeof r=="string"):[];return{result:Wt(e,this.storageColumns(),s),tables:new Set([b])}}readAdminStorageOrphans(e,t){const s=Array.isArray(t.liveKeys)?t.liveKeys.filter(n=>typeof n=="string"):[],r=Qr(e,this.storageColumns(),s);return r.truncated&&console.warn(`[@lunora/do] storageOrphans scan truncated after checking ${String(r.scanned)} storage references; reporting the first ${String(r.references.length)} dangling reference(s).`),{result:r,tables:new Set([b])}}readAdminWildcardOp(e){if(e===h.listTables)return Kt(this.state.storage.sql);if(e===h.getMetrics)return this.collectMetrics();if(e===h.getFunctionStats)return this.collectFunctionStats();if(e===h.listSubscriptions)return this.collectSubscriptions();if(e===h.getFanoutMetrics)return this.collectFanoutMetrics();if(e===h.getLogs)return{entries:this.logs.entries()};if(e===h.getTraces){const t=Br(this.spans.entries());return{total:t.total,traces:t.traces}}if(e===h.getMetricSeries)return{series:this.metricSeries.entries()};if(e===h.getMetricHistory)return sr(this.sql);if(e===h.getSettings)return cs(this.env);if(e===h.getSecurityAudit)return ds(this.env);if(e===h.getAdvisories)return{advisories:[...this.advisories(),...this.runtimeAdvisories()]};if(e===h.rlsPolicies)return this.rlsMetadata();if(e===h.maskPolicies)return this.maskMetadata();if(e===h.storageRules)return this.storageRulesMetadata();if(e===h.studioFeatures)return this.studioFeatures();if(e===h.listWorkflows)return this.workflowsMetadata();if(e===h.listQueues)return this.queuesMetadata()}collectSubscriptions(){return Ht(this.state.getWebSockets().map(e=>this.readAttachment(e)))}collectFanoutMetrics(){const e=Qt(this.state.getWebSockets().map(s=>this.readAttachment(s))),t=this.relay?.relayCount()??0;return{...e,maxRelays:this.relay?.maxRelays()??Te,promoted:t>0,relayCount:t,shapePoke:this.fanout.shapePoke,sinceMs:this.metrics.sinceMs,whisper:this.fanout.whisper}}readAdminAuditLog(e,t){we(e);const s=typeof t.limit=="number"?t.limit:void 0,r=typeof t.sinceSeq=="number"?t.sinceSeq:void 0;return{result:{entries:Os(e,{limit:s,sinceSeq:r})},tables:new Set([b])}}readAdminRequestLog(e,t){W(e);const s=t.outcome==="ok"||t.outcome==="error"?t.outcome:void 0;return{result:{entries:Or(e,{functionPathPrefix:typeof t.functionPathPrefix=="string"?t.functionPathPrefix:void 0,limit:typeof t.limit=="number"?t.limit:void 0,outcome:s,shardKey:typeof t.shardKey=="string"?t.shardKey:void 0,sinceSeq:typeof t.sinceSeq=="number"?t.sinceSeq:void 0,tableTouched:typeof t.tableTouched=="string"?t.tableTouched:void 0,userId:typeof t.userId=="string"?t.userId:void 0})},tables:new Set([b])}}readAdminIssues(e,t){return W(e),{result:{issues:xr(e,{functionPathPrefix:typeof t.functionPathPrefix=="string"?t.functionPathPrefix:void 0,limit:typeof t.limit=="number"?t.limit:void 0,shardKey:typeof t.shardKey=="string"?t.shardKey:void 0,status:ia(t.status)?t.status:void 0,userId:typeof t.userId=="string"?t.userId:void 0})},tables:new Set([b])}}readAdminDurableSignal(e,t,s){if(e===h.getAuthMetrics)return this.readAdminAuthMetrics(t);if(e===h.getCapturedMail)return this.readAdminCapturedMail(t,s);if(e===h.getQueueMessages)return this.readAdminQueueMessages(t,s)}readAdminAuthMetrics(e){let t;try{t=Mt(e)}catch{t={attempts:0,failureRate:0,failures:0,history:[],sinceMs:0}}return{result:t,tables:new Set([b])}}readAdminCapturedMail(e,t){const s=typeof t.limit=="number"?t.limit:void 0;let r;try{r=Vt(e,{limit:s})}catch{r={entries:[]}}return{result:r,tables:new Set([Zt])}}readAdminQueueMessages(e,t){const s=typeof t.limit=="number"?t.limit:void 0,r=typeof t.queue=="string"?t.queue:void 0;let n;try{n=ur(e,{limit:s,queue:r})}catch{n={entries:[]}}return{result:n,tables:new Set([A])}}readAdminTablePage(e,t){const s=typeof t.table=="string"?t.table:"";return{result:Gt(e,{filters:be(t.filters),limit:typeof t.limit=="number"?t.limit:void 0,offset:typeof t.offset=="number"?t.offset:void 0,orderBy:ya(t.orderBy),refs:this.tableRefs(s),search:typeof t.search=="string"?t.search:void 0,skipCount:typeof t.skipCount=="boolean"?t.skipCount:void 0,table:s}),tables:new Set([s===""?b:s])}}readAdminFacetColumn(e,t){const s=typeof t.table=="string"?t.table:"";return{result:zt(e,{column:typeof t.column=="string"?t.column:"",filters:be(t.filters),limit:typeof t.limit=="number"?t.limit:void 0,search:typeof t.search=="string"?t.search:void 0,table:s}),tables:new Set([s===""?b:s])}}readAdminRunSql(e,t){const s=typeof t.sql=="string"?t.sql:"";return{result:us(e,s),tables:new Set([b])}}executeAdminSubscription(e,t){const s=this.readAdminOp(e,t);return s?{result:s.result,tables:s.tables}:null}async resolveReactiveOutcome(e,t,s,r){if(s)return this.executeAdminSubscription(e,t);if(e.startsWith(jt)){const n=await this.runFlagSubscriptionRead(e,t,r);return n===null?null:{result:n,tables:new Set([b])}}return this.executeSubscription(e,t,r)}isIdentityIndependent(e){return e.startsWith(k)}resolveReactiveOutcomeDeduped(e,t,s,r,n){if(!this.isIdentityIndependent(e))return this.resolveReactiveOutcome(e,t,s,r);const i=Ne(e,t,null),o=n.get(i);if(o!==void 0)return o;const c=this.resolveReactiveOutcome(e,t,s,r);return n.set(i,c),c}isAdminAuthorized(e){const t=(this.env??{}).LUNORA_ADMIN_TOKEN;if(!t||t.length===0)return!1;const s=le(e.headers.get("authorization"));return s!==void 0&&j(s,t)}async handleStream(e,t,s,r){const n=this.executeStream(s,r);if(!n){e.send(JSON.stringify({error:{code:"NOT_FOUND",message:`stream not registered: ${s}`},id:t,type:"error"}));return}let i=this.streamCancellers.get(e);if(i||(i=new Map,this.streamCancellers.set(e,i)),i.size>=S.MAX_STREAMS_PER_SOCKET){try{e.send(JSON.stringify({error:{code:"TOO_MANY_STREAMS",message:`stream cap of ${String(S.MAX_STREAMS_PER_SOCKET)} reached on this socket`},id:t,type:"error"}))}catch{}return}const o=new AbortController;i.set(t,o),e.send(JSON.stringify({id:t,type:"ack"}));try{for await(const c of n.iterator(o.signal)){if(o.signal.aborted)break;await M(e),e.send(JSON.stringify({data:w(c),id:t,type:"chunk"}))}o.signal.aborted||e.send(JSON.stringify({id:t,type:"complete"}))}catch(c){const{body:d,redacted:u}=C(c,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});u&&console.error("[@lunora/do] unhandled stream error:",c),e.send(JSON.stringify({error:{code:d.code,message:d.message},id:t,type:"error"}))}finally{i.delete(t),i.size===0&&this.streamCancellers.delete(e)}}async flushChangedTables(){const e=this.pendingChangedTables;if(this.pendingChangedTables=void 0,!(!e||e.size===0)){if(this.pendingRefreshTables)for(const t of e)this.pendingRefreshTables.add(t);else this.pendingRefreshTables=e;if(!this.refreshInFlight){if(typeof this.state.waitUntil=="function"){this.state.waitUntil(this.drainSubscriptionRefreshes());return}await this.drainSubscriptionRefreshes()}}}async drainSubscriptionRefreshes(){if(!this.refreshInFlight){this.refreshInFlight=!0;try{let e=this.pendingRefreshTables;for(;e&&e.size>0;){this.pendingRefreshTables=void 0;const t=this.currentCdcCursor(),s=this.currentCdcEpoch();await Promise.all([this.refreshSubscriptions(e),this.pokeShapeSubscribers(e,t,s),this.relay?.onFlush(e,t??0)]),e=this.pendingRefreshTables}}finally{this.refreshInFlight=!1}}}async refreshSubscriptions(e){const t=[...this.state.getWebSockets()],s=this.currentCdcCursor(),r=this.currentCdcEpoch(),n=new Map;await je(t,async i=>{if(this.isSocketExpired(i)){this.dropExpiredSocket(i);return}const o=this.readAttachment(i);for(const[c,d]of Object.entries(o.subs)){const{functionPath:u}=d;if(!u)continue;const l=u.startsWith(k),m=this.subMemos.get(i)?.get(c);if(!(m&&!m.tables.has(b)&&!ea(m.tables,e)))try{const p=await this.resolveReactiveOutcomeDeduped(u,d.args??{},l,{identity:o.identity,userId:o.userId},n);if(!p)continue;await M(i),this.pushSubscriptionData(i,c,p,s,r)}catch{continue}}})}async seedSubscription(e,t,s,r,n){const i=s.args??{},o=this.readAttachment(e),c=await this.resolveReactiveOutcome(r,i,n,{identity:o.identity,userId:o.userId});if(!c)return;const{sinceEpoch:d,sinceSeq:u}=s,l=n||u===void 0?void 0:this.evaluateResume(u,c.tables,d),m=n?void 0:l?.epoch??this.currentCdcEpoch();if(l?.resumable){this.seedSubscriptionMemo(e,t,c);try{e.send(`{"type":"resume","id":${JSON.stringify(t)}${Ve(l.cursor??0,m)}}`)}catch{}return}this.pushSubscriptionData(e,t,c,l?.cursor??this.currentCdcCursor(),m)}async handleShapeSubscribe(e,t,s){const r=this.shapeSubscribe(e,t,s);if(r!=="ok"){const i=r==="too_many"?"TOO_MANY_SUBSCRIPTIONS":"SUBSCRIPTION_PERSIST_FAILED",o=r==="too_many"?`subscription cap of ${String(S.MAX_SUBSCRIPTIONS_PER_SOCKET)} reached on this socket`:"failed to persist shape subscription attachment";this.sendShapeSubscribeError(e,t,i,o);return}const n=await this.seedShapeSubscription(e,t,s);if(n!=="ok"){this.shapeUnsubscribe(e,t),this.sendShapeSubscribeError(e,t,n.code,n.message);return}try{e.send(JSON.stringify({id:t,type:"ack"}))}catch{}}sendShapeSubscribeError(e,t,s,r){try{e.send(JSON.stringify({code:s,error:{code:s,message:r},id:t,type:"error"}))}catch{}}async seedShapeSubscription(e,t,s){const r=this.readAttachment(e),n={identity:r.identity,userId:r.userId},i=await this.relay?.seedRelayShape(e,t,s,n);if(i!==void 0)return i;let o;try{o=this.resolveShape(s.name,s.args??{},n)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=C(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{code:d.code,message:d.message}}if(!o)return{code:"SHAPE_NOT_FOUND",message:`shape "${s.name}" not found or not permitted`};try{return o.global?await this.seedGlobalShape(e,t,o,n,r.connectionId??""):await this.seedOpLogShape(e,t,s,o)}catch(c){this.recordShapeError(`shape:seed:${t}`,c);const{body:d}=C(c,{fallbackCode:"SHAPE_SEED_FAILED",redactedMessage:"shape seed failed"});return{code:d.code,message:d.message}}}async seedOpLogShape(e,t,s,r){const{baseCheckpoint:n,cursor:i,epoch:o,rowsPatch:c}=this.computeOpLogShapeSeed(s,r);return await M(e),this.sendPoke(e,[{rowsPatch:c,shapeId:t}],i,o,n)&&this.recordShapeMemo(e,t,i),"ok"}computeOpLogShapeSeed(e,t){const s=this.sql,r=this.currentCdcCursor()??0,n=this.currentCdcEpoch(),i=this.cdcEnabled()?$e(s):void 0,o=this.cdcEnabled()&&e.sinceSeq!==void 0&&e.sinceEpoch===n&&e.sinceSeq<=r&&(e.sinceSeq===r||i!==void 0&&i<=e.sinceSeq+1),c=o&&e.sinceSeq!==void 0?this.buildShapeDiff(s,t,e.sinceSeq,r):this.buildShapeSeed(s,t);return{baseCheckpoint:o?e.sinceSeq:void 0,cursor:r,epoch:n,rowsPatch:c}}async pokeShapeSubscribers(e,t,s){const r=[...this.state.getWebSockets()],n=t??this.currentCdcCursor()??0,i=this.sql,o=new Map;let c=0;const d=async l=>{if(this.isSocketExpired(l)){this.dropExpiredSocket(l);return}const m=this.readAttachment(l),{shapes:p}=m;if(p)try{const g={identity:m.identity,userId:m.userId},{emptyAdvanced:E,partAdvanced:yt,parts:Ae}=this.collectShapePokeParts(l,p,g,e,n,i,o);for(const te of E)this.recordShapeMemo(l,te,n);if(Ae.length>0&&(await M(l),this.sendPoke(l,Ae,n,s,void 0))){c+=1;for(const te of yt)this.recordShapeMemo(l,te,n)}}catch{}},u=Date.now();await je(r,d),this.fanout.shapePoke=re(this.fanout.shapePoke,r.length,c,Date.now()-u)}collectShapePokeParts(e,t,s,r,n,i,o){const c=[],d=[],u=[];for(const[l,m]of Object.entries(t))try{const p=this.resolveShape(m.name,m.args??{},s);if(!p||p.global||!r.has(p.table))continue;const g=this.shapeMemos.get(e)?.get(l)?.cursor??0,E=this.buildShapeDiff(i,p,g,n,o);E.length>0?(c.push({rowsPatch:E,shapeId:l}),u.push(l)):d.push(l)}catch(p){this.recordShapeError(`shape:poke:${l}`,p)}return{emptyAdvanced:d,partAdvanced:u,parts:c}}readShapeOpRange(e,t,s,r,n){const i=`${t}\0${String(s)}\0${String(r)}`,o=n?.get(i);if(o!==void 0)return o;const c=new Map,d=new Set([t]);let u=s;for(;;){const{changes:l,cursor:m}=this.readShapeCdcPage(e,u,d);for(const p of l)c.set(p.id,p);if(l.length===0||m===u||m>=r)break;u=m}return n?.set(i,c),c}readShapeCdcPage(e,t,s){return ne(e,{sinceSeq:t,tables:s})}buildShapeDiff(e,t,s,r,n){const i=this.readShapeOpRange(e,t.table,s,r,n);if(i.size===0)return[];const o=[...i.keys()],c=Ts(e,t.table,t.effectiveWhere,o),d=[];for(const[u,l]of i){if(c.has(u)){l.doc!==void 0&&d.push({key:u,op:l.op,table:t.table,value:me(l.doc,t.columns)});continue}l.op!=="insert"&&d.push({key:u,op:"delete",table:t.table})}return d}buildShapeSeed(e,t){return vs(e,t.table,t.effectiveWhere).map(s=>({key:s.id,op:"insert",table:t.table,value:me(s.doc,t.columns)}))}async seedGlobalShape(e,t,s,r,n){const i=await this.readGlobalShapeRows(s,r);if(!this.withinGlobalShapeBound(i.length,`shape:seed:${t}`,s.table))return{code:"SHAPE_GLOBAL_TOO_LARGE",message:`global shape membership for "${s.table}" exceeds the ${String(S.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`};const{next:o,rowsPatch:c}=We(i,new Map,{columns:s.columns,table:s.table});return await M(e),this.sendPoke(e,[{rowsPatch:c,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)&&(this.recordGlobalSnapshot(e,t,o),this.saveGlobalSnapshot(n,t,o)),await this.scheduleGlobalPoll(),"ok"}async refreshGlobalShape(e,t,s,r,n){const i=await this.readGlobalShapeRows(s,r);if(!this.withinGlobalShapeBound(i.length,`shape:poll:${t}`,s.table))return;const o=this.readGlobalSnapshot(e,t,n),{next:c,rowsPatch:d}=We(i,o,{columns:s.columns,table:s.table});if(d.length===0){this.recordGlobalSnapshot(e,t,c);return}await M(e),this.sendPoke(e,[{rowsPatch:d,shapeId:t}],this.currentCdcCursor()??0,this.currentCdcEpoch(),void 0)&&(this.recordGlobalSnapshot(e,t,c),this.saveGlobalSnapshot(n,t,c))}readGlobalSnapshot(e,t,s){const r=this.globalShapeSnapshots.get(e)?.get(t);if(r)return r;const n=this.loadGlobalSnapshot(s,t);return this.recordGlobalSnapshot(e,t,n),n}recordGlobalSnapshot(e,t,s){let r=this.globalShapeSnapshots.get(e);r||(r=new Map,this.globalShapeSnapshots.set(e,r)),r.set(t,s)}loadGlobalSnapshot(e,t){if(e==="")return new Map;try{return Es(this.sql,e,t)}catch{return new Map}}saveGlobalSnapshot(e,t,s){if(e!=="")try{ws(this.sql,e,t,s)}catch{}}async scheduleGlobalPoll(e){if(this.globalPollScheduled)return;const{setAlarm:t}=this.state.storage;if(t){this.globalPollScheduled=!0;try{await t.call(this.state.storage,e??Date.now()+S.GLOBAL_SHAPE_POLL_INTERVAL_MS)}catch{this.globalPollScheduled=!1}}}recordShapeError(e,t){this.logs.push({functionPath:e,level:"error",message:t instanceof Error?t.message:String(t),timestamp:Date.now()})}withinGlobalShapeBound(e,t,s){return e<=S.GLOBAL_SHAPE_MAX_ROWS?!0:(this.recordShapeError(t,new Error(`global shape membership for "${s}" (${String(e)} rows) exceeds the ${String(S.GLOBAL_SHAPE_MAX_ROWS)}-row cap; narrow it with a shape predicate or an RLS read policy`)),!1)}async pollGlobalShapes(){const e=[...this.state.getWebSockets()];let t=0;for(const s of e){if(this.isSocketExpired(s)){this.dropExpiredSocket(s);continue}const r=this.readAttachment(s),{shapes:n}=r;if(!n)continue;const i={identity:r.identity,userId:r.userId};t+=await this.pollSocketGlobalShapes(s,n,i,r.connectionId??"")}return t}async pollSocketGlobalShapes(e,t,s,r){let n=0;for(const[i,o]of Object.entries(t)){let c;try{c=this.resolveShape(o.name,o.args??{},s)}catch(d){n+=1,this.recordShapeError(`shape:poll:${i}`,d);continue}if(c?.global){n+=1;try{await this.refreshGlobalShape(e,i,c,s,r)}catch(d){this.recordShapeError(`shape:poll:${i}`,d)}}}return n}sendPoke(e,t,s,r,n){this.pokeSequence+=1;const i=`poke-${String(this.pokeSequence)}`,o=Re(t,{baseCheckpoint:n,checkpoint:s,epoch:r,lastMutationId:this.socketClientWatermark(e),pokeId:i});try{for(const c of o)e.send(c);return!0}catch{return!1}}socketClientWatermark(e){const t=this.readAttachment(e),{clientId:s}=t;if(s!==void 0)try{return ae(this.sql,t.userId??"",s)}catch{return}}recordShapeMemo(e,t,s){let r=this.shapeMemos.get(e);r||(r=new Map,this.shapeMemos.set(e,r)),r.set(t,{cursor:s})}seedSubscriptionMemo(e,t,s){let r=this.subMemos.get(e);r||(r=new Map,this.subMemos.set(e,r)),r.set(t,{lastJson:JSON.stringify(w(s.result??null)),tables:s.tables})}pushSubscriptionData(e,t,s,r,n){let i=this.subMemos.get(e);i||(i=new Map,this.subMemos.set(e,i));const o=Ve(r,n),c=JSON.stringify(w(s.result??null)),d=i.get(t);if(d?.lastJson===c){d.tables=s.tables;const m=this.socketClientWatermark(e),p=m===void 0?"":`,"lastMutationId":${String(m)}`;L(e,`{"type":"settled","id":${JSON.stringify(t)}${p}${o}}`);return}const u=[],l=(d===void 0?void 0:rs(d.lastJson,s.result,s.tables.values().next().value??"",u))===void 0?L(e,`{"type":"data","id":${JSON.stringify(t)},"data":${c}${o}}`):as(e,t,u,o);i.set(t,{lastJson:l?c:d?.lastJson??Xr,tables:s.tables})}async isUpgradeAllowed(e){const t=this.env??{},s=t.LUNORA_ALLOWED_ORIGINS;if(s&&s.trim()!==""){const n=e.headers.get("origin");if(!n||!s.split(",").map(i=>i.trim()).filter(i=>i.length>0).includes(n))return!1}const r=t.LUNORA_WS_BEARER;if(r&&r.length>0){const n=this.suppliedWsToken(e);if(!n||!j(n,r)&&!await this.isAdminSocket(e))return!1}return!0}suppliedWsToken(e){const t=le(e.headers.get("authorization"));return t!==void 0?t:new URL(e.url).searchParams.get("token")??void 0}async isAdminSocket(e){const t=this.env??{},s=t.LUNORA_ADMIN_TOKEN;if(!s||s.length===0)return!1;const r=this.suppliedWsToken(e);if(r===void 0)return!1;if(await Ns(s,r))return!0;const n=le(e.headers.get("authorization"))===void 0,i=jr.has((t.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN??"").trim().toLowerCase());return n&&i?!1:j(r,s)}armWebSocketKeepalive(){const e=this.state.setWebSocketAutoResponse;typeof e!="function"||typeof WebSocketRequestResponsePair>"u"||e.call(this.state,new WebSocketRequestResponsePair(Gr,zr))}async routeNonRpc(e,t){if(e.pathname==="/_lunora/relay"&&t.method==="POST")return this.relay?await this.relay.handleControl(t):new Response("relay tier inactive",{status:404});if(e.pathname==="/_lunora/route"&&t.method==="GET")return y({relayCount:this.relay?.relayCount()??0});if(e.pathname==="/rpc-batch"&&t.method==="POST")return this.handleBatchRpc(t);if(t.headers.get("Upgrade")==="websocket")return this.handleWebSocketUpgrade(t)}async handleWebSocketUpgrade(e){if(!await this.isUpgradeAllowed(e))return new Response("Forbidden",{status:403});const t=await this.isAdminSocket(e),s=new WebSocketPair,r=s[0],n=s[1];this.state.acceptWebSocket(n);const i=e.headers.get("x-lunora-userid")??void 0,o=rt(e.headers.get("x-lunora-identity")),c=Number(e.headers.get("x-lunora-identity-exp")),d=Number.isFinite(c)&&c>0?c:void 0;return n.serializeAttachment?.({admin:t,connectionId:crypto.randomUUID(),subs:{},...d===void 0?{}:{expiresAt:d},...o===void 0?{}:{identity:o},...i===void 0?{}:{userId:i}}),new Response(null,{status:101,webSocket:r})}cdcEnabled(){try{return this.sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",Oe).toArray().length>0}catch{return!1}}isSocketExpired(e){const{expiresAt:t}=this.readAttachment(e);return typeof t=="number"&&Date.now()>=t}dropExpiredSocket(e){try{e.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},type:"error"})),e.close(4001,"token_expired")}catch{}}setWhisperMembership(e,t,s){const r=this.readAttachment(e),n=r.whispers??[],i=n.includes(t);if(s){if(i||n.length>=S.MAX_WHISPER_TOPICS_PER_SOCKET)return;r.whispers=[...n,t]}else{if(!i)return;const o=n.filter(c=>c!==t);o.length===0?delete r.whispers:r.whispers=o}try{e.serializeAttachment?.(r)}catch{}}allowWhisper(e){const t=Date.now(),s=this.whisperBuckets.get(e)??{last:t,tokens:S.WHISPER_RATE_BURST},r=Math.min(S.WHISPER_RATE_BURST,s.tokens+(t-s.last)/1e3*S.WHISPER_RATE_PER_SEC);return r<1?(this.whisperBuckets.set(e,{last:t,tokens:r}),!1):(this.whisperBuckets.set(e,{last:t,tokens:r-1}),!0)}async broadcastWhisper(e,t,s){if(!this.allowWhisper(e))return;const r=JSON.stringify(s??null);if(r.length>S.MAX_WHISPER_BYTES)return;const n=this.readAttachment(e).userId,i=n===void 0?"":`,"from":${JSON.stringify(n)}`,o=`{"type":"whisper","topic":${JSON.stringify(t)},"data":${r}${i}}`;this.deliverWhisperLocal(t,o,e),await this.relay?.forwardWhisper(t,o)}deliverWhisperLocal(e,t,s){let r=0,n=0;for(const i of this.state.getWebSockets())r+=1,!(i===s||this.readAttachment(i).whispers?.includes(e)!==!0)&&(L(i,t),n+=1);return this.fanout.whisper=re(this.fanout.whisper,r,n,0),n}readAttachment(e){const t=e.deserializeAttachment?.();return t&&typeof t=="object"&&"subs"in t&&t.subs?t:{subs:{}}}}export{Yr as ROOT_DO_SIZE_WARN_BYTES,z as ROOT_SHARD_NAME,S as ShardDO,rs as subscriptionListDeltas};
@@ -0,0 +1 @@
1
+ import{isLunoraError as _}from"@lunora/errors";const L=/[\w.-]/u,x=t=>{let e="";for(const r of t)e+=L.test(r)?r:"_";return e},C=t=>{if(typeof t.name!="string"||t.name.length===0)throw new Error("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new Error("recordEvaluation `score` must be a finite number");const e=x(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},D=t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}},K=t=>typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:D(t),y=(t,e)=>{if(t===void 0&&e===void 0)return;const r={};if(e!==void 0)for(const[n,a]of Object.entries(e))r[n]=K(a);if(t!==void 0)for(const[n,a]of Object.entries(t))r[n]=K(a);return Object.keys(r).length===0?void 0:r},E=t=>{const e=new Uint8Array(t);crypto.getRandomValues(e);let r="";for(const n of e)r+=n.toString(16).padStart(2,"0");return r},S=/^[0-9a-f]+$/,F=(t,e,r=!0)=>`00-${t}-${e}-${r?"01":"00"}`,R=t=>{if(t==null)return;const e=t.trim().toLowerCase().split("-"),[r,n,a,s]=e;if(!(e.length<4||r===void 0||r.length!==2||!S.test(r)||r==="ff"||r==="00"&&e.length!==4||n===void 0||a===void 0||s===void 0||s.length!==2||!S.test(s)||n.length!==32||a.length!==16||!S.test(n)||!S.test(a)||n==="00000000000000000000000000000000"||a==="0000000000000000"))return{parentSpanId:a,sampled:(Number.parseInt(s,16)&1)===1,traceId:n}},f=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),W=t=>{const e=R(t);return{rootSpanId:e?.parentSpanId??E(8),sampled:e?.sampled??!0,traceId:e?.traceId??E(16)}},T=t=>_(t)?t.code:t instanceof Error?t.constructor.name:"Error",N=t=>{const e=Object.keys(t);return e.length>0&&e.every(r=>r==="attributes"||r==="kind"||r==="links")},U=128,q=128,z=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},H=t=>{try{return new URL(t).host}catch{return t}},V=(t,e)=>{try{return t(new URL(e))}catch{return!1}},J=t=>t===void 0?{}:N(t)?t:{attributes:t},B=(t,e)=>{if(t.isTraced){t.setAttribute(f.functionPath,e.functionPath),t.setAttribute(f.ok,e.ok),t.setAttribute(f.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(f.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(f.userId,e.userId),e.error!==void 0&&(t.setAttribute(f.errorType,e.error.type),t.setAttribute(f.errorMessage,e.error.message));for(const[r,n]of Object.entries(e.attributes))(typeof n=="boolean"||typeof n=="number"||typeof n=="string")&&t.setAttribute(`lunora.attr.${r}`,n)}},G=t=>{const e={attributes:{},events:[],links:[]},r={spanContext:()=>t,addEvent:(n,a)=>{if(e.events.length>=U)return;const s=y(a);e.events.push({...s===void 0?{}:{attributes:s},name:n,ts:Date.now()})},addLink:n=>{if(e.links.length>=q)return;const a=y(n.attributes);e.links.push({...a===void 0?{}:{attributes:a},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{Object.assign(e.attributes,y(C(n)))},recordException:n=>{r.addEvent("exception",{"exception.message":n instanceof Error?n.message:String(n),...n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":T(n)})},setAttribute:(n,a)=>{Object.assign(e.attributes,y({[n]:a}))},setAttributes:n=>{Object.assign(e.attributes,y(n))}};return{collected:e,handle:r}},X=t=>{const{anchor:e,fuseCloudflareSpans:r,functionPath:n,record:a,resolveCloudflareTracing:s,shardKey:i,userId:c}=t,h=u=>async(v,I,d)=>{const l=E(8),g=Date.now(),o=J(d),M=y(o.attributes),{collected:k,handle:j}=G({spanId:l,traceId:e.traceId}),A=async b=>{let m=!0,w;try{return await I(h(l),j)}catch(p){throw m=!1,w={message:p instanceof Error?p.message:String(p),type:T(p)},p}finally{const p=Date.now()-g,O=c(),$={...M,...k.attributes},P=[...o.links??[],...k.links];try{a({...Object.keys($).length===0?{}:{attributes:$},durationMs:p,...k.events.length===0?{}:{events:k.events},...w===void 0?{}:{error:w},functionPath:n,...o.kind===void 0||o.kind==="internal"?{}:{kind:o.kind},...P.length===0?{}:{links:P},name:v,ok:m,parentSpanId:u,shardKey:i,spanId:l,startTs:g,traceId:e.traceId,userId:O})}catch{}if(b!==void 0)try{B(b,{attributes:$,durationMs:p,error:w,functionPath:n,ok:m,shardKey:i,userId:O})}catch{}}};if(r===!0&&s!==void 0){const b=await s();if(b!==void 0&&typeof b.enterSpan=="function")return await b.enterSpan(v,m=>A(m))}return await A()};return h(e.rootSpanId)},Y=(t,e)=>{const{anchor:r,functionPath:n,propagate:a=!0,record:s,shardKey:i,userId:c}=t;return async(h,u)=>{const v=E(8),I=Date.now(),d=new Request(h,u);(typeof a=="function"?V(a,d.url):a)&&d.headers.set("traceparent",F(r.traceId,v,r.sampled??!0));let l,g;try{const o=await e(d);return g=o.status,o.ok||(l={message:`HTTP ${String(o.status)}`,type:`HTTP_${String(o.status)}`}),o}catch(o){throw l={message:o instanceof Error?o.message:String(o),type:T(o)},o}finally{try{s({attributes:{"http.request.method":d.method,...g===void 0?{}:{"http.response.status_code":g},"url.full":z(d.url)},durationMs:Date.now()-I,...l===void 0?{}:{error:l},functionPath:n,kind:"client",name:`${d.method} ${H(d.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,shardKey:i,spanId:v,startTs:I,traceId:r.traceId,userId:c()})}catch{}}}},Z=t=>{const{functionPath:e,record:r,shardKey:n}=t,a=(s,i,c,h)=>{if(!Number.isFinite(c))return;const u=y(h);try{r({...u===void 0?{}:{attributes:u},functionPath:e,kind:s,name:i,shardKey:n,ts:Date.now(),value:c})}catch{}};return{count:(s,i=1,c)=>{a("counter",s,i,c)},gauge:(s,i,c)=>{a("gauge",s,i,c)},record:(s,i,c)=>{a("histogram",s,i,c)}}},tt=t=>{const{anchor:e,collected:r,durationMs:n,failure:a,functionPath:s,shardKey:i,startTs:c,userId:h}=t,u=r?.attributes??{};return{...Object.keys(u).length===0?{}:{attributes:u},dispatch:!0,durationMs:n,...r===void 0||r.events.length===0?{}:{events:r.events},...a===void 0?{}:{error:{message:a.thrown instanceof Error?a.thrown.message:String(a.thrown),type:T(a.thrown)}},functionPath:s,...r===void 0||r.links.length===0?{}:{links:r.links},name:s,ok:a===void 0,parentSpanId:"",shardKey:i,spanId:e.rootSpanId,startTs:c,traceId:e.traceId,userId:h}};export{R as A,E as O,X as a,Y as b,Z as c,tt as d,G as e,B as f,y as n,W as r,T as t,f as w};
@@ -1 +1 @@
1
- import{f as r,c as t,e as c,b as s,a as o,d as p}from"./context-telemetry-BQoMfXLz.mjs";export{r as applyCloudflareSpanAttributes,t as createMetrics,c as createSpanCollector,s as createTracedFetch,o as createTracer,p as dispatchRootSpan};
1
+ import{f as r,c as t,e as c,b as s,a as o,d as p}from"./context-telemetry-BFO0N_e4.mjs";export{r as applyCloudflareSpanAttributes,t as createMetrics,c as createSpanCollector,s as createTracedFetch,o as createTracer,p as dispatchRootSpan};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/do",
3
- "version": "1.0.0-alpha.49",
3
+ "version": "1.0.0-alpha.50",
4
4
  "description": "Lunora Durable Objects: ShardDO (SQLite, OCC, hibernated WebSocket subscriptions) and SessionDO",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{isLunoraError as L}from"@lunora/errors";const x=t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}},E=t=>typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:x(t),b=(t,e)=>{if(t===void 0&&e===void 0)return;const n={};if(e!==void 0)for(const[r,s]of Object.entries(e))n[r]=E(s);if(t!==void 0)for(const[r,s]of Object.entries(t))n[r]=E(s);return Object.keys(n).length===0?void 0:n},T=t=>{const e=new Uint8Array(t);crypto.getRandomValues(e);let n="";for(const r of e)n+=r.toString(16).padStart(2,"0");return n},S=/^[0-9a-f]+$/,C=(t,e,n=!0)=>`00-${t}-${e}-${n?"01":"00"}`,D=t=>{if(t==null)return;const e=t.trim().toLowerCase().split("-"),[n,r,s,a]=e;if(!(e.length<4||n===void 0||n.length!==2||!S.test(n)||n==="ff"||n==="00"&&e.length!==4||r===void 0||s===void 0||a===void 0||a.length!==2||!S.test(a)||r.length!==32||s.length!==16||!S.test(r)||!S.test(s)||r==="00000000000000000000000000000000"||s==="0000000000000000"))return{parentSpanId:s,sampled:(Number.parseInt(a,16)&1)===1,traceId:r}},f=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),B=t=>{const e=D(t);return{rootSpanId:e?.parentSpanId??T(8),sampled:e?.sampled??!0,traceId:e?.traceId??T(16)}},P=t=>L(t)?t.code:t instanceof Error?t.constructor.name:"Error",R=t=>{const e=Object.keys(t);return e.length>0&&e.every(n=>n==="attributes"||n==="kind"||n==="links")},_=128,F=128,U=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},H=t=>{try{return new URL(t).host}catch{return t}},N=(t,e)=>{try{return t(new URL(e))}catch{return!1}},V=t=>t===void 0?{}:R(t)?t:{attributes:t},q=(t,e)=>{if(t.isTraced){t.setAttribute(f.functionPath,e.functionPath),t.setAttribute(f.ok,e.ok),t.setAttribute(f.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(f.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(f.userId,e.userId),e.error!==void 0&&(t.setAttribute(f.errorType,e.error.type),t.setAttribute(f.errorMessage,e.error.message));for(const[n,r]of Object.entries(e.attributes))(typeof r=="boolean"||typeof r=="number"||typeof r=="string")&&t.setAttribute(`lunora.attr.${n}`,r)}},z=t=>{const e={attributes:{},events:[],links:[]},n={spanContext:()=>t,addEvent:(r,s)=>{if(e.events.length>=_)return;const a=b(s);e.events.push({...a===void 0?{}:{attributes:a},name:r,ts:Date.now()})},addLink:r=>{if(e.links.length>=F)return;const s=b(r.attributes);e.links.push({...s===void 0?{}:{attributes:s},spanId:r.spanId,traceId:r.traceId})},recordException:r=>{n.addEvent("exception",{"exception.message":r instanceof Error?r.message:String(r),...r instanceof Error&&typeof r.stack=="string"?{"exception.stacktrace":r.stack}:{},"exception.type":P(r)})},setAttribute:(r,s)=>{Object.assign(e.attributes,b({[r]:s}))},setAttributes:r=>{Object.assign(e.attributes,b(r))}};return{collected:e,handle:n}},G=t=>{const{anchor:e,fuseCloudflareSpans:n,functionPath:r,record:s,resolveCloudflareTracing:a,shardKey:i,userId:c}=t,h=d=>async(v,m,u)=>{const l=T(8),y=Date.now(),o=V(u),M=b(o.attributes),{collected:k,handle:j}=z({spanId:l,traceId:e.traceId}),A=async g=>{let I=!0,w;try{return await m(h(l),j)}catch(p){throw I=!1,w={message:p instanceof Error?p.message:String(p),type:P(p)},p}finally{const p=Date.now()-y,K=c(),$={...M,...k.attributes},O=[...o.links??[],...k.links];try{s({...Object.keys($).length===0?{}:{attributes:$},durationMs:p,...k.events.length===0?{}:{events:k.events},...w===void 0?{}:{error:w},functionPath:r,...o.kind===void 0||o.kind==="internal"?{}:{kind:o.kind},...O.length===0?{}:{links:O},name:v,ok:I,parentSpanId:d,shardKey:i,spanId:l,startTs:y,traceId:e.traceId,userId:K})}catch{}if(g!==void 0)try{q(g,{attributes:$,durationMs:p,error:w,functionPath:r,ok:I,shardKey:i,userId:K})}catch{}}};if(n===!0&&a!==void 0){const g=await a();if(g!==void 0&&typeof g.enterSpan=="function")return await g.enterSpan(v,I=>A(I))}return await A()};return h(e.rootSpanId)},Q=(t,e)=>{const{anchor:n,functionPath:r,propagate:s=!0,record:a,shardKey:i,userId:c}=t;return async(h,d)=>{const v=T(8),m=Date.now(),u=new Request(h,d);(typeof s=="function"?N(s,u.url):s)&&u.headers.set("traceparent",C(n.traceId,v,n.sampled??!0));let l,y;try{const o=await e(u);return y=o.status,o.ok||(l={message:`HTTP ${String(o.status)}`,type:`HTTP_${String(o.status)}`}),o}catch(o){throw l={message:o instanceof Error?o.message:String(o),type:P(o)},o}finally{try{a({attributes:{"http.request.method":u.method,...y===void 0?{}:{"http.response.status_code":y},"url.full":U(u.url)},durationMs:Date.now()-m,...l===void 0?{}:{error:l},functionPath:r,kind:"client",name:`${u.method} ${H(u.url)}`,ok:l===void 0,parentSpanId:n.rootSpanId,shardKey:i,spanId:v,startTs:m,traceId:n.traceId,userId:c()})}catch{}}}},W=t=>{const{functionPath:e,record:n,shardKey:r}=t,s=(a,i,c,h)=>{if(!Number.isFinite(c))return;const d=b(h);try{n({...d===void 0?{}:{attributes:d},functionPath:e,kind:a,name:i,shardKey:r,ts:Date.now(),value:c})}catch{}};return{count:(a,i=1,c)=>{s("counter",a,i,c)},gauge:(a,i,c)=>{s("gauge",a,i,c)},record:(a,i,c)=>{s("histogram",a,i,c)}}},X=t=>{const{anchor:e,collected:n,durationMs:r,failure:s,functionPath:a,shardKey:i,startTs:c,userId:h}=t,d=n?.attributes??{};return{...Object.keys(d).length===0?{}:{attributes:d},dispatch:!0,durationMs:r,...n===void 0||n.events.length===0?{}:{events:n.events},...s===void 0?{}:{error:{message:s.thrown instanceof Error?s.thrown.message:String(s.thrown),type:P(s.thrown)}},functionPath:a,...n===void 0||n.links.length===0?{}:{links:n.links},name:a,ok:s===void 0,parentSpanId:"",shardKey:i,spanId:e.rootSpanId,startTs:c,traceId:e.traceId,userId:h}};export{D as A,T as O,G as a,Q as b,W as c,X as d,z as e,q as f,b as n,B as r,P as t,f as w};