@lunora/server 1.0.0-alpha.256 → 1.0.0-alpha.257

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
@@ -1859,6 +1859,11 @@ interface OrmLike {
1859
1859
  declare const defineLazyFacade: (target: FacadeWriterLike, tableName: string) => void;
1860
1860
  /** Build `ctx.orm` over a per-table facade map (table name → FacadeEntry). */
1861
1861
  declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
1862
+ /**
1863
+ * Whether a value can sit on one SSE field line. A CR, LF or NUL would end the
1864
+ * line early and let the value inject `event:` / `data:` lines of its own.
1865
+ */
1866
+ declare const isSafeHeaderValue: (value: string) => boolean;
1862
1867
  /** HTTP verbs the typed {@link httpRoute} builder can bind to. */
1863
1868
  type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
1864
1869
  /** The `run*` trio, shared between {@link HttpActionCtx} itself and its `forShard(key)` view. */
@@ -2168,8 +2173,6 @@ declare const sseEvent: <R>(frame: {
2168
2173
  data: R;
2169
2174
  id: string;
2170
2175
  }) => SseEvent<R>;
2171
- /** A header or SSE field value that cannot break out of its line. */
2172
- declare const isSafeHeaderValue: (value: string) => boolean;
2173
2176
  /**
2174
2177
  * Typed REST route builder. Compiles down to a {@link LunoraRouteHandler}, so a
2175
2178
  * typed route and a hand-written {@link httpAction} are interchangeable when
@@ -3567,7 +3570,7 @@ interface PresenceMember {
3567
3570
  data?: Record<string, unknown>;
3568
3571
  /** Last heartbeat time (epoch ms). */
3569
3572
  lastSeen: number;
3570
- /** The room / channel / document this presence is scoped to. */
3573
+ /** The room / channel / document this presence is scoped to, as the client named it. */
3571
3574
  roomId: string;
3572
3575
  /** Authenticated user id, when known. */
3573
3576
  userId?: string;
@@ -3586,8 +3589,8 @@ interface DefinePresenceOptions {
3586
3589
  disconnectGraceMs?: number;
3587
3590
  /**
3588
3591
  * Upper bound on SESSION ROWS `listPresent` reads per call — one row per
3589
- * `(roomId, sessionId)`, so one per open tab, NOT one per person. The read
3590
- * is newest-first over the `(roomId, lastSeen)` index, so the rows kept are
3592
+ * `(tenantId, roomId, sessionId)`, so one per open tab, NOT one per person. The read
3593
+ * is newest-first over the `(tenantId, roomId, lastSeen)` index, so the rows kept are
3591
3594
  * always the freshest heartbeats and a room with more sessions than this
3592
3595
  * has its stalest ones truncated.
3593
3596
  *
@@ -3598,6 +3601,20 @@ interface DefinePresenceOptions {
3598
3601
  * Defaults to 1024. A non-finite value falls back to the default.
3599
3602
  */
3600
3603
  maxSessions?: number;
3604
+ /**
3605
+ * The tenant whose rooms the caller can reach, derived from the verified
3606
+ * identity (`ctx.auth.getIdentity()`), never from `args` — a client-chosen
3607
+ * tenant is no boundary. Read only server-verified claims here. Rooms of
3608
+ * different tenants never meet: the same `roomId` under two tenants is two
3609
+ * rooms, and heartbeat, `listPresent`, the heartbeat reap and the
3610
+ * disconnect cleanup are all pinned to the caller's tenant.
3611
+ *
3612
+ * Defaults to the identity's `orgId` claim, or `""` (the app-wide tenant)
3613
+ * when it is absent — right for a single-tenant app. An identity's claims can
3614
+ * lag a membership change by the identity cache window, and a socket keeps
3615
+ * the claims it connected with, so its disconnect cleanup targets that tenant.
3616
+ */
3617
+ tenant?: (identity: Record<string, unknown> | null) => string;
3601
3618
  /**
3602
3619
  * How long (ms) a heartbeat keeps a member present. `listPresent` excludes
3603
3620
  * rows whose `lastSeen` is older than `now - ttlMs`. Defaults to 30s.
@@ -3610,19 +3627,21 @@ interface PresenceFunctions {
3610
3627
  * Connection-lifecycle hook: the instant a client's WebSocket drops, hard-
3611
3628
  * delete its presence row so it disappears from `listPresent` with no TTL
3612
3629
  * lag. Targets the row by the `{ roomId, sessionId }` the client passed as
3613
- * the connection `context`, and only deletes it when the disconnecting
3630
+ * the connection `context`, within the socket's own tenant (from its verified
3631
+ * identity, never the context), and only deletes it when the disconnecting
3614
3632
  * VERIFIED identity owns the row (so a forged context can't evict another
3615
3633
  * member). The TTL filter + `sweep` remain the fallback for ungraceful drops
3616
3634
  * where no `context` was recorded.
3617
3635
  */
3618
3636
  disconnect: RegisteredLifecycleHook;
3619
3637
  /**
3620
- * Upsert the caller's presence row for `roomId` and stamp `lastSeen = now`.
3621
- * Keyed by `(roomId, sessionId)` — re-heartbeats patch the existing row so
3622
- * subscribers receive a single-row delta, not a churn of insert/delete. A
3623
- * heartbeat may only patch a row owned by the same identity (an existing row
3624
- * held by a different `userId` is refused with `FORBIDDEN`), so a client
3625
- * can't overwrite another member's awareness data via a guessed `sessionId`.
3638
+ * Upsert the caller's presence row for `roomId` in their tenant and stamp
3639
+ * `lastSeen = now`. Keyed by `(tenantId, roomId, sessionId)` — re-heartbeats
3640
+ * patch the existing row so subscribers receive a single-row delta, not a
3641
+ * churn of insert/delete. A heartbeat may only patch a row owned by the
3642
+ * same identity (an existing row held by a different `userId` is refused
3643
+ * with `FORBIDDEN`), so a client can't overwrite another member's awareness
3644
+ * data via a guessed `sessionId`.
3626
3645
  */
3627
3646
  heartbeat: RegisteredMutation<{
3628
3647
  data: ReturnType<typeof v.optional>;
@@ -3632,21 +3651,25 @@ interface PresenceFunctions {
3632
3651
  lastSeen: number;
3633
3652
  }>;
3634
3653
  /**
3635
- * Live query returning the non-expired members of `roomId`, newest heartbeat
3636
- * first. Subscribe to it for a reactive "who's here" list.
3654
+ * Live query returning the non-expired members of `roomId` in the caller's
3655
+ * tenant, newest heartbeat first. Subscribe to it for a reactive "who's
3656
+ * here" list.
3637
3657
  */
3638
3658
  listPresent: RegisteredQuery<{
3639
3659
  roomId: ReturnType<typeof v.string>;
3640
3660
  }, PresenceMember[]>;
3641
3661
  /**
3642
- * Internal mutation that hard-deletes every expired row for `roomId`. Stale
3643
- * rows already vanish from `listPresent` via the read-time TTL filter, and
3644
- * active rooms self-clean via the heartbeat's opportunistic reap; this is
3645
- * optional hardening for bulk cleanup of rooms that went quiet with stale
3646
- * rows left behind (schedule it on a cron / `runAfter` if you care).
3662
+ * Internal mutation that hard-deletes every expired row for `roomId` in
3663
+ * `tenantId` (`""` for the app-wide tenant). Server-only, so the caller names
3664
+ * the tenant. Stale rows already vanish from `listPresent` via the
3665
+ * read-time TTL filter, and active rooms self-clean via the heartbeat's
3666
+ * opportunistic reap; this is optional hardening for bulk cleanup of rooms
3667
+ * that went quiet with stale rows left behind (schedule it on a cron /
3668
+ * `runAfter` if you care).
3647
3669
  */
3648
3670
  sweep: RegisteredMutation<{
3649
3671
  roomId: ReturnType<typeof v.string>;
3672
+ tenantId: ReturnType<typeof v.string>;
3650
3673
  }, {
3651
3674
  deleted: number;
3652
3675
  }>;
@@ -3659,8 +3682,9 @@ type PresenceComponent = Component<{
3659
3682
  };
3660
3683
  /**
3661
3684
  * The presence schema extension: a single `present` table, auto-namespaced to
3662
- * `presence_present` at merge time, indexed by `(roomId, sessionId)` for the
3663
- * heartbeat upsert and by `roomId` for `listPresent`.
3685
+ * `presence_present` at merge time, indexed by `(tenantId, roomId, sessionId)`
3686
+ * for the heartbeat upsert and by `(tenantId, roomId, lastSeen)` for
3687
+ * `listPresent`, the reap and `sweep`.
3664
3688
  */
3665
3689
  declare const presenceExtension: SchemaExtension<{
3666
3690
  [PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
@@ -3675,7 +3699,7 @@ declare const presenceExtension: SchemaExtension<{
3675
3699
  * (callable only server-side, e.g. from a cron) since hard-deletes shouldn't be
3676
3700
  * client triggered. `listPresent` stays a plain public query so the client can
3677
3701
  * subscribe to it.
3678
- * @param options presence configuration (TTL).
3702
+ * @param options presence configuration (TTL, tenant policy).
3679
3703
  * @returns a component bundling the extension and the presence functions.
3680
3704
  */
3681
3705
  declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
@@ -4382,16 +4406,7 @@ httpRoute,
4382
4406
  * handler can guard a request-derived header value before writing it — the fix the
4383
4407
  * `http_action_response_header_injection` advisor lint points to.
4384
4408
  */
4385
- httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isPerDispatchMiddleware,
4386
- /**
4387
- * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4388
- * NUL. Guards against response-header injection / `Headers`-construction throws
4389
- * when reflecting attacker-influenced object metadata (e.g. a stored
4390
- * `Content-Type`). Exported (see the `export {}` at the file end) so an `httpAction`
4391
- * handler can guard a request-derived header value before writing it — the fix the
4392
- * `http_action_response_header_injection` advisor lint points to.
4393
- */
4394
- isSafeHeaderValue,
4409
+ httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isPerDispatchMiddleware, isSafeHeaderValue,
4395
4410
  /**
4396
4411
  * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4397
4412
  * NUL. Guards against response-header injection / `Headers`-construction throws
package/dist/index.d.ts CHANGED
@@ -1859,6 +1859,11 @@ interface OrmLike {
1859
1859
  declare const defineLazyFacade: (target: FacadeWriterLike, tableName: string) => void;
1860
1860
  /** Build `ctx.orm` over a per-table facade map (table name → FacadeEntry). */
1861
1861
  declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
1862
+ /**
1863
+ * Whether a value can sit on one SSE field line. A CR, LF or NUL would end the
1864
+ * line early and let the value inject `event:` / `data:` lines of its own.
1865
+ */
1866
+ declare const isSafeHeaderValue: (value: string) => boolean;
1862
1867
  /** HTTP verbs the typed {@link httpRoute} builder can bind to. */
1863
1868
  type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
1864
1869
  /** The `run*` trio, shared between {@link HttpActionCtx} itself and its `forShard(key)` view. */
@@ -2168,8 +2173,6 @@ declare const sseEvent: <R>(frame: {
2168
2173
  data: R;
2169
2174
  id: string;
2170
2175
  }) => SseEvent<R>;
2171
- /** A header or SSE field value that cannot break out of its line. */
2172
- declare const isSafeHeaderValue: (value: string) => boolean;
2173
2176
  /**
2174
2177
  * Typed REST route builder. Compiles down to a {@link LunoraRouteHandler}, so a
2175
2178
  * typed route and a hand-written {@link httpAction} are interchangeable when
@@ -3567,7 +3570,7 @@ interface PresenceMember {
3567
3570
  data?: Record<string, unknown>;
3568
3571
  /** Last heartbeat time (epoch ms). */
3569
3572
  lastSeen: number;
3570
- /** The room / channel / document this presence is scoped to. */
3573
+ /** The room / channel / document this presence is scoped to, as the client named it. */
3571
3574
  roomId: string;
3572
3575
  /** Authenticated user id, when known. */
3573
3576
  userId?: string;
@@ -3586,8 +3589,8 @@ interface DefinePresenceOptions {
3586
3589
  disconnectGraceMs?: number;
3587
3590
  /**
3588
3591
  * Upper bound on SESSION ROWS `listPresent` reads per call — one row per
3589
- * `(roomId, sessionId)`, so one per open tab, NOT one per person. The read
3590
- * is newest-first over the `(roomId, lastSeen)` index, so the rows kept are
3592
+ * `(tenantId, roomId, sessionId)`, so one per open tab, NOT one per person. The read
3593
+ * is newest-first over the `(tenantId, roomId, lastSeen)` index, so the rows kept are
3591
3594
  * always the freshest heartbeats and a room with more sessions than this
3592
3595
  * has its stalest ones truncated.
3593
3596
  *
@@ -3598,6 +3601,20 @@ interface DefinePresenceOptions {
3598
3601
  * Defaults to 1024. A non-finite value falls back to the default.
3599
3602
  */
3600
3603
  maxSessions?: number;
3604
+ /**
3605
+ * The tenant whose rooms the caller can reach, derived from the verified
3606
+ * identity (`ctx.auth.getIdentity()`), never from `args` — a client-chosen
3607
+ * tenant is no boundary. Read only server-verified claims here. Rooms of
3608
+ * different tenants never meet: the same `roomId` under two tenants is two
3609
+ * rooms, and heartbeat, `listPresent`, the heartbeat reap and the
3610
+ * disconnect cleanup are all pinned to the caller's tenant.
3611
+ *
3612
+ * Defaults to the identity's `orgId` claim, or `""` (the app-wide tenant)
3613
+ * when it is absent — right for a single-tenant app. An identity's claims can
3614
+ * lag a membership change by the identity cache window, and a socket keeps
3615
+ * the claims it connected with, so its disconnect cleanup targets that tenant.
3616
+ */
3617
+ tenant?: (identity: Record<string, unknown> | null) => string;
3601
3618
  /**
3602
3619
  * How long (ms) a heartbeat keeps a member present. `listPresent` excludes
3603
3620
  * rows whose `lastSeen` is older than `now - ttlMs`. Defaults to 30s.
@@ -3610,19 +3627,21 @@ interface PresenceFunctions {
3610
3627
  * Connection-lifecycle hook: the instant a client's WebSocket drops, hard-
3611
3628
  * delete its presence row so it disappears from `listPresent` with no TTL
3612
3629
  * lag. Targets the row by the `{ roomId, sessionId }` the client passed as
3613
- * the connection `context`, and only deletes it when the disconnecting
3630
+ * the connection `context`, within the socket's own tenant (from its verified
3631
+ * identity, never the context), and only deletes it when the disconnecting
3614
3632
  * VERIFIED identity owns the row (so a forged context can't evict another
3615
3633
  * member). The TTL filter + `sweep` remain the fallback for ungraceful drops
3616
3634
  * where no `context` was recorded.
3617
3635
  */
3618
3636
  disconnect: RegisteredLifecycleHook;
3619
3637
  /**
3620
- * Upsert the caller's presence row for `roomId` and stamp `lastSeen = now`.
3621
- * Keyed by `(roomId, sessionId)` — re-heartbeats patch the existing row so
3622
- * subscribers receive a single-row delta, not a churn of insert/delete. A
3623
- * heartbeat may only patch a row owned by the same identity (an existing row
3624
- * held by a different `userId` is refused with `FORBIDDEN`), so a client
3625
- * can't overwrite another member's awareness data via a guessed `sessionId`.
3638
+ * Upsert the caller's presence row for `roomId` in their tenant and stamp
3639
+ * `lastSeen = now`. Keyed by `(tenantId, roomId, sessionId)` — re-heartbeats
3640
+ * patch the existing row so subscribers receive a single-row delta, not a
3641
+ * churn of insert/delete. A heartbeat may only patch a row owned by the
3642
+ * same identity (an existing row held by a different `userId` is refused
3643
+ * with `FORBIDDEN`), so a client can't overwrite another member's awareness
3644
+ * data via a guessed `sessionId`.
3626
3645
  */
3627
3646
  heartbeat: RegisteredMutation<{
3628
3647
  data: ReturnType<typeof v.optional>;
@@ -3632,21 +3651,25 @@ interface PresenceFunctions {
3632
3651
  lastSeen: number;
3633
3652
  }>;
3634
3653
  /**
3635
- * Live query returning the non-expired members of `roomId`, newest heartbeat
3636
- * first. Subscribe to it for a reactive "who's here" list.
3654
+ * Live query returning the non-expired members of `roomId` in the caller's
3655
+ * tenant, newest heartbeat first. Subscribe to it for a reactive "who's
3656
+ * here" list.
3637
3657
  */
3638
3658
  listPresent: RegisteredQuery<{
3639
3659
  roomId: ReturnType<typeof v.string>;
3640
3660
  }, PresenceMember[]>;
3641
3661
  /**
3642
- * Internal mutation that hard-deletes every expired row for `roomId`. Stale
3643
- * rows already vanish from `listPresent` via the read-time TTL filter, and
3644
- * active rooms self-clean via the heartbeat's opportunistic reap; this is
3645
- * optional hardening for bulk cleanup of rooms that went quiet with stale
3646
- * rows left behind (schedule it on a cron / `runAfter` if you care).
3662
+ * Internal mutation that hard-deletes every expired row for `roomId` in
3663
+ * `tenantId` (`""` for the app-wide tenant). Server-only, so the caller names
3664
+ * the tenant. Stale rows already vanish from `listPresent` via the
3665
+ * read-time TTL filter, and active rooms self-clean via the heartbeat's
3666
+ * opportunistic reap; this is optional hardening for bulk cleanup of rooms
3667
+ * that went quiet with stale rows left behind (schedule it on a cron /
3668
+ * `runAfter` if you care).
3647
3669
  */
3648
3670
  sweep: RegisteredMutation<{
3649
3671
  roomId: ReturnType<typeof v.string>;
3672
+ tenantId: ReturnType<typeof v.string>;
3650
3673
  }, {
3651
3674
  deleted: number;
3652
3675
  }>;
@@ -3659,8 +3682,9 @@ type PresenceComponent = Component<{
3659
3682
  };
3660
3683
  /**
3661
3684
  * The presence schema extension: a single `present` table, auto-namespaced to
3662
- * `presence_present` at merge time, indexed by `(roomId, sessionId)` for the
3663
- * heartbeat upsert and by `roomId` for `listPresent`.
3685
+ * `presence_present` at merge time, indexed by `(tenantId, roomId, sessionId)`
3686
+ * for the heartbeat upsert and by `(tenantId, roomId, lastSeen)` for
3687
+ * `listPresent`, the reap and `sweep`.
3664
3688
  */
3665
3689
  declare const presenceExtension: SchemaExtension<{
3666
3690
  [PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
@@ -3675,7 +3699,7 @@ declare const presenceExtension: SchemaExtension<{
3675
3699
  * (callable only server-side, e.g. from a cron) since hard-deletes shouldn't be
3676
3700
  * client triggered. `listPresent` stays a plain public query so the client can
3677
3701
  * subscribe to it.
3678
- * @param options presence configuration (TTL).
3702
+ * @param options presence configuration (TTL, tenant policy).
3679
3703
  * @returns a component bundling the extension and the presence functions.
3680
3704
  */
3681
3705
  declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
@@ -4382,16 +4406,7 @@ httpRoute,
4382
4406
  * handler can guard a request-derived header value before writing it — the fix the
4383
4407
  * `http_action_response_header_injection` advisor lint points to.
4384
4408
  */
4385
- httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isPerDispatchMiddleware,
4386
- /**
4387
- * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4388
- * NUL. Guards against response-header injection / `Headers`-construction throws
4389
- * when reflecting attacker-influenced object metadata (e.g. a stored
4390
- * `Content-Type`). Exported (see the `export {}` at the file end) so an `httpAction`
4391
- * handler can guard a request-derived header value before writing it — the fix the
4392
- * `http_action_response_header_injection` advisor lint points to.
4393
- */
4394
- isSafeHeaderValue,
4409
+ httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isPerDispatchMiddleware, isSafeHeaderValue,
4395
4410
  /**
4396
4411
  * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4397
4412
  * NUL. Guards against response-header injection / `Headers`-construction throws
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DU87Okaj.mjs";import{initLunora as s}from"./packem_shared/initLunora-DH7k24N0.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as S,flushDeferredDeletes as u,withDeferredDeletes as h}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as A,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as I,documentHistoryExtension as _}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-DHn50G0w.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as v,defineLazyFacade as O}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as N,httpRoute as k,httpRouter as w,isSafeHeaderValue as U,lastEventId as B,sseEvent as V}from"./packem_shared/httpAction-Y87mmHRJ.mjs";import{serveStorageObject as j}from"./packem_shared/serveStorageObject-C4jB3i3P.mjs";import{defineIdentity as z}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as J}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as Q,onDisconnect as X,onShardInit as q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as $,DEFAULT_MAX_LIMIT as ee,clampLimit as re,defineListArgs as oe}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as ie,liveStreamRouter as ne}from"./packem_shared/defineLiveStream-BueK_whh.mjs";import{defineMigration as ae}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as se}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as pe}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as ce}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as Ee,d as Se,a as ue,b as he,e as De,f as Te,g as ge,h as Re,i as Ae,j as Le,k as Ie,m as _e}from"./packem_shared/plugin-D0ogWCbA.mjs";import{PRESENCE_DEFAULT_TTL_MS as Me,PRESENCE_TABLE as Pe,definePresence as be,presenceExtension as ye}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DbBZGuXA.mjs";import{protectPublic as ve}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as He}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as ke}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as Ue}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ve}from"./packem_shared/defineShape-CjBBjn-S.mjs";import{defineWebSocket as je}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as ze}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Je}from"@lunora/errors";import{cronJobs as Qe}from"@lunora/scheduler";import{ValidationError as qe,v as Ze}from"@lunora/values";import{allowAll as er,deny as rr,isDeny as or,toWhereInput as tr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as nr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as ar,buildRlsReadRegistry as dr,composeShapeReadWhere as sr}from"./packem_shared/assertShapesDeclareReadPolicies-CHqQ2eDy.mjs";import{buildMaskRegistry as pr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as cr,definePermission as lr,definePolicies as Er,definePolicy as Sr,defineRole as ur}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Dr,defineStorageRules as Tr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as Rr}from"./packem_shared/mask-BFPGwDqW.mjs";import{r as Lr}from"./packem_shared/middleware-mzWrOTEE.mjs";import{storageRules as _r}from"./packem_shared/storageRules-5NQpFz_N.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,$ as DEFAULT_LIMIT,ee as DEFAULT_MAX_LIMIT,A as DOCUMENT_HISTORY_REDACTED_FIELDS,L as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Je as LunoraError,Me as PRESENCE_DEFAULT_TTL_MS,Pe as PRESENCE_TABLE,e as VERSION,qe as ValidationError,n as actionCacheExtension,er as allowAll,nr as asBucketStorage,ar as assertShapesDeclareReadPolicies,S as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,v as bindTableFacade,pr as buildMaskRegistry,dr as buildRlsReadRegistry,f as cacheKeyFor,re as clampLimit,Ee as composePluginMiddleware,sr as composeShapeReadWhere,cr as createPolicyDsl,l as createSecrets,Ue as createServices,Qe as cronJobs,a as defineActionCache,Se as defineAggregateIndex,ue as defineComponent,I as defineDocumentHistory,P as defineEnv,z as defineIdentity,J as defineIdentityGuard,O as defineLazyFacade,oe as defineListArgs,ie as defineLiveStream,ae as defineMigration,se as defineModule,pe as defineMutator,lr as definePermission,he as definePlugin,Er as definePolicies,Sr as definePolicy,be as definePresence,De as defineRankIndex,ur as defineRole,ke as defineRoom,Te as defineSchema,ge as defineSchemaExtension,Ve as defineShape,Dr as defineStorageRule,Tr as defineStorageRules,Re as defineTable,Ae as defineVectorIndex,je as defineWebSocket,rr as deny,_ as documentHistoryExtension,u as flushDeferredDeletes,N as httpAction,k as httpRoute,w as httpRouter,Le as indexFieldsFromSchema,s as initLunora,Ie as installPlugins,or as isDeny,p as isPerDispatchMiddleware,U as isSafeHeaderValue,B as lastEventId,ne as liveStreamRouter,Rr as mask,_e as mergeSchemaExtension,Q as onConnect,X as onDisconnect,He as onQueryChange,q as onShardInit,ze as onWhisper,ce as platformAdmin,ye as presenceExtension,ve as protectPublic,b as redactSecrets,Lr as rls,j as serveStorageObject,V as sseEvent,_r as storageRules,x as tagPerDispatchMiddleware,tr as toWhereInput,Ze as v,h as withDeferredDeletes,g as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DU87Okaj.mjs";import{initLunora as s}from"./packem_shared/initLunora-DH7k24N0.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as S,flushDeferredDeletes as u,withDeferredDeletes as h}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as A,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as I,documentHistoryExtension as _}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-DHn50G0w.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as v,defineLazyFacade as O}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as N,httpRoute as k,httpRouter as w,lastEventId as U,sseEvent as B}from"./packem_shared/httpAction-DuAVtPa_.mjs";import{serveStorageObject as W}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as G}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as K,onDisconnect as Q,onShardInit as X}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Z,DEFAULT_MAX_LIMIT as $,clampLimit as ee,defineListArgs as re}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as te,liveStreamRouter as ie}from"./packem_shared/defineLiveStream-BmMpdotv.mjs";import{defineMigration as fe}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as de}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as me}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as xe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as le,d as Ee,a as Se,b as ue,e as he,f as De,g as Te,h as ge,i as Re,j as Ae,k as Le,m as Ie}from"./packem_shared/plugin-D0ogWCbA.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ce,PRESENCE_TABLE as Me,definePresence as Pe,presenceExtension as be}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-BtGG52OZ.mjs";import{protectPublic as Fe}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Oe}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Ne}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as we}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Be}from"./packem_shared/defineShape-CjBBjn-S.mjs";import{defineWebSocket as We}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Ye}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ge}from"@lunora/errors";import{cronJobs as Ke}from"@lunora/scheduler";import{ValidationError as Xe,v as qe}from"@lunora/values";import{allowAll as $e,deny as er,isDeny as rr,toWhereInput as or}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ir}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as fr,buildRlsReadRegistry as ar,composeShapeReadWhere as dr}from"./packem_shared/assertShapesDeclareReadPolicies-CHqQ2eDy.mjs";import{buildMaskRegistry as mr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as xr,definePermission as cr,definePolicies as lr,definePolicy as Er,defineRole as Sr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as hr,defineStorageRules as Dr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as gr}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Ar}from"./packem_shared/mask-BFPGwDqW.mjs";import{r as Ir}from"./packem_shared/middleware-mzWrOTEE.mjs";import{storageRules as Cr}from"./packem_shared/storageRules-5NQpFz_N.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,Z as DEFAULT_LIMIT,$ as DEFAULT_MAX_LIMIT,A as DOCUMENT_HISTORY_REDACTED_FIELDS,L as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Ge as LunoraError,Ce as PRESENCE_DEFAULT_TTL_MS,Me as PRESENCE_TABLE,e as VERSION,Xe as ValidationError,n as actionCacheExtension,$e as allowAll,ir as asBucketStorage,fr as assertShapesDeclareReadPolicies,S as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,v as bindTableFacade,mr as buildMaskRegistry,ar as buildRlsReadRegistry,f as cacheKeyFor,ee as clampLimit,le as composePluginMiddleware,dr as composeShapeReadWhere,xr as createPolicyDsl,l as createSecrets,we as createServices,Ke as cronJobs,a as defineActionCache,Ee as defineAggregateIndex,Se as defineComponent,I as defineDocumentHistory,P as defineEnv,Y as defineIdentity,G as defineIdentityGuard,O as defineLazyFacade,re as defineListArgs,te as defineLiveStream,fe as defineMigration,de as defineModule,me as defineMutator,cr as definePermission,ue as definePlugin,lr as definePolicies,Er as definePolicy,Pe as definePresence,he as defineRankIndex,Sr as defineRole,Ne as defineRoom,De as defineSchema,Te as defineSchemaExtension,Be as defineShape,hr as defineStorageRule,Dr as defineStorageRules,ge as defineTable,Re as defineVectorIndex,We as defineWebSocket,er as deny,_ as documentHistoryExtension,u as flushDeferredDeletes,N as httpAction,k as httpRoute,w as httpRouter,Ae as indexFieldsFromSchema,s as initLunora,Le as installPlugins,rr as isDeny,p as isPerDispatchMiddleware,gr as isSafeHeaderValue,U as lastEventId,ie as liveStreamRouter,Ar as mask,Ie as mergeSchemaExtension,K as onConnect,Q as onDisconnect,Oe as onQueryChange,X as onShardInit,Ye as onWhisper,xe as platformAdmin,be as presenceExtension,Fe as protectPublic,b as redactSecrets,Ir as rls,W as serveStorageObject,B as sseEvent,Cr as storageRules,x as tagPerDispatchMiddleware,or as toWhereInput,qe as v,h as withDeferredDeletes,g as withDeferredSchedules};
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as R}from"./initLunora-DH7k24N0.mjs";import{onDisconnect as L}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as D}from"./plugin-D0ogWCbA.mjs";const P=3e4,N=1024,B=8,p=4096,y="presence",T="present",r=`${y}_${T}`,C=l=>{const I=l?.orgId;return typeof I=="string"?I:""},U=v(y,{tables:{[T]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),tenantId:t.string(),userId:t.optional(t.string())}).index("byTenantRoomSession",["tenantId","roomId","sessionId"]).index("byTenantRoomLastSeen",["tenantId","roomId","lastSeen"])}}),{mutation:E,query:F}=R.dataModel().create(),H=(l={})=>{const I=l.ttlMs??P,S=l.tenant??C,w=Math.max(0,Math.min(l.disconnectGraceMs??0,I)),h=l.maxSessions,_=h!==void 0&&Number.isFinite(h)?Math.max(1,Math.floor(h)):N,q=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:e,ctx:n})=>{const c=Date.now(),i=n.auth.userId??void 0,o=S(await n.auth.getIdentity());if(e.data!==void 0&&new TextEncoder().encode(JSON.stringify(e.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const s=await n.db.query(r).withIndex("byTenantRoomSession",d=>d.eq("tenantId",o).eq("roomId",e.roomId).eq("sessionId",e.sessionId)).first();if(s&&(s.userId??void 0)!==i)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const m={lastSeen:c,roomId:e.roomId,sessionId:e.sessionId,tenantId:o,...e.data===void 0?{}:{data:e.data},...i===void 0?{}:{userId:i}};await(s?n.db.patch(r,s._id,m):n.db.insert(r,m));const f=c-I-Math.max(w,I),u=(await n.db.query(r).withIndex("byTenantRoomLastSeen",d=>d.eq("tenantId",o).eq("roomId",e.roomId)).order("asc").take(B)).filter(d=>d.lastSeen<=f);return await Promise.all(u.map(d=>n.db.delete(r,d._id))),{lastSeen:c}}),g=F.input({roomId:t.string()}).query(async({args:e,ctx:n})=>{const c=Date.now()-I,i=S(await n.auth.getIdentity()),s=(await n.db.query(r).withIndex("byTenantRoomLastSeen",a=>a.eq("tenantId",i).eq("roomId",e.roomId)).order("desc").take(_)).filter(a=>a.lastSeen>c),m=new Set,f=[];for(const a of s){const u=a.userId;if(u!==void 0){if(m.has(u))continue;m.add(u)}const d={lastSeen:a.lastSeen,roomId:a.roomId};u!==void 0&&(d.userId=u),a.data!==void 0&&(d.data=a.data),f.push(d)}return f}),x={...E.input({roomId:t.string(),tenantId:t.string()}).mutation(async({args:e,ctx:n})=>{const c=Date.now()-I,i=await n.db.query(r).withIndex("byTenantRoomLastSeen",o=>o.eq("tenantId",e.tenantId).eq("roomId",e.roomId)).filter(o=>o.lastSeen<=c).collect();return await Promise.all(i.map(o=>n.db.delete(r,o._id))),{deleted:i.length}}),visibility:"internal"},M=L(async(e,n)=>{const c=n.context?.roomId,i=n.context?.sessionId;if(typeof c!="string"||typeof i!="string")return;const o=S(await e.auth.getIdentity()),s=await e.db.query(r).withIndex("byTenantRoomSession",a=>a.eq("tenantId",o).eq("roomId",c).eq("sessionId",i)).first();if(!s)return;const m=n.userId??void 0;if((s.userId??void 0)!==m)return;if(w===0){await e.db.delete(r,s._id);return}const f=Math.min(s.lastSeen,Date.now()+w-I);await e.db.patch(r,s._id,{lastSeen:f})});return D(y,{extension:U,functions:{disconnect:M,heartbeat:q,listPresent:g,sweep:x}})};export{P as PRESENCE_DEFAULT_TTL_MS,r as PRESENCE_TABLE,H as definePresence,U as presenceExtension};
@@ -1 +1 @@
1
- import{LunoraError as S,isLunoraError as I}from"@lunora/errors";import{isStringValidator as P,parseValidatorMap as w}from"@lunora/values";import{Hono as j}from"hono";import{httpRouter as A,httpAction as E}from"./httpAction-Y87mmHRJ.mjs";const C="/_lunora/live/connect",g="/_lunora/live/control",N="room:",D="__lunora_socket__:",B=256,v=e=>`/live/${e}/connect`,m=e=>`/live/${e}/control`,K=/^[A-Za-z]\w*$/u,T=e=>K.test(e),U=e=>`${e}:`.startsWith(N)||`${e}:`.startsWith(D),k=(e,t,r)=>[e,...t.map(a=>{const i=r[a];if(typeof i!="string")throw new TypeError(`live topic "${e}" needs a string key.${a}`);return encodeURIComponent(i)})].join(":"),V=(e,t)=>{if(e.length>B)return;const[r,...a]=e.split(":");if(r===void 0||!Object.hasOwn(t,r))return;const i=t[r];if(a.length!==i.length)return;const o={};try{for(const[d,u]of i.entries())o[u]=decodeURIComponent(a[d]);return k(r,i,o)===e?{key:o,name:r}:void 0}catch{return}},F=async e=>{try{const t=await e.json();return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}},_=e=>Response.json({code:"FORBIDDEN_TOPIC",error:`subscribe to "${e}" was denied`},{status:403}),h=e=>Response.json({code:"BAD_REQUEST",error:e},{status:400}),H=(e,t)=>{for(const[r,a]of Object.entries(t)){if(!T(r))throw new TypeError(`defineLiveStream("${e}"): topic name "${r}" must be a plain identifier (letters, digits and "_", starting with a letter)`);if(U(r))throw new TypeError(`defineLiveStream("${e}"): topic name "${r}" would encode into a reserved topic prefix`);for(const[i,o]of Object.entries(a.key??{})){if(!T(i))throw new TypeError(`defineLiveStream("${e}"): key field "${r}.${i}" must be a plain identifier`);if(!P(o))throw new TypeError(`defineLiveStream("${e}"): key field "${r}.${i}" must be a string validator (v.string(), v.id(), v.literal(…))`)}}},z=(e,t)=>new S("BAD_REQUEST",`publish to "${e}" was refused: ${t instanceof Error?t.message:String(t)}`,{status:400}),X=e=>{H(e.id,e.topics);const t=v(e.id),r=m(e.id),a=Object.fromEntries(Object.entries(e.topics).map(([s,c])=>[s,Object.keys(c.key??{})])),i=s=>{const c=V(s,a),n=c===void 0?void 0:e.topics[c.name];if(!(c===void 0||n===void 0))try{return{declaration:n,key:w(n.key??{},c.key,"key"),name:c.name}}catch{return}},o=(s,c)=>{const n=i(s);if(n===void 0)throw new S("BAD_REQUEST",`"${s}" is not a topic declared by live stream "${e.id}"`,{status:400});const{declaration:p}=n;try{return w({payload:p.payload},{payload:c},"topic").payload}catch(y){throw z(s,y)}},d=async(s,c)=>{const n=i(c);if(n===void 0)return!1;if(!e.onSubscribe)return e.allowAnonymousControl===!0&&s.auth.userId===null;try{return await e.onSubscribe({ctx:s,key:n.key,raw:c,topic:n.name})===!0}catch(p){return console.error("[lunora] live subscribe authorization threw; denying:",p),!1}},u=E(async(s,c)=>{const n=new URL(c.url).searchParams.get("shard")??void 0;return s.fetchShard(n,C,{method:"GET"})}),R=E(async(s,c)=>{const n=await F(c);if(!n)return h("Expected a JSON object body");const{action:p}=n,y=typeof n.topic=="string"?n.topic:void 0;if(y===void 0||y.length===0)return h("topic is required");if(p!=="subscribe"&&p!=="unsubscribe")return h("action must be subscribe or unsubscribe");const l=typeof n.shardKey=="string"?n.shardKey:void 0,L=l===void 0?s:{...s,...s.forShard(l)};if(p==="subscribe"&&!await d(L,y))return _(y);const b=s.fetchShard(l,g,{body:JSON.stringify({...n,stream:e.id}),method:"POST"});if(p!=="subscribe")return b;try{return await b}catch(f){if(I(f)&&f.code==="FORBIDDEN_SHARD")return _(y);throw f}});return{connect:u,connectPath:t,control:R,controlPath:r,id:e.id,topics:e.topics,validatePublish:o}},M=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},$=new WeakSet,O=(e,t)=>{for(const r of t){let a;const i=()=>(a??=r.load().catch(o=>{throw a=void 0,o}),a);e.get(v(r.id),async o=>{const{connect:d}=await i();return d(o)}),e.post(m(r.id),async o=>{const{control:d}=await i();return d(o)})}},q=(e,t)=>{if(t instanceof j)return $.has(t)||(O(t,e),$.add(t)),t;const r=A();if(O(r,e),t===void 0)return r;const a=new Set(e.flatMap(o=>[`GET ${v(o.id)}`,`POST ${m(o.id)}`])),i=(o,d,u)=>typeof t=="function"?t(o,d,u):t.fetch(o,d,u);return{...M(t),fetch:(o,d,u)=>a.has(`${o.method} ${new URL(o.url).pathname}`)?r.fetch(o,d,u):i(o,d,u)}};export{X as defineLiveStream,q as liveStreamRouter};
1
+ import{LunoraError as S,isLunoraError as I}from"@lunora/errors";import{isStringValidator as P,parseValidatorMap as w}from"@lunora/values";import{Hono as j}from"hono";import{httpRouter as A,httpAction as E}from"./httpAction-DuAVtPa_.mjs";const C="/_lunora/live/connect",g="/_lunora/live/control",N="room:",D="__lunora_socket__:",B=256,v=e=>`/live/${e}/connect`,m=e=>`/live/${e}/control`,K=/^[A-Za-z]\w*$/u,T=e=>K.test(e),U=e=>`${e}:`.startsWith(N)||`${e}:`.startsWith(D),k=(e,t,r)=>[e,...t.map(a=>{const i=r[a];if(typeof i!="string")throw new TypeError(`live topic "${e}" needs a string key.${a}`);return encodeURIComponent(i)})].join(":"),V=(e,t)=>{if(e.length>B)return;const[r,...a]=e.split(":");if(r===void 0||!Object.hasOwn(t,r))return;const i=t[r];if(a.length!==i.length)return;const o={};try{for(const[d,u]of i.entries())o[u]=decodeURIComponent(a[d]);return k(r,i,o)===e?{key:o,name:r}:void 0}catch{return}},F=async e=>{try{const t=await e.json();return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}},_=e=>Response.json({code:"FORBIDDEN_TOPIC",error:`subscribe to "${e}" was denied`},{status:403}),h=e=>Response.json({code:"BAD_REQUEST",error:e},{status:400}),H=(e,t)=>{for(const[r,a]of Object.entries(t)){if(!T(r))throw new TypeError(`defineLiveStream("${e}"): topic name "${r}" must be a plain identifier (letters, digits and "_", starting with a letter)`);if(U(r))throw new TypeError(`defineLiveStream("${e}"): topic name "${r}" would encode into a reserved topic prefix`);for(const[i,o]of Object.entries(a.key??{})){if(!T(i))throw new TypeError(`defineLiveStream("${e}"): key field "${r}.${i}" must be a plain identifier`);if(!P(o))throw new TypeError(`defineLiveStream("${e}"): key field "${r}.${i}" must be a string validator (v.string(), v.id(), v.literal(…))`)}}},z=(e,t)=>new S("BAD_REQUEST",`publish to "${e}" was refused: ${t instanceof Error?t.message:String(t)}`,{status:400}),X=e=>{H(e.id,e.topics);const t=v(e.id),r=m(e.id),a=Object.fromEntries(Object.entries(e.topics).map(([s,c])=>[s,Object.keys(c.key??{})])),i=s=>{const c=V(s,a),n=c===void 0?void 0:e.topics[c.name];if(!(c===void 0||n===void 0))try{return{declaration:n,key:w(n.key??{},c.key,"key"),name:c.name}}catch{return}},o=(s,c)=>{const n=i(s);if(n===void 0)throw new S("BAD_REQUEST",`"${s}" is not a topic declared by live stream "${e.id}"`,{status:400});const{declaration:p}=n;try{return w({payload:p.payload},{payload:c},"topic").payload}catch(y){throw z(s,y)}},d=async(s,c)=>{const n=i(c);if(n===void 0)return!1;if(!e.onSubscribe)return e.allowAnonymousControl===!0&&s.auth.userId===null;try{return await e.onSubscribe({ctx:s,key:n.key,raw:c,topic:n.name})===!0}catch(p){return console.error("[lunora] live subscribe authorization threw; denying:",p),!1}},u=E(async(s,c)=>{const n=new URL(c.url).searchParams.get("shard")??void 0;return s.fetchShard(n,C,{method:"GET"})}),R=E(async(s,c)=>{const n=await F(c);if(!n)return h("Expected a JSON object body");const{action:p}=n,y=typeof n.topic=="string"?n.topic:void 0;if(y===void 0||y.length===0)return h("topic is required");if(p!=="subscribe"&&p!=="unsubscribe")return h("action must be subscribe or unsubscribe");const l=typeof n.shardKey=="string"?n.shardKey:void 0,L=l===void 0?s:{...s,...s.forShard(l)};if(p==="subscribe"&&!await d(L,y))return _(y);const b=s.fetchShard(l,g,{body:JSON.stringify({...n,stream:e.id}),method:"POST"});if(p!=="subscribe")return b;try{return await b}catch(f){if(I(f)&&f.code==="FORBIDDEN_SHARD")return _(y);throw f}});return{connect:u,connectPath:t,control:R,controlPath:r,id:e.id,topics:e.topics,validatePublish:o}},M=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},$=new WeakSet,O=(e,t)=>{for(const r of t){let a;const i=()=>(a??=r.load().catch(o=>{throw a=void 0,o}),a);e.get(v(r.id),async o=>{const{connect:d}=await i();return d(o)}),e.post(m(r.id),async o=>{const{control:d}=await i();return d(o)})}},q=(e,t)=>{if(t instanceof j)return $.has(t)||(O(t,e),$.add(t)),t;const r=A();if(O(r,e),t===void 0)return r;const a=new Set(e.flatMap(o=>[`GET ${v(o.id)}`,`POST ${m(o.id)}`])),i=(o,d,u)=>typeof t=="function"?t(o,d,u):t.fetch(o,d,u);return{...M(t),fetch:(o,d,u)=>a.has(`${o.method} ${new URL(o.url).pathname}`)?r.fetch(o,d,u):i(o,d,u)}};export{X as defineLiveStream,q as liveStreamRouter};
@@ -0,0 +1 @@
1
+ import{LunoraError as E,toErrorBody as T,isLunoraError as L}from"@lunora/errors";import{parseValidatorMap as w,ValidationError as q}from"@lunora/values";import{encodeWire as v}from"@lunora/wire";import{Hono as C}from"hono";import{SSE_HEADERS as S,sseFrame as b,isSafeHeaderValue as H}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as R}from"./apply-output-C5wZ5EAL.mjs";const $=e=>async r=>e(r.get("lunora"),r.req.raw),z=()=>{const e=new C;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},O=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},I=(e,r,o)=>{const n=O(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const i=n._meta?.inner;return a.map(d=>g(i?.kind??"string",d))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},A=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=I(t,r,n))}return w(e,o,"searchParams")},N=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const i=o[t];n[t]=i===void 0?void 0:g(O(a).kind,i)}return w(e,n,"params")},D=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return w(e,o,"body")},j=e=>{if(e instanceof q)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(L(e)){const{body:r,redacted:o,status:n}=T(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message,...r.why===void 0?{}:{why:r.why}},{status:n})}throw e},P=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},x=(e,r)=>async o=>{const n=P(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?A(e.searchParams,o):{},i=Object.keys(e.params).length>0?N(e.params,o):{},d=Object.keys(e.body).length>0?await D(e.body,o):{},h=await r({body:d,ctx:t,params:i,searchParams:a}),s=e.output?R(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const y=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:y?c:void 0,status:204}):Response.json(s,{headers:y?c:void 0})}catch(t){return j(t)}},K=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const o=new URL(e.url).searchParams.get("lastEventId");return o===null||o===""?void 0:o},_=Symbol.for("@lunora/server/sse-event"),X=e=>({[_]:!0,data:e.data,id:e.id}),B=e=>typeof e=="object"&&e!==null&&e[_]===!0,V=(e,r)=>{if(B(r)){if(!H(r.id))throw new E("INTERNAL","sseEvent id must not contain CR, LF or NUL");const o=e?R(e,r.data):r.data;return b(v(o),void 0,r.id)}return b(v(e?R(e,r):r))},M=(e,r)=>(async o=>{const n=P(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?A(e.searchParams,o):{},a=Object.keys(e.params).length>0?N(e.params,o):{}}catch(m){return j(m)}const i=o.get("lunora"),d=o.req.raw,h=new TextEncoder,s=new AbortController;if(d.signal.aborted)return s.abort(),new Response("",{headers:S});const c=()=>{s.abort()};d.signal.addEventListener("abort",c,{once:!0});const y=new ReadableStream({cancel(){d.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const f=r({ctx:i,params:a,request:d,searchParams:t,signal:s.signal});for await(const p of f){if(s.signal.aborted)break;m.enqueue(h.encode(V(e.output,p)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(f){const{body:p,redacted:k}=T(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});k&&console.error("[lunora] unhandled stream handler error:",f),s.signal.aborted||m.enqueue(h.encode(b({code:p.code,hint:p.hint,message:p.message,why:p.why},"error")))}finally{d.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(y,{headers:S})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>x(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>M(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),Y={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")};export{$ as httpAction,Y as httpRoute,z as httpRouter,H as isSafeHeaderValue,K as lastEventId,X as sseEvent};
@@ -0,0 +1,6 @@
1
+ const i={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},s=n=>!(n.includes("\r")||n.includes(`
2
+ `)||n.includes("\0")),a=(n,e,t)=>{if(t!==void 0&&!s(t))throw new Error("SSE event id must not contain CR, LF or NUL");const o=JSON.stringify(n),c=t===void 0?"":`id: ${t}
3
+ `,r=e===void 0?"":`event: ${e}
4
+ `;return`${c}${r}data: ${o}
5
+
6
+ `};export{i as SSE_HEADERS,s as isSafeHeaderValue,a as sseFrame};
@@ -0,0 +1 @@
1
+ import{isSafeHeaderValue as b}from"./isSafeHeaderValue-DswDADFy.mjs";const N=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,R=/(?:W\/)?"[^"]*"/g,p=t=>t.startsWith("W/")?t.slice(2):t,S=(t,e)=>{if(t.trim()==="*")return!0;const n=p(g(e));return(t.match(R)??[]).some(s=>p(s)===n)},m=(t,e)=>{if(t===null)return{kind:"full"};const n=N.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let r,o;if(s===""){const u=Number(a);if(u===0)return{kind:"unsatisfiable"};r=Math.max(0,e-u),o=e-1}else r=Number(s),o=a===""?e-1:Math.min(Number(a),e-1);return r>o||r>=e?{kind:"unsatisfiable"}:{end:o,kind:"partial",start:r}},v=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),w=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&b(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return v.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},y=t=>m(t,0).kind==="full",h=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...w(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},T=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},W=async(t,e,n,s,a="no-store")=>{if(!await T(s,e,n))return new Response("Forbidden",{status:403});const r=n.headers.get("if-none-match");let o;if(r!==null){const d=await t.storage.head(e);if(!d)return new Response("Not Found",{status:404});if(S(r,d.etag))return new Response(void 0,{headers:{"cache-control":a,etag:g(d.etag)},status:304});o=d}const u=n.headers.get("range");if(y(u))return h(t,e,a);const c=o??await t.storage.head(e);if(!c)return new Response("Not Found",{status:404});const i=m(u,c.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(c.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(c.etag)},status:416});if(i.kind==="full")return h(t,e,a);const f=i.end-i.start+1,l=await t.storage.download(e,{range:{length:f,offset:i.start}});return l?new Response(l.body,{headers:{...w(c,a),"content-length":String(f),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(c.size)}`},status:206}):new Response("Not Found",{status:404})};export{W as serveStorageObject};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.256",
3
+ "version": "1.0.0-alpha.257",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -73,10 +73,10 @@
73
73
  },
74
74
  "dependencies": {
75
75
  "@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
76
- "@lunora/scheduler": "1.0.0-alpha.159",
77
- "@lunora/shard-engine": "1.0.0-alpha.175",
78
- "@lunora/values": "1.0.0-alpha.86",
79
- "@lunora/wire": "1.0.0-alpha.5",
76
+ "@lunora/scheduler": "1.0.0-alpha.160",
77
+ "@lunora/shard-engine": "1.0.0-alpha.176",
78
+ "@lunora/values": "1.0.0-alpha.87",
79
+ "@lunora/wire": "1.0.0-alpha.6",
80
80
  "drizzle-orm": "1.0.0-rc.5",
81
81
  "hono": "^4.13.13"
82
82
  },
@@ -1 +0,0 @@
1
- import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DH7k24N0.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-D0ogWCbA.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",r=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const I=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,I)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const d=Date.now(),a=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(r).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==a)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const c={lastSeen:d,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...a===void 0?{}:{userId:a}};await(e?s.db.patch(r,e._id,c):s.db.insert(r,c));const l=d-I-Math.max(f,I),m=(await s.db.query(r).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=l);return await Promise.all(m.map(i=>s.db.delete(r,i._id))),{lastSeen:d}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const d=Date.now()-I,e=(await s.db.query(r).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>d),c=new Set,l=[];for(const n of e){const m=n.userId;if(m!==void 0){if(c.has(m))continue;c.add(m)}const i={lastSeen:n.lastSeen,roomId:n.roomId};m!==void 0&&(i.userId=m),n.data!==void 0&&(i.data=n.data),l.push(i)}return l}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const d=Date.now()-I,a=await s.db.query(r).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=d).collect();return await Promise.all(a.map(e=>s.db.delete(r,e._id))),{deleted:a.length}}),visibility:"internal"},q=T(async(o,s)=>{const d=s.context?.roomId,a=s.context?.sessionId;if(typeof d!="string"||typeof a!="string")return;const e=await o.db.query(r).withIndex("byRoomSession",n=>n.eq("roomId",d).eq("sessionId",a)).first();if(!e)return;const c=s.userId??void 0;if((e.userId??void 0)!==c)return;if(f===0){await o.db.delete(r,e._id);return}const l=Math.min(e.lastSeen,Date.now()+f-I);await o.db.patch(r,e._id,{lastSeen:l})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,r as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
@@ -1,6 +0,0 @@
1
- import{LunoraError as b,toErrorBody as S,isLunoraError as k}from"@lunora/errors";import{parseValidatorMap as w,ValidationError as L}from"@lunora/values";import{encodeWire as q}from"@lunora/wire";import{Hono as C}from"hono";import{a as R}from"./apply-output-C5wZ5EAL.mjs";const W=e=>async r=>e(r.get("lunora"),r.req.raw),G=()=>{const e=new C;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new b("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},O=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},x=(e,r,o)=>{const n=O(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const i=n._meta?.inner;return a.map(d=>g(i?.kind??"string",d))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},T=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=x(t,r,n))}return w(e,o,"searchParams")},N=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const i=o[t];n[t]=i===void 0?void 0:g(O(a).kind,i)}return w(e,n,"params")},H=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new b("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new b("BAD_REQUEST","Expected a JSON object body");return w(e,o,"body")},A=e=>{if(e instanceof L)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(k(e)){const{body:r,redacted:o,status:n}=S(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message,...r.why===void 0?{}:{why:r.why}},{status:n})}throw e},j=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},I=(e,r)=>async o=>{const n=j(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?T(e.searchParams,o):{},i=Object.keys(e.params).length>0?N(e.params,o):{},d=Object.keys(e.body).length>0?await H(e.body,o):{},h=await r({body:d,ctx:t,params:i,searchParams:a}),s=e.output?R(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const y=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:y?c:void 0,status:204}):Response.json(s,{headers:y?c:void 0})}catch(t){return A(t)}},v={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},z=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const o=new URL(e.url).searchParams.get("lastEventId");return o===null||o===""?void 0:o},P=Symbol.for("@lunora/server/sse-event"),K=e=>({[P]:!0,data:e.data,id:e.id}),D=e=>typeof e=="object"&&e!==null&&e[P]===!0,B=e=>!(e.includes("\r")||e.includes(`
2
- `)||e.includes("\0")),E=(e,r,o)=>{const n=JSON.stringify(r===void 0?q(e):e);if(o!==void 0&&!B(o))throw new b("INTERNAL","sseEvent id must not contain CR, LF or NUL");const t=o===void 0?"":`id: ${o}
3
- `,a=r?`event: ${r}
4
- `:"";return`${t}${a}data: ${n}
5
-
6
- `},V=(e,r)=>{if(D(r)){const o=e?R(e,r.data):r.data;return E(o,void 0,r.id)}return E(e?R(e,r):r)},$=(e,r)=>(async o=>{const n=j(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?T(e.searchParams,o):{},a=Object.keys(e.params).length>0?N(e.params,o):{}}catch(m){return A(m)}const i=o.get("lunora"),d=o.req.raw,h=new TextEncoder,s=new AbortController;if(d.signal.aborted)return s.abort(),new Response("",{headers:v});const c=()=>{s.abort()};d.signal.addEventListener("abort",c,{once:!0});const y=new ReadableStream({cancel(){d.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const f=r({ctx:i,params:a,request:d,searchParams:t,signal:s.signal});for await(const p of f){if(s.signal.aborted)break;m.enqueue(h.encode(V(e.output,p)))}s.signal.aborted||m.enqueue(h.encode(E({},"complete")))}catch(f){const{body:p,redacted:_}=S(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});_&&console.error("[lunora] unhandled stream handler error:",f),s.signal.aborted||m.enqueue(h.encode(E({code:p.code,hint:p.hint,message:p.message,why:p.why},"error")))}finally{d.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(y,{headers:v})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>I(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>$(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),X={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")};export{W as httpAction,X as httpRoute,G as httpRouter,B as isSafeHeaderValue,z as lastEventId,K as sseEvent};
@@ -1 +0,0 @@
1
- import{isSafeHeaderValue as b}from"./httpAction-Y87mmHRJ.mjs";const N=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,R=/(?:W\/)?"[^"]*"/g,p=t=>t.startsWith("W/")?t.slice(2):t,S=(t,e)=>{if(t.trim()==="*")return!0;const n=p(g(e));return(t.match(R)??[]).some(s=>p(s)===n)},m=(t,e)=>{if(t===null)return{kind:"full"};const n=N.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let r,o;if(s===""){const u=Number(a);if(u===0)return{kind:"unsatisfiable"};r=Math.max(0,e-u),o=e-1}else r=Number(s),o=a===""?e-1:Math.min(Number(a),e-1);return r>o||r>=e?{kind:"unsatisfiable"}:{end:o,kind:"partial",start:r}},v=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),w=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&b(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return v.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},y=t=>m(t,0).kind==="full",h=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...w(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},T=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},W=async(t,e,n,s,a="no-store")=>{if(!await T(s,e,n))return new Response("Forbidden",{status:403});const r=n.headers.get("if-none-match");let o;if(r!==null){const d=await t.storage.head(e);if(!d)return new Response("Not Found",{status:404});if(S(r,d.etag))return new Response(void 0,{headers:{"cache-control":a,etag:g(d.etag)},status:304});o=d}const u=n.headers.get("range");if(y(u))return h(t,e,a);const c=o??await t.storage.head(e);if(!c)return new Response("Not Found",{status:404});const i=m(u,c.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(c.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(c.etag)},status:416});if(i.kind==="full")return h(t,e,a);const f=i.end-i.start+1,l=await t.storage.download(e,{range:{length:f,offset:i.start}});return l?new Response(l.body,{headers:{...w(c,a),"content-length":String(f),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(c.size)}`},status:206}):new Response("Not Found",{status:404})};export{W as serveStorageObject};