@lunora/server 1.0.0-alpha.29 → 1.0.0-alpha.290

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 (104) hide show
  1. package/LICENSE.md +414 -104
  2. package/README.md +21 -15
  3. package/dist/data-model.d.mts +328 -78
  4. package/dist/data-model.d.ts +328 -78
  5. package/dist/data-model.mjs +0 -1
  6. package/dist/drizzle.mjs +1 -1
  7. package/dist/in-process.d.mts +115 -0
  8. package/dist/in-process.d.ts +115 -0
  9. package/dist/in-process.mjs +1 -0
  10. package/dist/index.d.mts +3615 -1125
  11. package/dist/index.d.ts +3615 -1125
  12. package/dist/index.mjs +1 -29
  13. package/dist/otel.d.mts +649 -0
  14. package/dist/otel.d.ts +649 -0
  15. package/dist/otel.mjs +1 -0
  16. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-Dv4DKrj0.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_LIMIT-z7HB19s7.mjs +1 -0
  18. package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs +1 -0
  19. package/dist/packem_shared/LunoraEnvError-06_Zc4yc.mjs +3 -0
  20. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-aj9Ec70J.mjs +1 -0
  21. package/dist/packem_shared/PROCEDURE_META-DVzrXpfa.mjs +1 -0
  22. package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
  23. package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
  24. package/dist/packem_shared/asBucketStorage-DoGYOjq3.mjs +1 -0
  25. package/dist/packem_shared/assertShapesDeclareReadPolicies-B9Kat3xb.mjs +1 -0
  26. package/dist/packem_shared/authorize-CVLZJxf_.mjs +1 -0
  27. package/dist/packem_shared/beginDeferredDeletes-DhwFBbvs.mjs +1 -0
  28. package/dist/packem_shared/beginDeferredSchedules-BOsY07vZ.mjs +1 -0
  29. package/dist/packem_shared/bindOrm-DjpQXKLX.mjs +1 -0
  30. package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
  31. package/dist/packem_shared/compose-middleware-BK9FlblN.mjs +1 -0
  32. package/dist/packem_shared/composePluginMiddleware-3e7F9JIa.mjs +1 -0
  33. package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
  34. package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
  35. package/dist/packem_shared/createSecrets-D6rLB42U.mjs +1 -0
  36. package/dist/packem_shared/createServices-IJvoqi0e.mjs +1 -0
  37. package/dist/packem_shared/defineAggregateIndex-C3xWV-Dr.mjs +1 -0
  38. package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
  39. package/dist/packem_shared/defineIdentityGuard-Bt8N65Zs.mjs +1 -0
  40. package/dist/packem_shared/defineLiveStream-D3xRvNDy.mjs +1 -0
  41. package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
  42. package/dist/packem_shared/defineModule-OecXWM3U.mjs +1 -0
  43. package/dist/packem_shared/defineMutator-DlLFSWbO.mjs +1 -0
  44. package/dist/packem_shared/defineRoom-CoGi-xwm.mjs +1 -0
  45. package/dist/packem_shared/defineShape-BE1Drcby.mjs +1 -0
  46. package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
  47. package/dist/packem_shared/defineWebSocket-BHoy6_ox.mjs +1 -0
  48. package/dist/packem_shared/fnv1a-D3ueNTWB.mjs +1 -0
  49. package/dist/packem_shared/functions-QFoBUe9t.mjs +1 -0
  50. package/dist/packem_shared/httpAction-DD8h1jcf.mjs +1 -0
  51. package/dist/packem_shared/initLunora-DcvCGLL_.mjs +1 -0
  52. package/dist/packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs +1 -0
  53. package/dist/packem_shared/isSafeHeaderValue-DswDADFy.mjs +6 -0
  54. package/dist/packem_shared/mask-BdHDaOeI.mjs +1 -0
  55. package/dist/packem_shared/middleware-6q14NoEG.mjs +1 -0
  56. package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
  57. package/dist/packem_shared/onQueryChange-iuLzmyPs.mjs +1 -0
  58. package/dist/packem_shared/onWhisper-CfDbFLQh.mjs +1 -0
  59. package/dist/packem_shared/platformAdmin-kczXQme8.mjs +1 -0
  60. package/dist/packem_shared/plugin-CyLqvCB9.mjs +1 -0
  61. package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
  62. package/dist/packem_shared/protectPublic-Bi5_95aP.mjs +1 -0
  63. package/dist/packem_shared/redact-secrets-BpatNz48.mjs +2 -0
  64. package/dist/packem_shared/redactSecrets-Dmh9pHZu.mjs +1 -0
  65. package/dist/packem_shared/rls-QoHmZEia.mjs +1 -0
  66. package/dist/packem_shared/run-middleware-BefYq7Xd.mjs +1 -0
  67. package/dist/packem_shared/serveStorageObject-CLz3qhNI.mjs +1 -0
  68. package/dist/packem_shared/storageRules-gnLtvRbZ.mjs +1 -0
  69. package/dist/packem_shared/types.d--zaGh3rX.d.mts +3025 -0
  70. package/dist/packem_shared/types.d--zaGh3rX.d.ts +3025 -0
  71. package/dist/packem_shared/{types.d-C4CMJK8x.d.mts → types.d-B7FLdYUD.d.mts} +15 -8
  72. package/dist/packem_shared/{types.d-DdYF8E18.d.ts → types.d-BCtjbIzl.d.ts} +15 -8
  73. package/dist/rls/testing.d.mts +13 -5
  74. package/dist/rls/testing.d.ts +13 -5
  75. package/dist/rls/testing.mjs +1 -49
  76. package/dist/types.d.mts +2 -1468
  77. package/dist/types.d.ts +2 -1468
  78. package/dist/types.mjs +0 -31
  79. package/package.json +28 -8
  80. package/dist/packem_shared/LunoraEnvError-BGmd1Qs0.mjs +0 -187
  81. package/dist/packem_shared/LunoraError-WbxmrpxR.mjs +0 -9
  82. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-Cv1UPaJj.mjs +0 -114
  83. package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
  84. package/dist/packem_shared/bindOrm-Bfgl7f-Q.mjs +0 -146
  85. package/dist/packem_shared/buildRlsReadRegistry-D54vUQe4.mjs +0 -107
  86. package/dist/packem_shared/composePluginMiddleware-z62dttBo.mjs +0 -103
  87. package/dist/packem_shared/createPolicyDsl-By3QB4he.mjs +0 -32
  88. package/dist/packem_shared/createSecrets-DwaR2rNG.mjs +0 -58
  89. package/dist/packem_shared/defineAggregateIndex-DTULzh09.mjs +0 -333
  90. package/dist/packem_shared/defineIdentity-DiX4zM9x.mjs +0 -35
  91. package/dist/packem_shared/defineMigration-Hx01yIht.mjs +0 -10
  92. package/dist/packem_shared/defineMutator-EIXAWhs9.mjs +0 -11
  93. package/dist/packem_shared/defineShape-C5scNOrf.mjs +0 -18
  94. package/dist/packem_shared/defineStorageRule-B5nL4Z1P.mjs +0 -23
  95. package/dist/packem_shared/functions-Di9FUNkf.mjs +0 -5
  96. package/dist/packem_shared/httpAction-DCXoYPIk.mjs +0 -355
  97. package/dist/packem_shared/initLunora-CmMVk4i7.mjs +0 -107
  98. package/dist/packem_shared/mask-CZuu9WAF.mjs +0 -331
  99. package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
  100. package/dist/packem_shared/policy-tag-DvpVH2tv.mjs +0 -13
  101. package/dist/packem_shared/protectPublic-BlcGpiRc.mjs +0 -15
  102. package/dist/packem_shared/rls-B_ZWgslr.mjs +0 -595
  103. package/dist/packem_shared/run-middleware-I6EiQfxL.mjs +0 -20
  104. package/dist/packem_shared/storageRules-6QxzDOcx.mjs +0 -88
package/dist/otel.d.ts ADDED
@@ -0,0 +1,649 @@
1
+ /**
2
+ * `@lunora/server/otel` — hand a Lunora `ctx` to anything that speaks
3
+ * `@opentelemetry/api`.
4
+ *
5
+ * **The problem.** Lunora's tracing is hand-rolled and zero-dependency, which is
6
+ * the right call for a runtime that has to boot in a Workers isolate. The cost
7
+ * is that a library instrumented against `@opentelemetry/api` — the Vercel AI
8
+ * SDK's `experimental_telemetry`, a database driver's instrumentation, an
9
+ * in-house shared package — cannot see Lunora's trace. Its spans go to whatever
10
+ * global provider is registered, which in a Worker is the no-op one. They vanish.
11
+ *
12
+ * **The fix.** {@link createOtelTracer} adapts a `ctx` into an OTel `Tracer`, so
13
+ * the library's spans become real `ctx.trace` spans in the request's trace:
14
+ *
15
+ * ```ts
16
+ * import { createOtelTracer } from "@lunora/server/otel";
17
+ *
18
+ * export const summarize = action.action(async ({ args, ctx }) =>
19
+ * generateText({
20
+ * model: openai("gpt-4o"),
21
+ * prompt: args.prompt,
22
+ * experimental_telemetry: { isEnabled: true, tracer: createOtelTracer(ctx) },
23
+ * }),
24
+ * );
25
+ * ```
26
+ *
27
+ * **Why passing the tracer explicitly is the supported path.** OTel's ambient
28
+ * `context` API (`trace.getActiveSpan()`, implicit parenting inside
29
+ * `startActiveSpan`) needs `AsyncLocalStorage` to track the current span across
30
+ * `await`s. Durable Objects run under a slimmer compatibility profile than
31
+ * `nodejs_compat`, and `@lunora/do` deliberately avoids ALS for that reason —
32
+ * the same reason `ctx.trace` threads its parent explicitly instead of keeping
33
+ * an ambient stack. So this bridge implements the `Tracer` surface faithfully
34
+ * and parents each span to the `Context` its caller THREADED (falling back to
35
+ * the dispatch when none was), never to a dynamically-scoped "current" span:
36
+ * nesting is flatter than a full SDK would give for a library that relies on
37
+ * ambient context, but every span lands in the right trace, under the parent it
38
+ * was told about, with the right timings, and none are lost. See
39
+ * {@link createOtelTracer} for the precise semantics.
40
+ *
41
+ * `@opentelemetry/api` is a PEER dependency: it keeps a module-global registry,
42
+ * so a second copy in the tree would silently split it.
43
+ */
44
+ import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d--zaGh3rX.js";
45
+ import '@lunora/values';
46
+ //#region src/context/types.d.ts
47
+ /**
48
+ * @since 1.0.0
49
+ */
50
+ interface Context {
51
+ /**
52
+ * Get a value from the context.
53
+ *
54
+ * @param key key which identifies a context value
55
+ */
56
+ getValue(key: symbol): unknown;
57
+ /**
58
+ * Create a new context which inherits from this context and has
59
+ * the given key set to the given value.
60
+ *
61
+ * @param key context key for which to set the value
62
+ * @param value value to set for the given key
63
+ */
64
+ setValue(key: symbol, value: unknown): Context;
65
+ /**
66
+ * Return a new context which inherits from this context but does
67
+ * not contain a value for the given key.
68
+ *
69
+ * @param key context key for which to clear a value
70
+ */
71
+ deleteValue(key: symbol): Context;
72
+ }
73
+ //#region src/common/AnyValue.d.ts
74
+ /**
75
+ * AnyValue can be:
76
+ * - a string, number, boolean value
77
+ * - a byte array (Uint8Array)
78
+ * - array of any value
79
+ * - map from string to any value (a plain Object)
80
+ * - null (an empty value)
81
+ *
82
+ * https://opentelemetry.io/docs/specs/otel/common/#anyvalue
83
+ *
84
+ * Notable JavaScript types that are excluded:
85
+ * - `undefined` - Excluding this means the common practice in instrumentations,
86
+ * using `undefined` to mean "no value for this optional attribute", can
87
+ * remain supported.
88
+ * - `BigInt`
89
+ * - TypedArrays other than `Uint8Array`
90
+ * - subclasses of Object, e.g. Date, Error
91
+ *
92
+ * The TypeScript type `unknown` is used for `AnyValue`. This has some
93
+ * implications:
94
+ * - Callers of `@opentelemetry/api` APIs using `AnyValue` can pass in
95
+ * whatever type. This was always the case for (untyped) JavaScript usage.
96
+ * - SDK implementations of `@opentelemetry/api` need to document if/when they
97
+ * support a subset of AnyValue types.
98
+ * - Using `unknown` allows future changes to support more types (e.g. BigInt).
99
+ *
100
+ * @since 1.10.0
101
+ */
102
+ type AnyValue = unknown;
103
+ //#region src/common/Attributes.d.ts
104
+ /**
105
+ * Attributes is a mapping from string to attribute values.
106
+ * https://opentelemetry.io/docs/specs/otel/common/#attribute-collections
107
+ *
108
+ * @since 1.1.0
109
+ */
110
+ interface Attributes {
111
+ [attributeKey: string]: AnyValue;
112
+ }
113
+ /**
114
+ * @since 1.1.0
115
+ * @deprecated use AnyValue
116
+ */
117
+ type AttributeValue = AnyValue;
118
+ //#region src/common/Time.d.ts
119
+ /**
120
+ * Defines High-Resolution Time.
121
+ *
122
+ * The first number, HrTime[0], is UNIX Epoch time in seconds since 00:00:00 UTC on 1 January 1970.
123
+ * The second number, HrTime[1], represents the partial second elapsed since Unix Epoch time represented by first number in nanoseconds.
124
+ * For example, 2021-01-01T12:30:10.150Z in UNIX Epoch time in milliseconds is represented as 1609504210150.
125
+ * The first number is calculated by converting and truncating the Epoch time in milliseconds to seconds:
126
+ * HrTime[0] = Math.trunc(1609504210150 / 1000) = 1609504210.
127
+ * The second number is calculated by converting the digits after the decimal point of the subtraction, (1609504210150 / 1000) - HrTime[0], to nanoseconds:
128
+ * HrTime[1] = Number((1609504210.150 - HrTime[0]).toFixed(9)) * 1e9 = 150000000.
129
+ * This is represented in HrTime format as [1609504210, 150000000].
130
+ *
131
+ * @since 1.0.0
132
+ */
133
+ type HrTime = [number, number];
134
+ /**
135
+ * Defines TimeInput.
136
+ *
137
+ * hrtime, epoch milliseconds, performance.now() or Date
138
+ *
139
+ * @since 1.0.0
140
+ */
141
+ type TimeInput = HrTime | number | Date;
142
+ //#region src/common/Exception.d.ts
143
+ interface ExceptionWithCode {
144
+ code: string | number;
145
+ name?: string;
146
+ message?: string;
147
+ stack?: string;
148
+ }
149
+ interface ExceptionWithMessage {
150
+ code?: string | number;
151
+ message: string;
152
+ name?: string;
153
+ stack?: string;
154
+ }
155
+ interface ExceptionWithName {
156
+ code?: string | number;
157
+ message?: string;
158
+ name: string;
159
+ stack?: string;
160
+ }
161
+ /**
162
+ * Defines Exception.
163
+ *
164
+ * string or an object with one of (message or name or code) and optional stack
165
+ *
166
+ * @since 1.0.0
167
+ */
168
+ type Exception = ExceptionWithCode | ExceptionWithMessage | ExceptionWithName | string;
169
+ //#region src/trace/attributes.d.ts
170
+ /**
171
+ * @deprecated please use {@link Attributes}
172
+ * @since 1.0.0
173
+ */
174
+ type SpanAttributes = Attributes;
175
+ /**
176
+ * @deprecated please use {@link AttributeValue}
177
+ * @since 1.0.0
178
+ */
179
+ type SpanAttributeValue = AttributeValue;
180
+ //#region src/trace/trace_state.d.ts
181
+ /**
182
+ * @since 1.0.0
183
+ */
184
+ interface TraceState {
185
+ /**
186
+ * Create a new TraceState which inherits from this TraceState and has the
187
+ * given key set.
188
+ * The new entry will always be added in the front of the list of states.
189
+ *
190
+ * @param key key of the TraceState entry.
191
+ * @param value value of the TraceState entry.
192
+ */
193
+ set(key: string, value: string): TraceState;
194
+ /**
195
+ * Return a new TraceState which inherits from this TraceState but does not
196
+ * contain the given key.
197
+ *
198
+ * @param key the key for the TraceState entry to be removed.
199
+ */
200
+ unset(key: string): TraceState;
201
+ /**
202
+ * Returns the value to which the specified key is mapped, or `undefined` if
203
+ * this map contains no mapping for the key.
204
+ *
205
+ * @param key with which the specified value is to be associated.
206
+ * @returns the value to which the specified key is mapped, or `undefined` if
207
+ * this map contains no mapping for the key.
208
+ */
209
+ get(key: string): string | undefined;
210
+ /**
211
+ * Serializes the TraceState to a `list` as defined below. The `list` is a
212
+ * series of `list-members` separated by commas `,`, and a list-member is a
213
+ * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs
214
+ * surrounding `list-members` are ignored. There can be a maximum of 32
215
+ * `list-members` in a `list`.
216
+ *
217
+ * @returns the serialized string.
218
+ */
219
+ serialize(): string;
220
+ }
221
+ //#region src/trace/span_context.d.ts
222
+ /**
223
+ * A SpanContext represents the portion of a {@link Span} which must be
224
+ * serialized and propagated along side of a {@link Baggage}.
225
+ *
226
+ * @since 1.0.0
227
+ */
228
+ interface SpanContext {
229
+ /**
230
+ * The ID of the trace that this span belongs to. It is worldwide unique
231
+ * with practically sufficient probability by being made as 16 randomly
232
+ * generated bytes, encoded as a 32 lowercase hex characters corresponding to
233
+ * 128 bits.
234
+ */
235
+ traceId: string;
236
+ /**
237
+ * The ID of the Span. It is globally unique with practically sufficient
238
+ * probability by being made as 8 randomly generated bytes, encoded as a 16
239
+ * lowercase hex characters corresponding to 64 bits.
240
+ */
241
+ spanId: string;
242
+ /**
243
+ * Only true if the SpanContext was propagated from a remote parent.
244
+ */
245
+ isRemote?: boolean;
246
+ /**
247
+ * Trace flags to propagate.
248
+ *
249
+ * It is represented as 1 byte (bitmap). Bit to represent whether trace is
250
+ * sampled or not. When set, the least significant bit documents that the
251
+ * caller may have recorded trace data. A caller who does not record trace
252
+ * data out-of-band leaves this flag unset.
253
+ *
254
+ * see {@link TraceFlags} for valid flag values.
255
+ */
256
+ traceFlags: number;
257
+ /**
258
+ * Tracing-system-specific info to propagate.
259
+ *
260
+ * The tracestate field value is a `list` as defined below. The `list` is a
261
+ * series of `list-members` separated by commas `,`, and a list-member is a
262
+ * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs
263
+ * surrounding `list-members` are ignored. There can be a maximum of 32
264
+ * `list-members` in a `list`.
265
+ * More Info: https://www.w3.org/TR/trace-context/#tracestate-field
266
+ *
267
+ * Examples:
268
+ * Single tracing system (generic format):
269
+ * tracestate: rojo=00f067aa0ba902b7
270
+ * Multiple tracing systems (with different formatting):
271
+ * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE
272
+ */
273
+ traceState?: TraceState;
274
+ }
275
+ //#region src/trace/status.d.ts
276
+ /**
277
+ * @since 1.0.0
278
+ */
279
+ interface SpanStatus {
280
+ /** The status code of this message. */
281
+ code: SpanStatusCode;
282
+ /** A developer-facing error message. */
283
+ message?: string;
284
+ }
285
+ /**
286
+ * An enumeration of status codes.
287
+ *
288
+ * @since 1.0.0
289
+ */
290
+ declare enum SpanStatusCode {
291
+ /**
292
+ * The default status.
293
+ */
294
+ UNSET = 0,
295
+ /**
296
+ * The operation has been validated by an Application developer or
297
+ * Operator to have completed successfully.
298
+ */
299
+ OK = 1,
300
+ /**
301
+ * The operation contains an error.
302
+ */
303
+ ERROR = 2
304
+ }
305
+ //#region src/trace/link.d.ts
306
+ /**
307
+ * A pointer from the current {@link Span} to another span in the same trace or
308
+ * in a different trace.
309
+ * Few examples of Link usage.
310
+ * 1. Batch Processing: A batch of elements may contain elements associated
311
+ * with one or more traces/spans. Since there can only be one parent
312
+ * SpanContext, Link is used to keep reference to SpanContext of all
313
+ * elements in the batch.
314
+ * 2. Public Endpoint: A SpanContext in incoming client request on a public
315
+ * endpoint is untrusted from service provider perspective. In such case it
316
+ * is advisable to start a new trace with appropriate sampling decision.
317
+ * However, it is desirable to associate incoming SpanContext to new trace
318
+ * initiated on service provider side so two traces (from Client and from
319
+ * Service Provider) can be correlated.
320
+ *
321
+ * @since 1.0.0
322
+ */
323
+ interface Link {
324
+ /** The {@link SpanContext} of a linked span. */
325
+ context: SpanContext;
326
+ /** A set of {@link SpanAttributes} on the link. */
327
+ attributes?: SpanAttributes;
328
+ /**
329
+ * Count of attributes of the link that were dropped due to collection limits
330
+ *
331
+ * @since 1.4.1
332
+ */
333
+ droppedAttributesCount?: number;
334
+ }
335
+ //#region src/trace/span.d.ts
336
+ /**
337
+ * An interface that represents a span. A span represents a single operation
338
+ * within a trace. Examples of span might include remote procedure calls or a
339
+ * in-process function calls to sub-components. A Trace has a single, top-level
340
+ * "root" Span that in turn may have zero or more child Spans, which in turn
341
+ * may have children.
342
+ *
343
+ * Spans are created by the {@link Tracer.startSpan} method.
344
+ *
345
+ * @since 1.0.0
346
+ */
347
+ interface Span {
348
+ /**
349
+ * Returns the {@link SpanContext} object associated with this Span.
350
+ *
351
+ * Get an immutable, serializable identifier for this span that can be used
352
+ * to create new child spans. Returned SpanContext is usable even after the
353
+ * span ends.
354
+ *
355
+ * @returns the SpanContext object associated with this Span.
356
+ */
357
+ spanContext(): SpanContext;
358
+ /**
359
+ * Sets an attribute to the span.
360
+ *
361
+ * Sets a single Attribute with the key and value passed as arguments.
362
+ *
363
+ * @param key the key for this attribute.
364
+ * @param value the value for this attribute. Setting a value null or
365
+ * undefined is invalid and will result in undefined behavior.
366
+ */
367
+ setAttribute(key: string, value: SpanAttributeValue): this;
368
+ /**
369
+ * Sets attributes to the span.
370
+ *
371
+ * @param attributes the attributes that will be added.
372
+ * null or undefined attribute values
373
+ * are invalid and will result in undefined behavior.
374
+ */
375
+ setAttributes(attributes: SpanAttributes): this;
376
+ /**
377
+ * Adds an event to the Span.
378
+ *
379
+ * @param name the name of the event.
380
+ * @param [attributesOrStartTime] the attributes that will be added; these are
381
+ * associated with this event. Can be also a start time
382
+ * if type is {@type TimeInput} and 3rd param is undefined
383
+ * @param [startTime] start time of the event.
384
+ */
385
+ addEvent(name: string, attributesOrStartTime?: SpanAttributes | TimeInput, startTime?: TimeInput): this;
386
+ /**
387
+ * Adds a single link to the span.
388
+ *
389
+ * Links added after the creation will not affect the sampling decision.
390
+ * It is preferred span links be added at span creation.
391
+ *
392
+ * @param link the link to add.
393
+ *
394
+ * @since 1.9.0
395
+ */
396
+ addLink(link: Link): this;
397
+ /**
398
+ * Adds multiple links to the span.
399
+ *
400
+ * Links added after the creation will not affect the sampling decision.
401
+ * It is preferred span links be added at span creation.
402
+ *
403
+ * @param links the links to add.
404
+ *
405
+ * @since 1.9.0
406
+ */
407
+ addLinks(links: Link[]): this;
408
+ /**
409
+ * Sets the status of the span.
410
+ *
411
+ * By default, a span has status {@link SpanStatusCode.UNSET}.
412
+ * Calling this method overrides that default.
413
+ *
414
+ * The status codes have a total order: `OK > ERROR > UNSET`.
415
+ *
416
+ * - Once {@link SpanStatusCode.OK} is set, any further attempts to change
417
+ * the status are ignored.
418
+ * - Any attempt to set {@link SpanStatusCode.UNSET} is always ignored.
419
+ *
420
+ * The `message` field is only used when {@link SpanStatusCode.ERROR} is set.
421
+ * For all other status codes, `message` is ignored.
422
+ *
423
+ * @param status The {@link SpanStatus} to set.
424
+ */
425
+ setStatus(status: SpanStatus): this;
426
+ /**
427
+ * Updates the Span name.
428
+ *
429
+ * This will override the name provided via {@link Tracer.startSpan}.
430
+ *
431
+ * Upon this update, any sampling behavior based on Span name will depend on
432
+ * the implementation.
433
+ *
434
+ * @param name the Span name.
435
+ */
436
+ updateName(name: string): this;
437
+ /**
438
+ * Marks the end of Span execution.
439
+ *
440
+ * Call to End of a Span MUST not have any effects on child spans. Those may
441
+ * still be running and can be ended later.
442
+ *
443
+ * Do not return `this`. The Span generally should not be used after it
444
+ * is ended so chaining is not desired in this context.
445
+ *
446
+ * @param [endTime] the time to set as Span's end time. If not provided,
447
+ * use the current time as the span's end time.
448
+ */
449
+ end(endTime?: TimeInput): void;
450
+ /**
451
+ * Returns the flag whether this span will be recorded.
452
+ *
453
+ * @returns true if this Span is active and recording information like events
454
+ * with the `AddEvent` operation and attributes using `setAttributes`.
455
+ */
456
+ isRecording(): boolean;
457
+ /**
458
+ * Sets exception as a span event
459
+ * @param exception the exception the only accepted values are string or Error
460
+ * @param [time] the time to set as Span's event time. If not provided,
461
+ * use the current time.
462
+ */
463
+ recordException(exception: Exception, time?: TimeInput): void;
464
+ }
465
+ //#region src/trace/span_kind.d.ts
466
+ /**
467
+ * @since 1.0.0
468
+ */
469
+ declare enum SpanKind {
470
+ /** Default value. Indicates that the span is used internally. */
471
+ INTERNAL = 0,
472
+ /**
473
+ * Indicates that the span covers server-side handling of an RPC or other
474
+ * remote request.
475
+ */
476
+ SERVER = 1,
477
+ /**
478
+ * Indicates that the span covers the client-side wrapper around an RPC or
479
+ * other remote request.
480
+ */
481
+ CLIENT = 2,
482
+ /**
483
+ * Indicates that the span describes producer sending a message to a
484
+ * broker. Unlike client and server, there is no direct critical path latency
485
+ * relationship between producer and consumer spans.
486
+ */
487
+ PRODUCER = 3,
488
+ /**
489
+ * Indicates that the span describes consumer receiving a message from a
490
+ * broker. Unlike client and server, there is no direct critical path latency
491
+ * relationship between producer and consumer spans.
492
+ */
493
+ CONSUMER = 4
494
+ }
495
+ //#region src/trace/SpanOptions.d.ts
496
+ /**
497
+ * Options needed for span creation
498
+ *
499
+ * @since 1.0.0
500
+ */
501
+ interface SpanOptions {
502
+ /**
503
+ * The SpanKind of a span
504
+ * @default {@link SpanKind.INTERNAL}
505
+ */
506
+ kind?: SpanKind;
507
+ /** A span's attributes */
508
+ attributes?: Attributes;
509
+ /** {@link Link}s span to other spans */
510
+ links?: Link[];
511
+ /** A manually specified start time for the created `Span` object. */
512
+ startTime?: TimeInput;
513
+ /** The new span should be a root span. (Ignore parent from context). */
514
+ root?: boolean;
515
+ }
516
+ //#region src/trace/tracer.d.ts
517
+ /**
518
+ * Tracer provides an interface for creating {@link Span}s.
519
+ *
520
+ * @since 1.0.0
521
+ */
522
+ interface Tracer {
523
+ /**
524
+ * Starts a new {@link Span}. Start the span without setting it on context.
525
+ *
526
+ * This method do NOT modify the current Context.
527
+ *
528
+ * @param name The name of the span
529
+ * @param [options] SpanOptions used for span creation
530
+ * @param [context] Context to use to extract parent
531
+ * @returns Span The newly created span
532
+ * @example
533
+ * const span = tracer.startSpan('op');
534
+ * span.setAttribute('key', 'value');
535
+ * span.end();
536
+ */
537
+ startSpan(name: string, options?: SpanOptions, context?: Context): Span;
538
+ /**
539
+ * Starts a new {@link Span} and calls the given function passing it the
540
+ * created span as first argument.
541
+ * Additionally the new span gets set in context and this context is activated
542
+ * for the duration of the function call.
543
+ *
544
+ * **Important**: The callback function is responsible for calling `span.end()`
545
+ * to finish the span. Unlike some other OpenTelemetry implementations, the span
546
+ * is NOT automatically ended when the callback returns. If `span.end()` is not
547
+ * called, the span will never be exported and will be silently lost.
548
+ *
549
+ * @param name The name of the span
550
+ * @param [options] SpanOptions used for span creation
551
+ * @param [context] Context to use to extract parent
552
+ * @param fn function called in the context of the span and receives the newly created span as an argument
553
+ * @returns return value of fn
554
+ * @example
555
+ * const something = tracer.startActiveSpan('op', span => {
556
+ * try {
557
+ * do some work
558
+ * span.setStatus({code: SpanStatusCode.OK});
559
+ * return something;
560
+ * } catch (err) {
561
+ * span.setStatus({
562
+ * code: SpanStatusCode.ERROR,
563
+ * message: err.message,
564
+ * });
565
+ * throw err;
566
+ * } finally {
567
+ * span.end();
568
+ * }
569
+ * });
570
+ *
571
+ * @example
572
+ * const span = tracer.startActiveSpan('op', span => {
573
+ * try {
574
+ * do some work
575
+ * return span;
576
+ * } catch (err) {
577
+ * span.setStatus({
578
+ * code: SpanStatusCode.ERROR,
579
+ * message: err.message,
580
+ * });
581
+ * throw err;
582
+ * }
583
+ * });
584
+ * do some more work
585
+ * span.end();
586
+ */
587
+ startActiveSpan<F extends (span: Span) => unknown>(name: string, fn: F): ReturnType<F>;
588
+ startActiveSpan<F extends (span: Span) => unknown>(name: string, options: SpanOptions, fn: F): ReturnType<F>;
589
+ startActiveSpan<F extends (span: Span) => unknown>(name: string, options: SpanOptions, context: Context, fn: F): ReturnType<F>;
590
+ }
591
+ /**
592
+ * The slice of a Lunora function `ctx` this bridge needs — the dispatch's span
593
+ * handle and the span factory.
594
+ *
595
+ * Structural rather than `QueryCtx`/`MutationCtx`/`ActionCtx` so one signature
596
+ * accepts all three (and a test double), while still being expressed in the real
597
+ * {@link SpanHandle} / {@link LunoraTracer} types now that this lives beside them.
598
+ */
599
+ interface LunoraTraceContext {
600
+ /** The dispatch's own span handle — supplies the trace this bridge joins. */
601
+ readonly span: SpanHandle;
602
+ /** The span factory: `ctx.trace(name, fn, options)`. */
603
+ readonly trace: LunoraTracer;
604
+ }
605
+ /** Options for {@link createOtelTracer}. */
606
+ interface OtelTracerOptions {
607
+ /**
608
+ * Prefix applied to every span name the bridge creates, e.g. `"ai."`.
609
+ *
610
+ * Useful when a third-party library emits generic names (`doGenerate`,
611
+ * `execute`) that would be ambiguous next to your own spans in a collector.
612
+ * Off by default — renaming someone else's spans breaks the dashboards their
613
+ * own documentation tells you to build.
614
+ */
615
+ namePrefix?: string;
616
+ }
617
+ /**
618
+ * Adapt a Lunora `ctx` into an `@opentelemetry/api` `Tracer`.
619
+ *
620
+ * Spans created through it are ordinary `ctx.trace` spans: they join the
621
+ * request's trace, appear in the studio waterfall, ride the same sampling
622
+ * decision, and export through the same OTLP sink. Nothing in the runtime has to
623
+ * know they came from a third-party library.
624
+ *
625
+ * **Parenting.** The parent is read from the `Context` the caller threads —
626
+ * `startSpan(name, options, ctx)` parents to `trace.getSpanContext(ctx)` when it
627
+ * names a span in THIS trace — and falls back to the dispatch when no Context is
628
+ * passed (or it carries a span from a different trace, which would be a lie to
629
+ * parent to). What the bridge does NOT do is track a dynamically scoped "current"
630
+ * span, because that needs `AsyncLocalStorage` — unavailable in the Durable
631
+ * Object profile (see the module doc). `startActiveSpan` therefore runs its
632
+ * callback with the new span passed in, exactly as the interface requires, but
633
+ * does NOT make it ambient: `trace.getActiveSpan()` inside that callback still
634
+ * reports whatever the global provider says. A library that threads its `Context`
635
+ * or the span it is handed (the common case, and what the AI SDK does) nests
636
+ * correctly; one that relies on ambient context gets a flat trace instead of a
637
+ * nested one — flatter, never wrong, never lost.
638
+ *
639
+ * **Ids and sampling.** The `SpanContext` returned by `startSpan` is the one the
640
+ * span is RECORDED under: the id is minted here and handed to `ctx.trace` as its
641
+ * span identity, so a `traceparent` a library builds from it names a span that
642
+ * actually reaches the collector. `traceFlags` carries the trace's settled
643
+ * sampling verdict rather than a hardcoded SAMPLED, so a sampled-out trace is not
644
+ * announced downstream as kept.
645
+ * @param context Any Lunora function context (`QueryCtx` / `MutationCtx` / `ActionCtx`).
646
+ * @param options See {@link OtelTracerOptions}.
647
+ */
648
+ declare const createOtelTracer: (context: LunoraTraceContext, options?: OtelTracerOptions) => Tracer;
649
+ export { type LunoraTraceContext, type OtelTracerOptions, createOtelTracer };
package/dist/otel.mjs ADDED
@@ -0,0 +1 @@
1
+ import{SpanKind as d,trace as l,TraceFlags as g,SpanStatusCode as k}from"@opentelemetry/api";const N=r=>{let t="";for(let e=0;e<r.length;e+=32768)t+=String.fromCharCode(...r.subarray(e,e+32768));return btoa(t)},R={[d.CLIENT]:"client",[d.CONSUMER]:"consumer",[d.INTERNAL]:"internal",[d.PRODUCER]:"producer",[d.SERVER]:"server"},C=r=>{const t=new Uint8Array(r);crypto.getRandomValues(t);let n="";for(const e of t)n+=e.toString(16).padStart(2,"0");return n},S=r=>r==null||typeof r=="boolean"||typeof r=="number"||typeof r=="string",p=(r,t)=>{if(typeof r=="bigint")return r.toString();if(r instanceof Uint8Array)return N(r);if(typeof r!="object"||r===null)return r;if(t.has(r))return"[Circular]";t.add(r);try{return Array.isArray(r)?r.map(n=>p(n,t)):typeof r.toJSON=="function"?r:Object.fromEntries(Object.entries(r).map(([n,e])=>[n,p(e,t)]))}finally{t.delete(r)}},w=r=>{if(S(r))return r;if(Array.isArray(r)&&r.every(t=>S(t)))return r.map(String).join(",");if(typeof r=="bigint"||r instanceof Uint8Array)return p(r,new Set);if(typeof r=="function"||typeof r=="symbol")return r.toString();try{return JSON.stringify(p(r,new Set))}catch{return"[unserializable]"}},c=r=>{const t={};for(const[n,e]of Object.entries(r??{}))e!==void 0&&(t[n]=w(e));return t};class x{ended=!1;finish;handle;ids;pending=[];thrown;constructor(t){this.ids=t}get failure(){return this.thrown}addEvent(t,n,e){return this.write(s=>{s.addEvent(t,c(n))}),this}addLink(t){return this.write(n=>{n.addLink({attributes:c(t.attributes),spanId:t.context.spanId,traceId:t.context.traceId})}),this}addLinks(t){for(const n of t)this.addLink(n);return this}attach(t,n){this.handle=t,this.finish=n;for(const e of this.pending)e(t);this.pending.length=0,this.ended&&n()}end(t){this.ended||(this.ended=!0,this.finish?.())}isRecording(){return!this.ended}recordException(t,n){this.write(e=>{if(t instanceof Error||typeof t=="string"){e.recordException(t);return}const s=new Error(t.message??String(t.code??"exception"));t.name!==void 0&&(s.name=t.name),t.stack!==void 0&&(s.stack=t.stack),e.recordException(s)})}setAttribute(t,n){return this.write(e=>{e.setAttribute(t,w(n))}),this}setAttributes(t){return this.write(n=>{n.setAttributes(c(t))}),this}setStatus(t){return t.code===k.ERROR&&(this.thrown=new Error(t.message??"span reported an error status")),this}spanContext(){return this.ids}updateName(t){return this.write(n=>{n.setAttribute("otel.updated_name",t)}),this}write(t){if(this.handle===void 0){this.pending.push(t);return}t(this.handle)}}const j=(r,t={})=>{const{namePrefix:n=""}=t,e=(s,i,f)=>{const o=r.span.spanContext(),h=f===void 0?void 0:l.getSpanContext(f),b=h?.traceId===o.traceId?h.spanId:o.spanId,y=C(8),E={spanId:y,traceFlags:o.sampled??!0?g.SAMPLED:g.NONE,traceId:o.traceId},u=new x(E);let m=()=>{};const I=new Promise(a=>{m=a});return r.trace(`${n}${s}`,async(a,A)=>{if(u.attach(A,m),await I,u.failure!==void 0)throw u.failure},{...i?.attributes===void 0?{}:{attributes:c(i.attributes)},...i?.kind===void 0?{}:{kind:R[i.kind]??"internal"},...i?.links===void 0?{}:{links:i.links.map(a=>({attributes:c(a.attributes),spanId:a.context.spanId,traceId:a.context.traceId}))}},{parentSpanId:b,spanId:y}).catch(()=>{}),u};return{startActiveSpan:(s,...i)=>{const f=i.at(-1),o=typeof i[0]=="object"&&i[0]!==null?i[0]:void 0,h=i.length>2?i[1]:void 0,b=e(s,o,h);return f(b)},startSpan:e}};export{j as createOtelTracer};
@@ -0,0 +1 @@
1
+ import{isLunoraError as O}from"@lunora/errors";import{v as d}from"@lunora/values";import{parseWire as U,encodeWire as D,stableWireKey as F}from"@lunora/wire";import{initLunora as S}from"./initLunora-DcvCGLL_.mjs";import{g as k,h as q,a as B}from"./plugin-CyLqvCB9.mjs";const P=3600*1e3,R=512*1024,H=8,b=64,V=64,K=256,W=4096,u="actionCache",h="entries",r=`${u}_${h}`,T=o=>o===void 0?"":F(o),x=async(o,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${o}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},$=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:G}=S.dataModel().create(),Z=(o={})=>{const m=o.ttlMs!==void 0&&Number.isFinite(o.ttlMs)?Math.max(1,Math.floor(o.ttlMs)):P,A=o.maxValueBytes!==void 0&&Number.isFinite(o.maxValueBytes)?Math.max(1,Math.floor(o.maxValueBytes)):R,y=async(e,t)=>{const n=(await e.db.query(r).withIndex("byExpiresAt").order("asc").take(H)).filter(s=>s.expiresAt<=t);await Promise.all(n.map(async s=>e.db.delete(r,s._id)))},C=async(e,t)=>e.db.query(r).withIndex("byKey",a=>a.eq("key",t)).first(),f=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),N=async(e,t,a)=>{try{await(t?e.db.patch(r,t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(r,a))}catch(n){if(O(n)&&f.has(n.code))return;throw n}},I=async(e,t,a,n)=>{const s=T(a),i=await x(t,s),l=Date.now(),c=await C(e,i);if(c&&c.expiresAt>l)return U(c.value).v;const p=await n(),w=JSON.stringify(D({v:p})),E=Date.now(),g=E+m;return new TextEncoder().encode(w).length<=A?await N(e,c,{expiresAt:g,key:i,name:t,value:w}):c&&await e.db.delete(r,c._id),await y(e,E),p},M=async(e,t,a)=>{const n=await x(t,T(a)),s=await e.db.query(r).withIndex("byKey",i=>i.eq("key",n)).take(b);await Promise.all(s.map(async i=>e.db.delete(r,i._id)))},_=async(e,t,a,n)=>{if(n>=V)return{complete:!1,deleted:a};const s=await e.db.query(r).withIndex("byName",i=>i.eq("name",t)).take(b);return s.length===0?{complete:!0,deleted:a}:(await Promise.all(s.map(async i=>e.db.delete(r,i._id))),_(e,t,a+s.length,n+1))},L=async(e,t)=>_(e,t,0,0),v=G.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(W,Math.max(1,Math.floor(e.limit))):K,i=(await t.db.query(r).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(i.map(async l=>t.db.delete(r,l._id))),{deleted:i.length}});return{...B(u,{extension:$,functions:{purgeExpired:v}}),invalidate:M,invalidateAll:L,wrap:I}};export{P as ACTION_CACHE_DEFAULT_TTL_MS,r as ACTION_CACHE_TABLE,$ as actionCacheExtension,x as cacheKeyFor,Z as defineActionCache};
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{optionalInner as h,v as o}from"@lunora/values";const A=25,S=100,w=100,L=8,O=new Set(["id","storage","string"]),f=t=>{const n=h(t)??t;if(O.has(n.kind))return!0;const r=n._meta;if(n.kind==="literal")return typeof r?.value=="string";if(n.kind!=="union"||r?.members===void 0)return!1;const{members:s}=r;return s.some(e=>f(e))&&s.every(e=>e.kind==="null"||f(e))},_=(t,n)=>{const r=s=>o.optional(o.array(s).check(e=>e.length<=n,{message:`at most ${String(n)} values`}));return o.object({...f(t)?{contains:o.optional(o.string())}:{},eq:o.optional(t),gt:o.optional(t),gte:o.optional(t),in:r(t),isNull:o.optional(o.boolean()),lt:o.optional(t),lte:o.optional(t),ne:o.optional(t),notIn:r(t)})},B=(t,n,r)=>t===void 0||!Number.isFinite(t)?Math.min(n,r):Math.min(Math.max(1,Math.floor(t)),r),p=(t,n)=>t===void 0||!Number.isFinite(t)?n:Math.max(1,Math.floor(t)),E=new Set(["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"]),M=(t,n,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))return;const s=t,e={};let l=0;for(const a of E){if(!Object.hasOwn(s,a)||(l+=1,a==="contains"&&!r))continue;const c=s[a];if(Array.isArray(c)&&c.length>n)throw new b("BAD_REQUEST",`list filter: \`${a}\` accepts at most ${String(n)} values (got ${String(c.length)})`);e[a]=c}return l===0?void 0:e},I=(t,n,r,s)=>{const e={};for(const l of n){if(!Object.hasOwn(t,l))continue;const a=t[l],c=M(a,s,r.has(l));c!==void 0&&Object.keys(c).length===0||(e[l]=c??a)}return e},F=()=>t=>{const n=p(t.defaultLimit,A),r=p(t.maxLimit,S),s=p(t.maxInValues,w),e=p(t.maxOrderBy,L),l=new Set(Object.keys(t.filter)),a=new Set,c={};for(const[i,d]of Object.entries(t.filter)){f(d)&&a.add(i);const u=h(d)===void 0?d:o.union(d,o.null());c[i]=o.optional(o.union(u,_(u,s)))}const g=new Set(t.orderBy),y=t.orderBy.length===0?o.string().check(()=>!1,{message:"no sortable columns are declared for this endpoint"}):o.union(...t.orderBy.map(i=>o.literal(i)));return{args:{cursor:o.optional(o.union(o.string(),o.number(),o.null())),limit:o.optional(o.number()),orderBy:o.optional(o.array(o.object({direction:o.optional(o.union(o.literal("asc"),o.literal("desc"))),field:y}))),where:o.optional(o.object(c))},toQueryArgs:i=>{const d=i.orderBy?.filter(m=>g.has(m.field)).slice(0,e).map(m=>({[m.field]:m.direction??"asc"})),u=i.where===void 0?void 0:I(i.where,l,a,s);return{...i.cursor===void 0?{}:{cursor:typeof i.cursor=="number"?String(i.cursor):i.cursor},limit:B(i.limit,n,r),...d===void 0||d.length===0?{}:{orderBy:d},...u===void 0?{}:{where:u}}}}};export{A as DEFAULT_LIMIT,S as DEFAULT_MAX_LIMIT,B as clampLimit,F as defineListArgs};
@@ -0,0 +1 @@
1
+ import{v as r}from"@lunora/values";import{parseWire as I,encodeWire as O}from"@lunora/wire";import{initLunora as x}from"./initLunora-DcvCGLL_.mjs";import{g as v,h as R,a as U}from"./plugin-CyLqvCB9.mjs";const H=2160*60*60*1e3,L=64*1024,y=200,q=1e3,C=64,F=512,u=16,g=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],b="documentHistory",T="versions",l=`${b}_${T}`,w=v(b,{tables:{[T]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:P,internalQuery:Y}=x.dataModel().create(),V=(d={})=>{const _=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,p=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,A=new Set([...B,...d.redact??[]]);let M=0;const D=()=>(M+=1,M),a=(e,t=0)=>{if(Array.isArray(e))return t>=u?void 0:e.map(o=>a(o,t+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return t>=u?void 0:new Map([...e.entries()].filter(([o])=>typeof o!="string"||!A.has(o)).map(([o,i])=>[o,a(i,t+1)]));if(e instanceof Set)return t>=u?void 0:new Set([...e].map(o=>a(o,t+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=u))return Object.fromEntries(Object.entries(e).filter(([o])=>!A.has(o)).map(([o,i])=>[o,a(i,t+1)]))},E=e=>{if(e===void 0)return;const t=JSON.stringify(O(a(e)));if(!(t.length>p))return 3*t.length<=p?t:new TextEncoder().encode(t).length>p?void 0:t},f=async(e,t)=>{const o=E(t.doc),i=E(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:D(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>f(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),h=Y.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):y,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,m)=>{for(const c of g){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:I(n.doc)},...n.previous===void 0?{}:{previous:I(n.previous)},...n.truncated===!0?{truncated:!0}:{}}))}),N=P.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-_,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(y,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(l,s._id))),n+=c.length}return{deleted:n}});return{...U(b,{extension:w,functions:{listForDocument:h,vacuum:N}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,w as documentHistoryExtension};