@lunora/runtime 1.0.0-alpha.83 → 1.0.0-alpha.85

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.
Files changed (28) hide show
  1. package/dist/index.d.mts +44 -63
  2. package/dist/index.d.ts +44 -63
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/DEFAULT_LOG_COLUMNS-gYMhXLzO.mjs +1 -0
  5. package/dist/packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs +1 -0
  6. package/dist/packem_shared/analyticsEngineSink-B3sQ6FPW.mjs +1 -0
  7. package/dist/packem_shared/argsFromQuery-DUfMEn8Z.mjs +1 -0
  8. package/dist/packem_shared/composeWorker-KxOmsDWE.mjs +6 -0
  9. package/dist/packem_shared/createCrossShardRelationCapabilities-BYNkv1Ys.mjs +1 -0
  10. package/dist/packem_shared/createKvCursorStore-dBxlYrXY.mjs +1 -0
  11. package/dist/packem_shared/createQueryCoordinator-Ctr3eqmp.mjs +1 -0
  12. package/dist/packem_shared/{createShardClient-0Tz9JwbX.mjs → createShardClient-DoKTlCKb.mjs} +1 -1
  13. package/dist/packem_shared/export-tap-CGR3Xd9F.mjs +3 -0
  14. package/dist/packem_shared/pipeline-log-reader-C-nuWG_e.mjs +1 -0
  15. package/dist/packem_shared/{portable-json-DPJbalfn.mjs → portable-json-DpqTEd22.mjs} +1 -1
  16. package/dist/packem_shared/{rest-routes-Dq17Zntv.mjs → rest-routes-ZZES0ngM.mjs} +1 -1
  17. package/dist/packem_shared/{toAirbyteMessages-CIjE6Vm1.mjs → toAirbyteMessages-DvYrhqLf.mjs} +1 -1
  18. package/dist/packem_shared/{wire-codec-BsPOEXGn.mjs → wire-codec-CMVqBlcF.mjs} +1 -1
  19. package/package.json +4 -4
  20. package/dist/packem_shared/DEFAULT_LOG_COLUMNS-B8FFcwsX.mjs +0 -1
  21. package/dist/packem_shared/LOG_ARCHIVE_PATH-jgHjdsz2.mjs +0 -1
  22. package/dist/packem_shared/analyticsEngineSink-D9xt5_FI.mjs +0 -1
  23. package/dist/packem_shared/argsFromQuery-CRa3o4U3.mjs +0 -1
  24. package/dist/packem_shared/composeWorker-Bz6FNFLU.mjs +0 -6
  25. package/dist/packem_shared/createCrossShardRelationCapabilities-BRX27FkU.mjs +0 -1
  26. package/dist/packem_shared/createKvCursorStore-DLm6fYoN.mjs +0 -3
  27. package/dist/packem_shared/createQueryCoordinator-B4Zk2HfK.mjs +0 -1
  28. package/dist/packem_shared/pipeline-log-reader-BGrl66P5.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -873,29 +873,6 @@ type MergeStrategy = {
873
873
  kind: "groupBy";
874
874
  op?: "max" | "min" | "sum";
875
875
  };
876
- /**
877
- * Convenience: build the right wire-serializable {@link MergeStrategy} for a
878
- * given aggregate read. The reader doesn't know which op the caller chose, so
879
- * a fan-out wrapper passes the user's op + by-keys through this to derive the
880
- * merge.
881
- *
882
- * - `count` → `sum`.
883
- * - `aggregate({ op })` → `sum`/`max`/`min` (or throws for `avg`).
884
- * - `groupBy({ by, agg })` → `groupBy({ op })` (defaults to `sum` since
885
- * `groupBy`'s default reducer is `count`).
886
- * @returns the derived {@link MergeStrategy}.
887
- */
888
- declare const mergeStrategyForAggregate: (input: {
889
- agg?: {
890
- op?: "avg" | "count" | "max" | "min" | "sum";
891
- };
892
- kind: "groupBy";
893
- } | {
894
- kind: "count";
895
- } | {
896
- kind: "scalar";
897
- op: "avg" | "count" | "max" | "min" | "sum";
898
- }) => MergeStrategy;
899
876
  interface FanOutSpec {
900
877
  merge: MergeStrategy;
901
878
  /** Table whose shard keys drive the fan-out. */
@@ -938,6 +915,21 @@ interface QueryCoordinatorOptions {
938
915
  /** Required — drives which shards to fan out to. */
939
916
  registry: ShardRegistry;
940
917
  }
918
+ /**
919
+ * Shard a fan-out falls back to when registry discovery finds nothing — normally
920
+ * the worker's `"__root__"` — or `null` to deliberately keep an empty discovery
921
+ * as an empty fan-out.
922
+ *
923
+ * Required on every request that has it, with no default, on purpose. Discovery
924
+ * is registry-driven and a registry only knows the keys an app registers for its
925
+ * `.shardBy(...)` tables, so on a plain root-DO app it comes back empty and a
926
+ * fan-out that reads that as "nothing to do" reports success having touched
927
+ * nothing: an export streamed an empty NDJSON backup, a migration reported
928
+ * `completed` with `processed: 0`. Fan-outs inherited that bug by simply not
929
+ * passing the field, so omission is no longer expressible — say `null` when you
930
+ * mean it. See {@link withDefaultShard}.
931
+ */
932
+ type DefaultShardKey = string | null;
941
933
  interface FanOutRequest {
942
934
  args?: Record<string, unknown>;
943
935
  fanOut: FanOutSpec;
@@ -958,12 +950,8 @@ interface FanOutRequest {
958
950
  */
959
951
  interface MigrationFanOutRequest {
960
952
  args?: Record<string, unknown>;
961
- /**
962
- * Shard to fall back to when registry discovery finds nothing — normally
963
- * `"__root__"`. See {@link withDefaultShard}; omit it to keep an empty
964
- * discovery as an empty fan-out.
965
- */
966
- defaultShardKey?: string;
953
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
954
+ defaultShardKey: DefaultShardKey;
967
955
  functionPath: string;
968
956
  headers?: Record<string, string>;
969
957
  /** Table whose live shard keys the migration runs across. */
@@ -1171,22 +1159,8 @@ interface QueryCoordinator {
1171
1159
  */
1172
1160
  interface ExportFanOutRequest {
1173
1161
  args?: Record<string, unknown>;
1174
- /**
1175
- * Shard to fall back to when registry discovery yields NOTHING for the
1176
- * requested tables — normally `"__root__"`.
1177
- *
1178
- * Discovery is registry-driven, and a registry only knows the shard keys an
1179
- * app registers for its `.shardBy(...)` tables. A plain root-DO table has no
1180
- * entry and never will, so the union came back empty and the export fanned
1181
- * out to zero shards — returning an empty NDJSON body that looks like a
1182
- * successful backup of a table that simply had no rows. `orchestrateImport`
1183
- * has always resolved the same case to the default shard; export not doing so
1184
- * meant a round trip could silently write back nothing.
1185
- *
1186
- * Omit to keep the old "no keys, no shards" behavior (a caller that has
1187
- * already resolved its own shard set).
1188
- */
1189
- defaultShardKey?: string;
1162
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
1163
+ defaultShardKey: DefaultShardKey;
1190
1164
  headers?: Record<string, string>;
1191
1165
  /**
1192
1166
  * Tables driving the fan-out. Shards are derived from the union of each
@@ -1222,12 +1196,8 @@ interface ExportFanOutResult {
1222
1196
  */
1223
1197
  interface CdcSyncFanOutRequest {
1224
1198
  cursors?: Record<string, number>;
1225
- /**
1226
- * Shard to fall back to when registry discovery finds nothing — normally
1227
- * `"__root__"`. See {@link withDefaultShard}; omit it to keep an empty
1228
- * discovery as an empty fan-out.
1229
- */
1230
- defaultShardKey?: string;
1199
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
1200
+ defaultShardKey: DefaultShardKey;
1231
1201
  headers?: Record<string, string>;
1232
1202
  limit?: number;
1233
1203
  tables: ReadonlyArray<string>;
@@ -1423,6 +1393,16 @@ interface RunExportTapOptions {
1423
1393
  coordinator: QueryCoordinator;
1424
1394
  /** Durable cursor store (per-shard watermark). */
1425
1395
  cursorStore: ExportCursorStore;
1396
+ /**
1397
+ * Shard to drain when registry discovery finds nothing — normally the
1398
+ * worker's `"__root__"` — or `null` to keep an empty discovery as an empty
1399
+ * pass. Forwarded verbatim to `orchestrateCdcSync`, and required for the
1400
+ * same reason it is required there: a registry only knows the keys an app
1401
+ * registers for its `.shardBy(...)` tables, so on a plain root-DO app
1402
+ * discovery is `[]` and a caller that omitted this drained no shards while
1403
+ * reporting `{ delivered: 0, hasMore: false }` against a full change feed.
1404
+ */
1405
+ defaultShardKey: string | null;
1426
1406
  /** Headers forwarded to each shard (identity / admin bearer). */
1427
1407
  headers?: Record<string, string>;
1428
1408
  /** Base backoff in ms for the first retry (doubles each attempt, capped at `maxBackoffMs`). Defaults to `100`. */
@@ -1940,7 +1920,7 @@ interface PipelineLogQuery {
1940
1920
  functionPathPrefix?: string;
1941
1921
  /** Match only this exact severity. When set, `minLevel` is ignored for the same field. */
1942
1922
  level?: ContextLogLevel;
1943
- /** Max rows to return. Clamped to `[1, 10000]`; defaults to {@link DEFAULT_LOG_LIMIT}. */
1923
+ /** Max rows to return. Clamped to `[1, 10000]`; defaults to 500. */
1944
1924
  limit?: number;
1945
1925
  /** Severity floor: keep every level at or above this in {@link LOG_LEVEL_ORDER} (e.g. `warn` keeps warn, error, fatal). */
1946
1926
  minLevel?: ContextLogLevel;
@@ -2014,8 +1994,6 @@ interface PipelineLogReader {
2014
1994
  }
2015
1995
  /** The written-column contract exposed publicly: canonical field to default physical column name. */
2016
1996
  declare const DEFAULT_LOG_COLUMNS: Readonly<Record<PipelineLogField, string>>;
2017
- /** Default page size when a query omits `limit`. */
2018
- declare const DEFAULT_LOG_LIMIT: number;
2019
1997
  /**
2020
1998
  * Build a durable-log reader over one R2 Data Catalog (Iceberg) table.
2021
1999
  *
@@ -2539,8 +2517,6 @@ interface RestRouteDeps {
2539
2517
  * `shared/rest-surface` helper).
2540
2518
  */
2541
2519
  declare const restSurfaceFromRegistry: (functions: RestRegistryLike) => ReturnType<typeof describeRestSurface>;
2542
- /** Read `shardKey` from `?shardKey=` or the `x-lunora-shard-key` header; `undefined` routes to the default shard. */
2543
- declare const readShardKey: (url: URL, request: Request) => string | undefined;
2544
2520
  /**
2545
2521
  * Decode GET args from the query string. Each value is parsed as JSON when it
2546
2522
  * looks like a JSON scalar/array/object (so `?limit=10` → number, `?ids=[1,2]` →
@@ -3679,11 +3655,6 @@ interface WorkerOptions {
3679
3655
  * the same expression as {@link WorkerOptions.backupCron} runs alongside it.
3680
3656
  */
3681
3657
  crons?: Record<string, CronHandler>;
3682
- /**
3683
- * D1 binding for `.global()` tables. Currently unused by the routing
3684
- * layer; downstream packages will read it from `env.DB` directly.
3685
- */
3686
- d1?: unknown;
3687
3658
  /** Default shard key used when an envelope omits one. */
3688
3659
  defaultShardKey?: string;
3689
3660
  /**
@@ -4948,6 +4919,16 @@ declare const otlpSink: (options: OtlpSinkOptions) => ObservabilitySink;
4948
4919
  *
4949
4920
  * Each child sink is invoked in order; a throw from one does not prevent the
4950
4921
  * others from running (each call is individually guarded).
4922
+ *
4923
+ * A sink is not only its five callbacks: `fuseCloudflareTraces`,
4924
+ * `instrumentDatabase`, `metricHistory` and `traceFetch` are configuration the
4925
+ * shard DO reads directly off this object. They are carried through here,
4926
+ * FIRST-WINS across the children in argument order — returning only the
4927
+ * callbacks meant that
4928
+ * `combineSinks({ ...otlpSink(…), traceFetch: { propagate } }, consoleSink())`
4929
+ * produced a sink with no `traceFetch`, silently reverting to the `true` default
4930
+ * and injecting `traceparent` into every outbound `ctx.fetch` — including the
4931
+ * third-party hosts the predicate existed to exclude.
4951
4932
  * @param sinks The sinks to fan out to.
4952
4933
  */
4953
4934
  declare const combineSinks: (...sinks: ObservabilitySink[]) => ObservabilitySink;
@@ -5075,11 +5056,11 @@ declare const createShardClient: (namespace: ShardNamespaceLike, options?: Shard
5075
5056
  */
5076
5057
  declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
5077
5058
  declare const VERSION: string;
5078
- export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext,
5059
+ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext,
5079
5060
  /**
5080
5061
  * Resource attribute bag used by OTLP exporters. Re-exported from `shared/otlp`
5081
5062
  * because {@link OtlpSinkOptions.resourceAttributes} is part of the public
5082
5063
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5083
5064
  * into a typed constant.
5084
5065
  */
5085
- type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5066
+ type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.d.ts CHANGED
@@ -873,29 +873,6 @@ type MergeStrategy = {
873
873
  kind: "groupBy";
874
874
  op?: "max" | "min" | "sum";
875
875
  };
876
- /**
877
- * Convenience: build the right wire-serializable {@link MergeStrategy} for a
878
- * given aggregate read. The reader doesn't know which op the caller chose, so
879
- * a fan-out wrapper passes the user's op + by-keys through this to derive the
880
- * merge.
881
- *
882
- * - `count` → `sum`.
883
- * - `aggregate({ op })` → `sum`/`max`/`min` (or throws for `avg`).
884
- * - `groupBy({ by, agg })` → `groupBy({ op })` (defaults to `sum` since
885
- * `groupBy`'s default reducer is `count`).
886
- * @returns the derived {@link MergeStrategy}.
887
- */
888
- declare const mergeStrategyForAggregate: (input: {
889
- agg?: {
890
- op?: "avg" | "count" | "max" | "min" | "sum";
891
- };
892
- kind: "groupBy";
893
- } | {
894
- kind: "count";
895
- } | {
896
- kind: "scalar";
897
- op: "avg" | "count" | "max" | "min" | "sum";
898
- }) => MergeStrategy;
899
876
  interface FanOutSpec {
900
877
  merge: MergeStrategy;
901
878
  /** Table whose shard keys drive the fan-out. */
@@ -938,6 +915,21 @@ interface QueryCoordinatorOptions {
938
915
  /** Required — drives which shards to fan out to. */
939
916
  registry: ShardRegistry;
940
917
  }
918
+ /**
919
+ * Shard a fan-out falls back to when registry discovery finds nothing — normally
920
+ * the worker's `"__root__"` — or `null` to deliberately keep an empty discovery
921
+ * as an empty fan-out.
922
+ *
923
+ * Required on every request that has it, with no default, on purpose. Discovery
924
+ * is registry-driven and a registry only knows the keys an app registers for its
925
+ * `.shardBy(...)` tables, so on a plain root-DO app it comes back empty and a
926
+ * fan-out that reads that as "nothing to do" reports success having touched
927
+ * nothing: an export streamed an empty NDJSON backup, a migration reported
928
+ * `completed` with `processed: 0`. Fan-outs inherited that bug by simply not
929
+ * passing the field, so omission is no longer expressible — say `null` when you
930
+ * mean it. See {@link withDefaultShard}.
931
+ */
932
+ type DefaultShardKey = string | null;
941
933
  interface FanOutRequest {
942
934
  args?: Record<string, unknown>;
943
935
  fanOut: FanOutSpec;
@@ -958,12 +950,8 @@ interface FanOutRequest {
958
950
  */
959
951
  interface MigrationFanOutRequest {
960
952
  args?: Record<string, unknown>;
961
- /**
962
- * Shard to fall back to when registry discovery finds nothing — normally
963
- * `"__root__"`. See {@link withDefaultShard}; omit it to keep an empty
964
- * discovery as an empty fan-out.
965
- */
966
- defaultShardKey?: string;
953
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
954
+ defaultShardKey: DefaultShardKey;
967
955
  functionPath: string;
968
956
  headers?: Record<string, string>;
969
957
  /** Table whose live shard keys the migration runs across. */
@@ -1171,22 +1159,8 @@ interface QueryCoordinator {
1171
1159
  */
1172
1160
  interface ExportFanOutRequest {
1173
1161
  args?: Record<string, unknown>;
1174
- /**
1175
- * Shard to fall back to when registry discovery yields NOTHING for the
1176
- * requested tables — normally `"__root__"`.
1177
- *
1178
- * Discovery is registry-driven, and a registry only knows the shard keys an
1179
- * app registers for its `.shardBy(...)` tables. A plain root-DO table has no
1180
- * entry and never will, so the union came back empty and the export fanned
1181
- * out to zero shards — returning an empty NDJSON body that looks like a
1182
- * successful backup of a table that simply had no rows. `orchestrateImport`
1183
- * has always resolved the same case to the default shard; export not doing so
1184
- * meant a round trip could silently write back nothing.
1185
- *
1186
- * Omit to keep the old "no keys, no shards" behavior (a caller that has
1187
- * already resolved its own shard set).
1188
- */
1189
- defaultShardKey?: string;
1162
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
1163
+ defaultShardKey: DefaultShardKey;
1190
1164
  headers?: Record<string, string>;
1191
1165
  /**
1192
1166
  * Tables driving the fan-out. Shards are derived from the union of each
@@ -1222,12 +1196,8 @@ interface ExportFanOutResult {
1222
1196
  */
1223
1197
  interface CdcSyncFanOutRequest {
1224
1198
  cursors?: Record<string, number>;
1225
- /**
1226
- * Shard to fall back to when registry discovery finds nothing — normally
1227
- * `"__root__"`. See {@link withDefaultShard}; omit it to keep an empty
1228
- * discovery as an empty fan-out.
1229
- */
1230
- defaultShardKey?: string;
1199
+ /** {@link DefaultShardKey} — the shard fallback, or `null` for none. */
1200
+ defaultShardKey: DefaultShardKey;
1231
1201
  headers?: Record<string, string>;
1232
1202
  limit?: number;
1233
1203
  tables: ReadonlyArray<string>;
@@ -1423,6 +1393,16 @@ interface RunExportTapOptions {
1423
1393
  coordinator: QueryCoordinator;
1424
1394
  /** Durable cursor store (per-shard watermark). */
1425
1395
  cursorStore: ExportCursorStore;
1396
+ /**
1397
+ * Shard to drain when registry discovery finds nothing — normally the
1398
+ * worker's `"__root__"` — or `null` to keep an empty discovery as an empty
1399
+ * pass. Forwarded verbatim to `orchestrateCdcSync`, and required for the
1400
+ * same reason it is required there: a registry only knows the keys an app
1401
+ * registers for its `.shardBy(...)` tables, so on a plain root-DO app
1402
+ * discovery is `[]` and a caller that omitted this drained no shards while
1403
+ * reporting `{ delivered: 0, hasMore: false }` against a full change feed.
1404
+ */
1405
+ defaultShardKey: string | null;
1426
1406
  /** Headers forwarded to each shard (identity / admin bearer). */
1427
1407
  headers?: Record<string, string>;
1428
1408
  /** Base backoff in ms for the first retry (doubles each attempt, capped at `maxBackoffMs`). Defaults to `100`. */
@@ -1940,7 +1920,7 @@ interface PipelineLogQuery {
1940
1920
  functionPathPrefix?: string;
1941
1921
  /** Match only this exact severity. When set, `minLevel` is ignored for the same field. */
1942
1922
  level?: ContextLogLevel;
1943
- /** Max rows to return. Clamped to `[1, 10000]`; defaults to {@link DEFAULT_LOG_LIMIT}. */
1923
+ /** Max rows to return. Clamped to `[1, 10000]`; defaults to 500. */
1944
1924
  limit?: number;
1945
1925
  /** Severity floor: keep every level at or above this in {@link LOG_LEVEL_ORDER} (e.g. `warn` keeps warn, error, fatal). */
1946
1926
  minLevel?: ContextLogLevel;
@@ -2014,8 +1994,6 @@ interface PipelineLogReader {
2014
1994
  }
2015
1995
  /** The written-column contract exposed publicly: canonical field to default physical column name. */
2016
1996
  declare const DEFAULT_LOG_COLUMNS: Readonly<Record<PipelineLogField, string>>;
2017
- /** Default page size when a query omits `limit`. */
2018
- declare const DEFAULT_LOG_LIMIT: number;
2019
1997
  /**
2020
1998
  * Build a durable-log reader over one R2 Data Catalog (Iceberg) table.
2021
1999
  *
@@ -2539,8 +2517,6 @@ interface RestRouteDeps {
2539
2517
  * `shared/rest-surface` helper).
2540
2518
  */
2541
2519
  declare const restSurfaceFromRegistry: (functions: RestRegistryLike) => ReturnType<typeof describeRestSurface>;
2542
- /** Read `shardKey` from `?shardKey=` or the `x-lunora-shard-key` header; `undefined` routes to the default shard. */
2543
- declare const readShardKey: (url: URL, request: Request) => string | undefined;
2544
2520
  /**
2545
2521
  * Decode GET args from the query string. Each value is parsed as JSON when it
2546
2522
  * looks like a JSON scalar/array/object (so `?limit=10` → number, `?ids=[1,2]` →
@@ -3679,11 +3655,6 @@ interface WorkerOptions {
3679
3655
  * the same expression as {@link WorkerOptions.backupCron} runs alongside it.
3680
3656
  */
3681
3657
  crons?: Record<string, CronHandler>;
3682
- /**
3683
- * D1 binding for `.global()` tables. Currently unused by the routing
3684
- * layer; downstream packages will read it from `env.DB` directly.
3685
- */
3686
- d1?: unknown;
3687
3658
  /** Default shard key used when an envelope omits one. */
3688
3659
  defaultShardKey?: string;
3689
3660
  /**
@@ -4948,6 +4919,16 @@ declare const otlpSink: (options: OtlpSinkOptions) => ObservabilitySink;
4948
4919
  *
4949
4920
  * Each child sink is invoked in order; a throw from one does not prevent the
4950
4921
  * others from running (each call is individually guarded).
4922
+ *
4923
+ * A sink is not only its five callbacks: `fuseCloudflareTraces`,
4924
+ * `instrumentDatabase`, `metricHistory` and `traceFetch` are configuration the
4925
+ * shard DO reads directly off this object. They are carried through here,
4926
+ * FIRST-WINS across the children in argument order — returning only the
4927
+ * callbacks meant that
4928
+ * `combineSinks({ ...otlpSink(…), traceFetch: { propagate } }, consoleSink())`
4929
+ * produced a sink with no `traceFetch`, silently reverting to the `true` default
4930
+ * and injecting `traceparent` into every outbound `ctx.fetch` — including the
4931
+ * third-party hosts the predicate existed to exclude.
4951
4932
  * @param sinks The sinks to fan out to.
4952
4933
  */
4953
4934
  declare const combineSinks: (...sinks: ObservabilitySink[]) => ObservabilitySink;
@@ -5075,11 +5056,11 @@ declare const createShardClient: (namespace: ShardNamespaceLike, options?: Shard
5075
5056
  */
5076
5057
  declare const STORAGE_UPLOAD_MAX_BODY_BYTES: number;
5077
5058
  declare const VERSION: string;
5078
- export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_LOG_LIMIT, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext,
5059
+ export { type AccessContextLike, type AccessIdentityLike, type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, BACKUP_KEY_PREFIX, type BackupManifest, type BackupManifestEntry, type BackupRetentionPreview, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_LOG_COLUMNS, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportBatch, type ExportChange, type ExportCursorStore, type ExportFanOutRequest, type ExportFanOutResult, type ExportSink, type ExportTapFailure, type ExportTapResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, HEALTH_PATH, HEALTH_READY_PATH, type HealthAuthPosture, type HealthBody, type HealthCheckReport, type HealthProbe, type HealthProbeKind, type HealthProbeResult, type HealthRouteDeps, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, LOG_ARCHIVE_NOT_CONFIGURED, LOG_ARCHIVE_PATH, type ListAuthUsersOptions, type LogArchiveConfig, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MemoizeIdentityOptions, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type NotifySubscriptionDevice, type NotifySubscriptionStoreLike, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext,
5079
5060
  /**
5080
5061
  * Resource attribute bag used by OTLP exporters. Re-exported from `shared/otlp`
5081
5062
  * because {@link OtlpSinkOptions.resourceAttributes} is part of the public
5082
5063
  * surface — without a name for it, a caller cannot hoist a shared attribute bag
5083
5064
  * into a typed constant.
5084
5065
  */
5085
- type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, mergeStrategyForAggregate, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, readShardKey, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
5066
+ type OtlpResourceAttributes, type OtlpSinkOptions, type PipelineLike, type PipelineLogColumnMap, type PipelineLogCursor, type PipelineLogField, type PipelineLogPage, type PipelineLogQuery, type PipelineLogReader, type PipelineLogReaderOptions, type PipelineLogRow, type PipelineLogSinkOptions, type PrunedBackups, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type RateLimiterLike, type ResolvedSecurity, type ResolvedShard, type RestInvoke, type RestRateLimit, type RestRegistryEntry, type RestRegistryLike, type RestRoute, type RestRouteDeps, type Route, type RpcContext, type RpcEnvelope, type RunExportTapOptions, SHARD_REGISTRY_DO_NAME, STORAGE_UPLOAD_MAX_BODY_BYTES, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardCallArgs, type ShardCallOptions, type ShardCallReturn, type ShardCaller, type ShardCallerIdentity, type ShardClient, type ShardClientOptions, type ShardError, type ShardExportOutcome, type ShardFunctionReference, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceInput, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, type TraceSamplingConfig, type TraceTrustSignal, type TrustInboundTraceContext, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, applyRestCache, argsFromQuery, backupManifestKey, backupObjectKey, backupObjectKeyOfManifest, buildHealthRoutes, buildRestRoutes, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createKvCursorStore, createLunoraHandler, createMemoryCursorStore, createPipelineLogReader, createQueryCoordinator, createRestRateLimit, createShardClient, createStaticShardRegistry, createWorker, d1Probe, decorateResponse, defineExportSink, defineRpcEnvelope, durableObjectProbe, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, isBackupManifestEntry, isBackupManifestKey, memoizeIdentity, memoizeIdentityPerRequest, normalizeBackupPrefix, otlpSink, pipelineLogSink, presenceProbe, r2Sink, requestCarriesCredentials, resolveLogArchiveFromEnv, resolveLunoraOptions, resolveSecurity, resolveShard, restCacheHeaders, restSurfaceFromRegistry, routeIdentityResolvers, runExportTap, sanitizeChange, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookExportSink, webhookSink, withFrameworkWorker };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-CIjE6Vm1.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-Bz6FNFLU.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-BRX27FkU.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as b,toErrorResponse as g}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-DLm6fYoN.mjs";import{HEALTH_PATH as K,HEALTH_READY_PATH as N,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-vDK-rMbs.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-D9xt5_FI.mjs";import{D as pe,a as ce,c as me}from"./packem_shared/pipeline-log-reader-BGrl66P5.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-B4Zk2HfK.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as ye,b as ke}from"./packem_shared/rest-cache-CPSyD1RD.mjs";import{a as Ae,b as Ce,c as Le,r as Te,d as be}from"./packem_shared/rest-routes-Dq17Zntv.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-0Tz9JwbX.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ue}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,ce as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,K as HEALTH_PATH,N as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,b as LunoraError,Ue as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,me as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,be as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,g as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
1
+ import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-DvYrhqLf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-KxOmsDWE.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-BYNkv1Ys.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CGR3Xd9F.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-vDK-rMbs.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-B3sQ6FPW.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-Ctr3eqmp.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-CPSyD1RD.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-ZZES0ngM.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-DoKTlCKb.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import{D as r,c as L}from"./pipeline-log-reader-C-nuWG_e.mjs";export{r as DEFAULT_LOG_COLUMNS,L as createPipelineLogReader};
@@ -0,0 +1 @@
1
+ import{createR2Sql as h}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as l}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L,c as A}from"./pipeline-log-reader-C-nuWG_e.mjs";import{LunoraError as _}from"./LunoraError-DksAgIpa.mjs";import{a as R}from"./method-guard-BG_vJNTl.mjs";const v="/_lunora/admin/logs/archive",m="LUNORA_LOG_ARCHIVE_TABLE",C="LUNORA_LOG_ARCHIVE_NAMESPACE",V=e=>{if(typeof e!="object"||e===null)return;const o=e,s=o[m];if(typeof s!="string"||s==="")return;const n=o[C];return{table:s,...typeof n=="string"&&n!==""?{namespace:n}:{}}},T=new Set(L),O=e=>typeof e=="string"&&e!==""?e:void 0,S=(e,o)=>{if(e!==void 0){if(typeof e!="string"||!T.has(e))throw new _(`logs archive: invalid \`${o}\` — expected one of ${L.join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},p=(e,o)=>{if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))throw new _(`logs archive: invalid \`${o}\` — expected a finite number`,{code:"BAD_REQUEST",status:400});return e}},b=e=>{const o={},s=r=>{const t=O(e[r]);t!==void 0&&(o[r]=t)},n=r=>{const t=S(e[r],r);t!==void 0&&(o[r]=t)},i=r=>{const t=p(e[r],r);t!==void 0&&(o[r]=t)};s("functionPath"),s("functionPathPrefix"),s("traceId"),s("shardKey"),s("userId"),n("level"),n("minLevel"),i("sinceTs"),i("untilTs"),i("limit");const c=e.cursor;if(typeof c=="object"&&c!==null){const r=c,t=p(r.ts,"cursor.ts");if(t!==void 0){const a=r.seen;if(a!==void 0&&(!Array.isArray(a)||a.some(d=>typeof d!="string")))throw new _("logs archive: invalid `cursor.seen` — expected an array of strings",{code:"BAD_REQUEST",status:400});const u=a;o.cursor=u===void 0||u.length===0?{ts:t}:{seen:u,ts:t}}}return o},y=e=>{const o=e.R2_SQL_ACCOUNT_ID??e.CLOUDFLARE_ACCOUNT_ID,s=e.R2_SQL_TOKEN,n=e.R2_SQL_BUCKET,i=[];if((o===void 0||o==="")&&i.push("R2_SQL_ACCOUNT_ID"),(s===void 0||s==="")&&i.push("R2_SQL_TOKEN"),(n===void 0||n==="")&&i.push("R2_SQL_BUCKET"),i.length>0)throw new _(`log archive not configured (missing ${i.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET must be set — see the observability docs.`,{code:l,status:400});return{accountId:o,apiToken:s,bucket:n}},B=e=>{const{createReader:o=A,readJsonBody:s,requireAdminOption:n}=e,i=async(c,r)=>{R(c,"POST","Log-archive");const t=n(c,e.logArchive,{code:l,message:"log archive requires a `logArchive` config (an R2 Data Catalog table) on the worker — see the observability docs"}),{accountId:a,apiToken:u,bucket:d}=y(r??{}),g=b(await s(c)),E=h({accountId:a,apiToken:u,bucket:d}),f=await o(E,{columnMap:t.columnMap,namespace:t.namespace,table:t.table}).query(g);return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[v]:i}};export{l as LOG_ARCHIVE_NOT_CONFIGURED,v as LOG_ARCHIVE_PATH,B as buildLogArchiveAdminRoutes,V as resolveLogArchiveFromEnv};
@@ -0,0 +1 @@
1
+ import{e as p,L as y,o as x,c as S,O as $,f as X,g as q,h as J,w as G,i as Y,j as Z,m as Q}from"./otlp-resource-DeXhb949.mjs";const v=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},C=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:v(r),rr=512,tr=200,or=r=>{const s=r.maxItems??rr,o=r.maxDelayMs??tr;let t=[],e,a,n;const c=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},h=async()=>{c();const l=t;t=[];const d=n;a=void 0,n=void 0;try{l.length>0&&await r.export(l)}catch{}finally{d?.()}},m=l=>{a===void 0&&(a=new Promise(d=>{n=d}),e=setTimeout(()=>{h()},o)),l?.(a)};return{add:(l,d)=>{for(t.push(l);t.length>s;)t.shift();m(d),t.length>=s&&h()},flush:async l=>{if(t.length===0){c();return}const d=h();return l?.(d),d},get size(){return t.length}}},sr=/["\\\u0000-\u001F\uD800-\uDFFF]/,D=r=>sr.test(r)?JSON.stringify(r):`"${r}"`,A=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return D(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let c=0;c<r.length;c++)c>0&&(n+=","),n+=A(r[c]);return n+"]"}const s=Object.getPrototypeOf(r);if(s!==null&&s!==Object.prototype){const n=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=r,t=Object.keys(o).sort();let e="{",a=!0;for(const n of t){const c=o[n];c!==void 0&&(a?a=!1:e+=",",e+=D(n),e+=":",e+=A(c))}return e+"}"},er=(r,s)=>{const o=[p(y.functionPath,r.functionPath),p(y.ok,r.ok)];r.method!==void 0&&o.push(p("http.request.method",r.method)),r.path!==void 0&&o.push(p("url.path",r.path)),o.push(p("http.route",r.functionPath)),r.scheme!==void 0&&o.push(p("url.scheme",r.scheme)),r.host!==void 0&&o.push(p("server.address",r.host)),r.port!==void 0&&o.push(p("server.port",r.port)),r.userAgent!==void 0&&o.push(p("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(p(y.shardKey,r.shardKey)),o.push(p("http.response.status_code",r.error?.status??200)),r.error&&o.push(p(y.errorType,r.error.code),p("lunora.error_status",r.error.status)),r.fanOut&&o.push(p("lunora.fanout.table",r.fanOut.table),p("lunora.fanout.shards",r.fanOut.shards),p("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:S(s),kind:$.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??x(8),startTimeUnixNano:S(s-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??x(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:[p("exception.type",r.error.code),p("exception.message",r.error.message)],name:"exception",timeUnixNano:S(s)}]),t},L=(r,s)=>{const o=new Map([[y.functionPath,p(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(y.shardKey,p(y.shardKey,r.shardKey)),r.userId!==void 0&&o.set(y.userId,p(y.userId,r.userId)),r.errorType!==void 0&&o.set(y.errorType,p(y.errorType,r.errorType));for(const[t,e]of Object.entries(s??{}))o.set(t,p(t,C(e)));return[...o.values()]},nr=r=>{const s={attributes:L({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),kind:$[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>q(Object.fromEntries(Object.entries(t??{}).map(([e,a])=>[e,C(a)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:S(t.ts)}))),r.links!==void 0&&r.links.length>0&&(s.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),s},ir=r=>{const s=S(r.ts),o=L({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t={asDouble:r.value,attributes:o,timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[t]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[t],isMonotonic:!0}}},ar=r=>{const s={attributes:L({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:X[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes.push(p("event.name",r.eventName))),s},cr=1024,dr=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},H=async(r,s,o,t)=>{try{const e=JSON.stringify(s),{byteLength:a}=new TextEncoder().encode(e),n=(a<cr?fetch(r,{body:e,headers:o,method:"POST"}):dr(e).then(c=>fetch(r,{body:c,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(()=>{},()=>{});t?.(n),await n}catch{}},ur=(r,s,o,t)=>{H(r,s,o,t?.waitUntil).catch(()=>{})},O=(r,s)=>s===!0&&r.ok,pr=r=>r.kind==="metric"?void 0:r.event.traceId,lr=r=>{const s=Map.groupBy(r,t=>pr(t)),o=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:o}},j=5,fr=(r,s,o)=>{if(s===void 0)return r;const{byTrace:t,untraced:e}=lr(r),a=[...e];let n=0,c;for(const[h,m]of t){let l;try{l=s({logs:m.filter(d=>d.kind==="log").map(d=>d.event),rpc:m.filter(d=>d.kind==="rpc").map(d=>d.event),spans:m.filter(d=>d.kind==="span").map(d=>d.event),traceId:h})}catch(d){n+=1,n===1&&(c=d),l=!0}l&&a.push(...m)}return n>0&&o(c,n),a},P=(r,s)=>{if(s===void 0)return r;try{return s(r)??void 0}catch{return}},B=(r,s)=>{if(r.kind==="rpc"){const t=P(r.event,s?.rpc);return t===void 0?void 0:{bucket:"spans",encoded:er(t,r.endMs)}}if(r.kind==="span"){const t=P(r.event,s?.span);return t===void 0?void 0:{bucket:"spans",encoded:nr(t)}}if(r.kind==="log"){const t=P(r.event,s?.log);return t===void 0?void 0:{bucket:"logs",encoded:ar(t)}}const o=P(r.event,s?.metric);return o===void 0?void 0:{bucket:"metrics",encoded:ir(o)}},mr=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],yr=(r={})=>{const{onlyErrors:s}=r;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{O(o,s)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const t=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,t,o.functionPath)}}},gr=r=>{const{headers:s,onlyErrors:o,transform:t,transformLog:e,url:a}=r,n=J({"content-type":"application/json"},s),c=(h,m)=>{try{const l=fetch(a,{body:JSON.stringify(h),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(l)}catch{}};return{onLog:(h,m)=>{const l=P(h,e);l!==void 0&&c(l,m)},onRpc:(h,m)=>{if(O(h,o))return;const l=P(h,t);l!==void 0&&c(l,m)}}},br=r=>{const{capture:s,captureLog:o}=r,t=r.onlyErrors??!0;return{onLog:o?e=>{try{o(e)}catch{}}:void 0,onRpc:e=>{if(!O(e,t))try{s(e)}catch{}}}},kr=r=>{const{dataset:s,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{s.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},Sr=r=>{const{pipeline:s,serializeFields:o}=r;return{onLog:(t,e)=>{try{const a={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(a.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const c of["shardKey","userId","traceId","spanId"])t[c]!==void 0&&(a[c]=t[c]);const n=s.send([a]).catch(()=>{});e?.waitUntil&&e.waitUntil(n)}catch{}}}},Ir=r=>{const{batch:s,deploymentEnvironment:o,detectResources:t,endpoint:e,headers:a,onlyErrors:n,postProcessor:c,resourceAttributes:h,serviceNamespace:m,serviceVersion:l,tailSampler:d,token:z}=r,R=r.serviceName??"lunora",U={...l===void 0?{}:{"service.version":l},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...h},F=new WeakMap,k=u=>{if(t!==!0||u?.resourceAttributes===void 0)return U;const i=F.get(u);if(i!==void 0)return i;const f=Q(u.resourceAttributes(),U);return F.set(u,f),f};let I=e;for(;I.endsWith("/");)I=I.slice(0,-1);const _={logs:{url:`${I}/v1/logs`,wrap:Z},metrics:{url:`${I}/v1/metrics`,wrap:Y},spans:{url:`${I}/v1/traces`,wrap:G}},K=J({"content-type":"application/json"},a,z);let M=0;const V=(u,i)=>{if(M>=j)return;M+=1;const f=M===j?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(i)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,u)},W=async u=>{const i=fr(u,d,V),f=new Map;for(const g of i){const b=B(g,c);if(b===void 0)continue;const E=A(g.resource);let T=f.get(E);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(E,T)),T[b.bucket].push(b.encoded)}const w=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:E,wrap:T}=_[b];w.push(H(E,T(g[b],"@lunora/runtime",R,g.resource),K))}await Promise.all(w)};if(s===!1){const u=(i,f)=>{const w=B(i,c);if(w!==void 0){const{url:g,wrap:b}=_[w.bucket];ur(g,b(w.encoded,"@lunora/runtime",R,i.resource),K,f)}};return{onLog:(i,f)=>{u({event:i,kind:"log",resource:k(f)},f)},onMetric:(i,f)=>{u({event:i,kind:"metric",resource:k(f)},f)},onRpc:(i,f)=>{O(i,n)||u({endMs:Date.now(),event:i,kind:"rpc",resource:k(f)},f)},onSpan:(i,f)=>{u({event:i,kind:"span",resource:k(f)},f)}}}const N=or({export:W,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:u=>{N.flush(u?.waitUntil).catch(()=>{})},onLog:(u,i)=>{N.add({event:u,kind:"log",resource:k(i)},i?.waitUntil)},onMetric:(u,i)=>{N.add({event:u,kind:"metric",resource:k(i)},i?.waitUntil)},onRpc:(u,i)=>{O(u,n)||N.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(i)},i?.waitUntil)},onSpan:(u,i)=>{N.add({event:u,kind:"span",resource:k(i)},i?.waitUntil)}}},wr=(...r)=>{const s=(t,e)=>{for(const a of r){const n=a[t];if(n)try{n.apply(a,e)}catch{}}},o={};for(const t of r)for(const e of mr)o[e]===void 0&&t[e]!==void 0&&(o[e]=t[e]);return{...o,flush:t=>{s("flush",[t])},onLog:(t,e)=>{s("onLog",[t,e])},onMetric:(t,e)=>{s("onMetric",[t,e])},onRpc:(t,e)=>{s("onRpc",[t,e])},onSpan:(t,e)=>{s("onSpan",[t,e])}}};export{kr as analyticsEngineSink,wr as combineSinks,yr as consoleSink,Ir as otlpSink,Sr as pipelineLogSink,br as sentrySink,gr as webhookSink};
@@ -0,0 +1 @@
1
+ import"./rest-cache-CPSyD1RD.mjs";import{a,b as o,c as i,r as m}from"./rest-routes-ZZES0ngM.mjs";import"./method-guard-BG_vJNTl.mjs";export{a as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as restSurfaceFromRegistry};