@safaricom-mxl/effect-sdk 0.0.15 → 0.0.16

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["stringOrUndefined","resolveEventsConfig","make","layer","uuidv7","EnvConfig.sdkDisabled","EnvConfig.endpoint","endpoint","EnvConfig.otlpHeaders","EnvConfig.serviceVersion","serviceVersion","EnvConfig.environment","environment","EnvConfig.otelServiceName","EnvConfig.otelResourceAttributes","layer","otelLayer","eventsLayer"],"sources":["../../src/shared/product-event.ts","../../src/version.ts","../../src/server/events.ts","../../src/server/otel-context-bridge.ts","../../src/server/otlp.ts","../../src/server/config.ts","../../src/server/platform.ts","../../src/server/resource.ts","../../src/server/layer.ts","../../src/shared/flush-core.ts","../../src/cloudflare/index.ts"],"sourcesContent":["export type ProductEventSource = \"server\" | \"browser\";\n\nexport const MAX_EVENT_NAME_LENGTH = 80;\nexport const RESERVED_EVENT_NAMES = [\"session_start\", \"session_end\"] as const;\n\nexport interface ProductEventLine {\n readonly attributes: Record<string, string>;\n readonly group_id: string;\n readonly name: string;\n readonly page_path: string;\n readonly service_name: string;\n readonly session_id: string;\n readonly source: ProductEventSource;\n readonly timestamp: string;\n readonly traceparent?: string | undefined;\n readonly url: string;\n readonly user_id: string;\n readonly visitor_id: string;\n}\n\nexport interface TrackProps {\n readonly [key: string]: unknown;\n}\n\nexport interface TrackOptions {\n readonly attributes?: TrackProps | undefined;\n readonly groupId?: string | undefined;\n readonly pagePath?: string | undefined;\n readonly sessionId?: string | undefined;\n readonly timestamp?: Date | number | undefined;\n readonly traceparent?: string | undefined;\n readonly url?: string | undefined;\n readonly userId?: string | undefined;\n readonly visitorId?: string | undefined;\n}\n\nconst isReservedEventName = (name: string): boolean =>\n RESERVED_EVENT_NAMES.some((reserved) => reserved === name);\n\nexport const coerceTrackProps = (\n props: TrackProps | undefined\n): Record<string, string> => {\n if (props === undefined) {\n return {};\n }\n const attributes: Record<string, string> = {};\n for (const [key, value] of Object.entries(props)) {\n if (value === undefined) {\n continue;\n }\n attributes[key] = typeof value === \"string\" ? value : String(value);\n }\n return attributes;\n};\n\nexport const toEventTimestamp = (value: Date | number | undefined): string =>\n (value instanceof Date ? value : new Date(value ?? Date.now())).toISOString();\n\nexport const encodeProductEventLine = (input: {\n readonly name: string;\n readonly options?: TrackOptions | undefined;\n readonly serviceName: string;\n readonly source: ProductEventSource;\n}): ProductEventLine | undefined => {\n const trimmed = typeof input.name === \"string\" ? input.name.trim() : \"\";\n if (trimmed.length === 0 || isReservedEventName(trimmed)) {\n return undefined;\n }\n const options = input.options ?? {};\n return {\n attributes: coerceTrackProps(options.attributes),\n group_id: options.groupId ?? \"\",\n name: trimmed.slice(0, MAX_EVENT_NAME_LENGTH),\n page_path: options.pagePath ?? \"\",\n service_name: input.serviceName,\n session_id: options.sessionId ?? \"\",\n source: input.source,\n timestamp: toEventTimestamp(options.timestamp),\n traceparent: options.traceparent,\n url: options.url ?? \"\",\n user_id: options.userId ?? \"\",\n visitor_id: options.visitorId ?? \"\",\n };\n};\n\nexport const encodeNdjson = (lines: ReadonlyArray<ProductEventLine>): string =>\n `${lines.map((line) => JSON.stringify(line)).join(\"\\n\")}\\n`;\n","export const SDK_NAME = \"mxl-effect-sdk\";\nexport const SDK_VERSION = \"0.0.15\";\n","import {\n Cause,\n Context,\n Duration,\n Effect,\n Layer,\n ManagedRuntime,\n Option,\n Schedule,\n Schema,\n Semaphore,\n} from \"effect\";\nimport { FetchHttpClient, HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\nimport {\n encodeNdjson,\n encodeProductEventLine,\n type ProductEventLine,\n type TrackOptions,\n} from \"../shared/product-event.js\";\nimport { SDK_NAME, SDK_VERSION } from \"../version.js\";\n\nexport type { TrackOptions } from \"../shared/product-event.js\";\n\nconst DEFAULT_FLUSH_INTERVAL = Duration.seconds(5);\nconst DEFAULT_MAX_BATCH_SIZE = 100;\nconst MAX_BUFFERED_EVENTS = 1_000;\nconst WARN_INTERVAL_MS = 30_000;\nconst DEFAULT_BASKET_URL = \"http://127.0.0.1:8000\";\n\nexport interface MxlEventsConfig {\n readonly apiKey?: string | undefined;\n readonly clientId?: string | undefined;\n readonly endpoint?: string | undefined;\n readonly eventsPath?: string | undefined;\n readonly flushInterval?: Duration.Input | undefined;\n readonly maxBatchSize?: number | undefined;\n readonly serviceName?: string | undefined;\n}\n\nexport interface MxlEventsApi {\n readonly flush: Effect.Effect<void>;\n readonly track: (name: string, options?: TrackOptions) => Effect.Effect<void>;\n}\n\nexport class MxlEvents extends Context.Service<MxlEvents, MxlEventsApi>()(\n \"@safaricom-mxl/effect-sdk/MxlEvents\"\n) {}\n\nexport class ProductEventsPostError extends Schema.TaggedError<ProductEventsPostError>()(\n \"@safaricom-mxl/effect-sdk/ProductEventsPostError\",\n {\n cause: Schema.optionalKey(Schema.Defect()),\n message: Schema.String,\n status: Schema.optionalKey(Schema.Number),\n }\n) {}\n\nconst stringOrUndefined = (value: string | undefined): string | undefined =>\n value && value.length > 0 ? value : undefined;\n\nconst resolveEventsConfig = (config: MxlEventsConfig) => {\n const endpoint = (\n config.endpoint ??\n process.env.MXL_BASKET_URL ??\n DEFAULT_BASKET_URL\n ).replace(/\\/$/, \"\");\n return {\n apiKey: stringOrUndefined(config.apiKey ?? process.env.MXL_API_KEY),\n clientId: stringOrUndefined(config.clientId ?? process.env.MXL_CLIENT_ID),\n serviceName:\n config.serviceName ?? process.env.OTEL_SERVICE_NAME ?? \"unknown\",\n url: `${endpoint}${config.eventsPath ?? \"/events\"}`,\n };\n};\n\nexport const make = Effect.fn(\"MxlEvents.make\")(function* (\n config: MxlEventsConfig = {}\n) {\n const resolved = resolveEventsConfig(config);\n const maxBatchSize = Math.max(1, config.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE);\n const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);\n const flushing = yield* Semaphore.make(1);\n\n let buffer: Array<ProductEventLine> = [];\n let warnedAboutName = false;\n let warnedAboutClient = false;\n let lastPostWarnAt = 0;\n\n const warnPost = (error: ProductEventsPostError): void => {\n const now = Date.now();\n if (now - lastPostWarnAt < WARN_INTERVAL_MS) return;\n lastPostWarnAt = now;\n console.warn(`[MxlEvents] ${error.message} (dropping batch)`, error.cause ?? \"\");\n };\n const warnMissingClient = (): void => {\n if (warnedAboutClient) return;\n warnedAboutClient = true;\n console.warn(\n \"[MxlEvents] no client id — set MXL_CLIENT_ID or pass `clientId`; dropping events\"\n );\n };\n const warnEmptyName = (): void => {\n if (warnedAboutName) return;\n warnedAboutName = true;\n console.warn(\"[MxlEvents] track() needs a non-empty event name; the call was ignored.\");\n };\n\n const post = (lines: ReadonlyArray<ProductEventLine>) => {\n const headers: Record<string, string> = {\n \"mxl-client-id\": resolved.clientId ?? \"\",\n \"mxl-sdk-name\": SDK_NAME,\n \"mxl-sdk-version\": SDK_VERSION,\n \"user-agent\": `${SDK_NAME}-server/${SDK_VERSION}`,\n };\n if (resolved.apiKey) {\n headers[\"mxl-api-key\"] = resolved.apiKey;\n }\n return HttpClientRequest.post(resolved.url).pipe(\n HttpClientRequest.setHeaders(headers),\n HttpClientRequest.bodyText(encodeNdjson(lines), \"application/x-ndjson\"),\n client.execute,\n Effect.asVoid,\n Effect.mapError((error) =>\n error.response !== undefined\n ? new ProductEventsPostError({\n message: `POST ${resolved.url} → ${error.response.status}`,\n status: error.response.status,\n })\n : new ProductEventsPostError({\n cause: error,\n message: `POST ${resolved.url} failed: ${error.message}`,\n })\n )\n );\n };\n\n const flush: Effect.Effect<void> = flushing.withPermits(1)(\n Effect.suspend(() => {\n if (buffer.length === 0) return Effect.void;\n const batch = buffer;\n buffer = [];\n if (resolved.clientId === undefined) {\n warnMissingClient();\n return Effect.void;\n }\n return post(batch).pipe(\n Effect.catchCause((cause) =>\n Effect.sync(() => {\n warnPost(\n Option.getOrElse(Cause.findErrorOption(cause), () =>\n new ProductEventsPostError({\n cause: Cause.squash(cause),\n message: `POST ${resolved.url} failed`,\n })\n )\n );\n })\n )\n );\n })\n );\n\n const track = (name: string, options: TrackOptions = {}): Effect.Effect<void> =>\n Effect.sync(() => {\n const line = encodeProductEventLine({\n name,\n options,\n serviceName: resolved.serviceName,\n source: \"server\",\n });\n if (line === undefined) {\n warnEmptyName();\n return false;\n }\n buffer.push(line);\n if (buffer.length > MAX_BUFFERED_EVENTS) {\n buffer.splice(0, buffer.length - MAX_BUFFERED_EVENTS);\n }\n return buffer.length >= maxBatchSize;\n }).pipe(\n Effect.flatMap((full) => (full ? Effect.forkDetach(flush) : Effect.void)),\n Effect.asVoid\n );\n\n const interval = config.flushInterval ?? DEFAULT_FLUSH_INTERVAL;\n if (Duration.toMillis(interval) > 0) {\n yield* Effect.forkScoped(flush.pipe(Effect.schedule(Schedule.spaced(interval))));\n }\n yield* Effect.addFinalizer(() => flush);\n\n return { flush, track } satisfies MxlEventsApi;\n});\n\nexport const layer = (config: MxlEventsConfig = {}): Layer.Layer<MxlEvents> =>\n Layer.effect(MxlEvents, make(config)).pipe(Layer.provide(FetchHttpClient.layer));\n\nexport interface MxlEventsHandle {\n readonly dispose: () => Promise<void>;\n readonly flush: () => Promise<void>;\n readonly track: (name: string, options?: TrackOptions) => void;\n}\n\nexport const makeHandle = (config: MxlEventsConfig = {}): MxlEventsHandle => {\n const runtime = ManagedRuntime.make(layer(config));\n const swallow = (promise: Promise<unknown>): Promise<void> =>\n promise.then(\n () => undefined,\n () => undefined\n );\n return {\n dispose: () => swallow(runtime.dispose()),\n flush: () =>\n swallow(\n runtime.runPromise(\n Effect.gen(function* () {\n const events = yield* MxlEvents;\n yield* events.flush;\n })\n )\n ),\n track: (name, options) => {\n void swallow(\n runtime.runPromise(\n Effect.gen(function* () {\n const events = yield* MxlEvents;\n yield* events.track(name, options);\n })\n )\n );\n },\n };\n};\n","import * as Otel from \"@opentelemetry/api\";\nimport { Effect, Layer } from \"effect\";\nimport * as Tracer from \"effect/Tracer\";\n\nconst OTEL_SPAN_TYPE_ID = \"~@effect/opentelemetry/OtelTracer/OtelSpan\";\nconst evaluate = \"~effect/Effect/evaluate\" as const;\n\ninterface OtelWrappedSpan {\n readonly span: Otel.Span;\n}\n\nexport function formatTraceparent(span: Tracer.AnySpan): string {\n const flags = span.sampled ? \"01\" : \"00\";\n return `00-${span.traceId}-${span.spanId}-${flags}`;\n}\n\nexport function buildTraceCarrierFromSpan(\n span: Tracer.AnySpan,\n headers?: Record<string, string>\n): Record<string, string> {\n const carrier: Record<string, string> = {\n traceparent: formatTraceparent(span),\n };\n\n if (headers?.tracestate) {\n carrier.tracestate = headers.tracestate;\n }\n if (headers?.baggage) {\n carrier.baggage = headers.baggage;\n }\n\n return carrier;\n}\n\n/** Map an Effect span to an OpenTelemetry context with the span active. */\nexport function effectSpanToOtelContext(\n activeContext: Otel.Context,\n span: Tracer.AnySpan\n): Otel.Context {\n if (\n typeof span === \"object\" &&\n span !== null &&\n OTEL_SPAN_TYPE_ID in span &&\n \"span\" in span\n ) {\n return Otel.trace.setSpan(activeContext, (span as OtelWrappedSpan).span);\n }\n\n return Otel.trace.setSpanContext(activeContext, {\n isRemote: span._tag === \"ExternalSpan\",\n spanId: span.spanId,\n traceFlags: span.sampled ? Otel.TraceFlags.SAMPLED : Otel.TraceFlags.NONE,\n traceId: span.traceId,\n });\n}\n\n/** Wrap a tracer so Effect spans activate global `@opentelemetry/api` context. */\nexport function wrapTracerWithOtelContextBridge(\n base: Tracer.Tracer\n): Tracer.Tracer {\n const existingContext = base.context;\n\n return Tracer.make({\n span(options) {\n return base.span(options);\n },\n context(primitive, fiber) {\n if (fiber.cache.span === undefined) {\n if (existingContext) {\n return existingContext(primitive, fiber);\n }\n return primitive[evaluate](fiber);\n }\n\n return Otel.context.with(\n effectSpanToOtelContext(Otel.context.active(), fiber.cache.span),\n () => {\n if (existingContext) {\n return existingContext(primitive, fiber);\n }\n return primitive[evaluate](fiber);\n }\n );\n },\n });\n}\n\n/**\n * Layer that wraps the configured Effect tracer with a global OTel context bridge.\n *\n * Must be merged after `Otlp.layerJson` so queue propagation, log correlation,\n * and outbound W3C headers see the active server span.\n */\nexport const otelGlobalContextBridgeLayer = Layer.effect(\n Tracer.Tracer,\n Effect.gen(function* () {\n const base = yield* Tracer.Tracer;\n return wrapTracerWithOtelContextBridge(base);\n })\n);\n","export function normalizeOtlpBaseUrl(url: string): string {\n const trimmed = url.replace(/\\/$/, \"\");\n if (trimmed.endsWith(\"/v1/traces\") || trimmed.endsWith(\"/v1/logs\")) {\n return trimmed.replace(/\\/v1\\/(traces|logs|metrics)$/, \"\");\n }\n return trimmed;\n}\n","import { Config, Effect, Option } from \"effect\";\n\nconst DEFAULT_OTLP_ENDPOINT = \"http://127.0.0.1:4318\";\n\n/** Resolve the OTLP exporter endpoint from standard env vars. */\nexport const endpoint = Effect.gen(function* () {\n const otlp = yield* Config.option(\n Config.String(\"OTEL_EXPORTER_OTLP_ENDPOINT\")\n );\n if (Option.isSome(otlp)) return otlp;\n return yield* Config.option(Config.String(\"OTLP_ENDPOINT\"));\n});\n\nexport const defaultOtlpEndpoint = DEFAULT_OTLP_ENDPOINT;\n\nexport const sdkDisabled = Config.Boolean(\"OTEL_SDK_DISABLED\").pipe(\n Config.withDefault(false)\n);\n\n/**\n * Resolve service version / commit SHA from platform-specific env vars.\n *\n * Priority: npm_package_version > COMMIT_SHA > RAILWAY_GIT_COMMIT_SHA >\n * VERCEL_GIT_COMMIT_SHA > CF_PAGES_COMMIT_SHA > RENDER_GIT_COMMIT\n */\nexport const serviceVersion = Config.option(\n Config.String(\"npm_package_version\").pipe(\n Config.orElse(() => Config.String(\"COMMIT_SHA\")),\n Config.orElse(() => Config.String(\"RAILWAY_GIT_COMMIT_SHA\")),\n Config.orElse(() => Config.String(\"VERCEL_GIT_COMMIT_SHA\")),\n Config.orElse(() => Config.String(\"CF_PAGES_COMMIT_SHA\")),\n Config.orElse(() => Config.String(\"RENDER_GIT_COMMIT\"))\n )\n);\n\n/**\n * Resolve deployment environment from env vars.\n *\n * Priority: NODE_ENV > DEPLOYMENT_ENV > \"development\"\n */\nexport const environment = Config.String(\"NODE_ENV\").pipe(\n Config.orElse(() => Config.String(\"DEPLOYMENT_ENV\")),\n Config.withDefault(\"development\")\n);\n\n/** OTel-standard service name override. */\nexport const otelServiceName = Config.option(\n Config.String(\"OTEL_SERVICE_NAME\")\n);\n\n/**\n * Parse the OTel-standard `OTEL_RESOURCE_ATTRIBUTES` env var.\n *\n * Format per the OTel spec: comma-separated `key=value` pairs, values may be\n * URL-encoded.\n */\nexport const parseOtelResourceAttributes = (\n input: string\n): Record<string, string> => {\n const result: Record<string, string> = {};\n for (const pair of input.split(\",\")) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) continue;\n const key = pair.slice(0, eq).trim();\n if (!key) continue;\n const raw = pair.slice(eq + 1).trim();\n let value = raw;\n try {\n value = decodeURIComponent(raw);\n } catch {\n // Fall back to raw string when decoding fails.\n }\n result[key] = value;\n }\n return result;\n};\n\n/** Resolve and parse `OTEL_RESOURCE_ATTRIBUTES`. */\nexport const otelResourceAttributes = Effect.gen(function* () {\n const raw = yield* Config.option(Config.String(\"OTEL_RESOURCE_ATTRIBUTES\"));\n return Option.match(raw, {\n onNone: () => ({}) as Record<string, string>,\n onSome: (value) => parseOtelResourceAttributes(value),\n });\n});\n\n/**\n * Parse `OTEL_EXPORTER_OTLP_HEADERS` (`key=value,key2=value2`) into a header map.\n */\nexport const parseOtlpHeaders = (input: string): Record<string, string> => {\n const result: Record<string, string> = {};\n for (const pair of input.split(\",\")) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) continue;\n const key = pair.slice(0, eq).trim();\n if (!key) continue;\n const raw = pair.slice(eq + 1).trim();\n try {\n result[key] = decodeURIComponent(raw);\n } catch {\n result[key] = raw;\n }\n }\n return result;\n};\n\n/** Resolve OTLP export headers from env. */\nexport const otlpHeaders = Effect.gen(function* () {\n const raw = yield* Config.option(Config.String(\"OTEL_EXPORTER_OTLP_HEADERS\"));\n return Option.match(raw, {\n onNone: () => ({}) as Record<string, string>,\n onSome: (value) => parseOtlpHeaders(value),\n });\n});\n","import { Match } from \"effect\";\nimport { platform, provider, runtime } from \"std-env\";\n\nexport interface PlatformInputs {\n readonly runtime: string;\n readonly provider: string;\n readonly platform: string;\n readonly arch: string;\n readonly env: Readonly<Record<string, string | undefined>>;\n}\n\ntype Attrs = Record<string, string>;\nconst empty: Attrs = {};\n\nconst runtimeAttrs = (rt: string): Attrs =>\n Match.value(rt).pipe(\n Match.when(\"node\", () => ({ \"process.runtime.name\": \"nodejs\" })),\n Match.whenOr(\"bun\", \"deno\", \"workerd\", \"edge-light\", \"fastly\", (name) => ({\n \"process.runtime.name\": name,\n })),\n Match.orElse((): Attrs => empty)\n );\n\nconst osAttrs = (plat: string): Attrs =>\n Match.value(plat).pipe(\n Match.when(\"win32\", () => ({ \"os.type\": \"windows\" })),\n Match.whenOr(\"darwin\", \"linux\", \"freebsd\", \"openbsd\", \"netbsd\", (p) => ({\n \"os.type\": p,\n })),\n Match.orElse((): Attrs => empty)\n );\n\nconst archAttrs = (a: string): Attrs =>\n a === \"\"\n ? empty\n : {\n \"host.arch\": Match.value(a).pipe(\n Match.when(\"x64\", () => \"amd64\"),\n Match.when(\"ia32\", () => \"x86\"),\n Match.orElse((other) => other)\n ),\n };\n\nconst lambdaAttrs = (env: PlatformInputs[\"env\"]): Attrs => ({\n \"cloud.provider\": \"aws\",\n \"cloud.platform\": \"aws_lambda\",\n \"faas.name\": env.AWS_LAMBDA_FUNCTION_NAME!,\n ...(env.AWS_LAMBDA_FUNCTION_VERSION && {\n \"faas.version\": env.AWS_LAMBDA_FUNCTION_VERSION,\n }),\n ...(env.AWS_LAMBDA_LOG_STREAM_NAME && {\n \"faas.instance\": env.AWS_LAMBDA_LOG_STREAM_NAME,\n }),\n ...(env.AWS_REGION\n ? { \"cloud.region\": env.AWS_REGION }\n : env.AWS_DEFAULT_REGION\n ? { \"cloud.region\": env.AWS_DEFAULT_REGION }\n : {}),\n});\n\nconst providerAttrs = (prov: string, env: PlatformInputs[\"env\"]): Attrs =>\n Match.value(prov).pipe(\n Match.when(\"cloudflare_workers\", (): Attrs => ({\n \"cloud.provider\": \"cloudflare\",\n \"cloud.platform\": \"cloudflare.workers\",\n })),\n Match.when(\"cloudflare_pages\", (): Attrs => ({\n \"cloud.provider\": \"cloudflare\",\n \"cloud.platform\": \"cloudflare.pages\",\n })),\n Match.when(\"vercel\", (): Attrs => ({\n \"cloud.provider\": \"vercel\",\n \"cloud.platform\": \"vercel\",\n ...(env.VERCEL_REGION && { \"cloud.region\": env.VERCEL_REGION }),\n ...(env.VERCEL_DEPLOYMENT_ID && {\n \"faas.instance\": env.VERCEL_DEPLOYMENT_ID,\n }),\n })),\n Match.when(\"netlify\", (): Attrs => ({\n \"cloud.provider\": \"netlify\",\n \"cloud.platform\": \"netlify\",\n })),\n Match.whenOr(\"google_cloudrun\", \"google_cloudrun_job\", (): Attrs => ({\n \"cloud.provider\": \"gcp\",\n \"cloud.platform\": \"gcp_cloud_run\",\n ...(env.K_SERVICE && { \"faas.name\": env.K_SERVICE }),\n ...(env.K_REVISION && { \"faas.version\": env.K_REVISION }),\n ...(env.CLOUD_RUN_REGION && { \"cloud.region\": env.CLOUD_RUN_REGION }),\n })),\n Match.when(\"firebase_app_hosting\", (): Attrs => ({\n \"cloud.provider\": \"gcp\",\n \"cloud.platform\": \"gcp_firebase_app_hosting\",\n })),\n Match.when(\"aws_amplify\", (): Attrs => ({\n \"cloud.provider\": \"aws\",\n \"cloud.platform\": \"aws_amplify\",\n })),\n Match.when(\"deno-deploy\", (): Attrs => ({\n \"cloud.provider\": \"deno\",\n \"cloud.platform\": \"deno_deploy\",\n ...(env.DENO_REGION && { \"cloud.region\": env.DENO_REGION }),\n ...(env.DENO_DEPLOYMENT_ID && {\n \"faas.instance\": env.DENO_DEPLOYMENT_ID,\n }),\n })),\n Match.when(\"render\", (): Attrs => ({\n \"cloud.provider\": \"render\",\n \"cloud.platform\": \"render\",\n ...(env.RENDER_INSTANCE_ID && {\n \"faas.instance\": env.RENDER_INSTANCE_ID,\n }),\n })),\n Match.when(\"railway\", (): Attrs => ({\n \"cloud.provider\": \"railway\",\n \"cloud.platform\": \"railway\",\n ...(env.RAILWAY_REPLICA_ID && {\n \"faas.instance\": env.RAILWAY_REPLICA_ID,\n }),\n })),\n Match.when(\"edgeone_pages\", (): Attrs => ({\n \"cloud.provider\": \"tencent_cloud\",\n \"cloud.platform\": \"tencent_edgeone_pages\",\n })),\n Match.orElse((): Attrs => empty)\n );\n\nconst workerdFallback = (rt: string, alreadyResolved: boolean): Attrs =>\n rt === \"workerd\" && !alreadyResolved\n ? {\n \"cloud.provider\": \"cloudflare\",\n \"cloud.platform\": \"cloudflare.workers\",\n }\n : empty;\n\nconst vercelEdgeFallback = (\n rt: string,\n alreadyResolved: boolean,\n env: PlatformInputs[\"env\"]\n): Attrs =>\n rt === \"edge-light\" && !alreadyResolved && env.VERCEL\n ? { \"cloud.provider\": \"vercel\", \"cloud.platform\": \"vercel\" }\n : empty;\n\nexport const derivePlatformAttributes = (\n inputs: PlatformInputs\n): PlatformAttributes => {\n const { runtime: rt, provider: prov, platform: plat, arch, env } = inputs;\n\n const cloudAttrs = env.AWS_LAMBDA_FUNCTION_NAME\n ? lambdaAttrs(env)\n : providerAttrs(prov, env);\n const cloudResolved = \"cloud.provider\" in cloudAttrs;\n\n return {\n ...(rt && { \"mxl.runtime\": rt }),\n ...(prov && { \"mxl.provider\": prov }),\n ...runtimeAttrs(rt),\n ...osAttrs(plat),\n ...archAttrs(arch),\n ...cloudAttrs,\n ...workerdFallback(rt, cloudResolved),\n ...vercelEdgeFallback(rt, cloudResolved, env),\n };\n};\n\nexport type PlatformAttributes = Attrs;\n\nconst PLATFORM_ENV_KEYS = [\n \"AWS_LAMBDA_FUNCTION_NAME\",\n \"AWS_LAMBDA_FUNCTION_VERSION\",\n \"AWS_LAMBDA_LOG_STREAM_NAME\",\n \"AWS_REGION\",\n \"AWS_DEFAULT_REGION\",\n \"VERCEL\",\n \"VERCEL_REGION\",\n \"VERCEL_DEPLOYMENT_ID\",\n \"K_SERVICE\",\n \"K_REVISION\",\n \"CLOUD_RUN_REGION\",\n \"DENO_REGION\",\n \"DENO_DEPLOYMENT_ID\",\n \"RENDER_INSTANCE_ID\",\n \"RAILWAY_REPLICA_ID\",\n] as const;\n\nexport const getAutoPlatformAttributes = (): PlatformAttributes => {\n const proc = (\n globalThis as { process?: { env?: Record<string, string>; arch?: string } }\n ).process;\n const procEnv = proc?.env ?? {};\n const env: Record<string, string | undefined> = {};\n for (const key of PLATFORM_ENV_KEYS) env[key] = procEnv[key];\n\n return derivePlatformAttributes({\n runtime: runtime ?? \"\",\n provider: provider ?? \"\",\n platform: platform ?? \"\",\n arch: proc?.arch ?? \"\",\n env,\n });\n};\n","import { v7 as uuidv7 } from \"uuid\";\nimport { Effect, Option } from \"effect\";\n\nimport * as EnvConfig from \"./config.js\";\nimport { getAutoPlatformAttributes } from \"./platform.js\";\n\nconst stringOrUndefined = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\nconst DEFAULT_VCS_REPOSITORY_URL =\n \"https://gitlab.safaricom.co.ke/mxl/apm/mxl-effect-sdk\";\n\nfunction resolveCommitRevision(): string | undefined {\n return (\n stringOrUndefined(process.env.COMMIT_SHA) ??\n stringOrUndefined(process.env.VERCEL_GIT_COMMIT_SHA) ??\n stringOrUndefined(process.env.GITHUB_SHA) ??\n stringOrUndefined(process.env.RAILWAY_GIT_COMMIT_SHA) ??\n stringOrUndefined(process.env.CF_PAGES_COMMIT_SHA) ??\n stringOrUndefined(process.env.RENDER_GIT_COMMIT)\n );\n}\n\nlet serviceInstanceId: string | undefined;\nconst getServiceInstanceId = (): string => (serviceInstanceId ??= uuidv7());\n\nexport interface ResourceConfigInput {\n readonly serviceName?: string | undefined;\n readonly serviceVersion?: string | undefined;\n readonly environment?: string | undefined;\n readonly endpoint?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly attributes?: Record<string, string> | undefined;\n readonly sdkType?: \"server\" | undefined;\n}\n\nexport interface ResolvedResource {\n readonly endpoint: string | undefined;\n readonly headers: Record<string, string> | undefined;\n readonly resource: {\n readonly serviceName: string;\n readonly serviceVersion: string | undefined;\n readonly attributes: Record<string, string>;\n };\n readonly environment: string | undefined;\n}\n\nexport const resolveResource = (\n config: ResourceConfigInput\n): Effect.Effect<ResolvedResource> =>\n Effect.gen(function* () {\n const disabled = yield* EnvConfig.sdkDisabled;\n if (disabled) {\n return {\n endpoint: undefined,\n environment: undefined,\n headers: undefined,\n resource: {\n attributes: {},\n serviceName: config.serviceName ?? \"unknown\",\n serviceVersion: undefined,\n },\n } satisfies ResolvedResource;\n }\n\n const envEndpoint = yield* EnvConfig.endpoint;\n const endpoint =\n config.endpoint ??\n Option.getOrUndefined(envEndpoint) ??\n EnvConfig.defaultOtlpEndpoint;\n\n const envHeaders = yield* EnvConfig.otlpHeaders;\n const headers =\n config.headers && Object.keys(config.headers).length > 0\n ? config.headers\n : Object.keys(envHeaders).length > 0\n ? envHeaders\n : undefined;\n\n const envServiceVersion = yield* EnvConfig.serviceVersion;\n const serviceVersion =\n config.serviceVersion ?? Option.getOrUndefined(envServiceVersion);\n\n const envEnvironment = yield* EnvConfig.environment;\n const environment = config.environment ?? envEnvironment;\n\n const envOtelServiceName = yield* EnvConfig.otelServiceName;\n const serviceName =\n config.serviceName ??\n Option.getOrUndefined(envOtelServiceName) ??\n \"unknown\";\n\n const envResourceAttributes = yield* EnvConfig.otelResourceAttributes;\n\n const attributes: Record<string, string> = {};\n Object.assign(attributes, getAutoPlatformAttributes());\n attributes[\"mxl.sdk.type\"] = config.sdkType ?? \"server\";\n attributes[\"service.instance.id\"] = getServiceInstanceId();\n if (environment) {\n attributes[\"deployment.environment\"] = environment;\n attributes[\"deployment.environment.name\"] = environment;\n }\n if (serviceVersion) {\n attributes[\"service.version\"] = serviceVersion;\n }\n const commitRevision = resolveCommitRevision();\n if (commitRevision) {\n attributes[\"deployment.commit_sha\"] = commitRevision;\n attributes[\"vcs.ref.head.revision\"] = commitRevision;\n }\n attributes[\"vcs.repository.url.full\"] =\n stringOrUndefined(process.env.MXL_VCS_REPOSITORY_URL) ??\n DEFAULT_VCS_REPOSITORY_URL;\n Object.assign(attributes, envResourceAttributes);\n if (config.attributes) Object.assign(attributes, config.attributes);\n\n return {\n endpoint,\n environment,\n headers,\n resource: { serviceName, serviceVersion, attributes },\n } satisfies ResolvedResource;\n }).pipe(Effect.orDie);\n","import type { Duration } from \"effect\";\nimport { Effect, Layer } from \"effect\";\nimport * as Tracer from \"effect/Tracer\";\nimport { FetchHttpClient } from \"effect/unstable/http\";\nimport { Otlp } from \"effect/unstable/observability\";\n\nimport { wrapTracerWithOtelContextBridge } from \"./otel-context-bridge.js\";\nimport { normalizeOtlpBaseUrl } from \"./otlp.js\";\nimport { resolveResource } from \"./resource.js\";\n\nexport interface MxlConfig {\n readonly serviceName?: string | undefined;\n readonly serviceVersion?: string | undefined;\n readonly environment?: string | undefined;\n readonly endpoint?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly attributes?: Record<string, string> | undefined;\n readonly maxBatchSize?: number | undefined;\n readonly loggerExportInterval?: Duration.Input | undefined;\n readonly metricsExportInterval?: Duration.Input | undefined;\n readonly tracerExportInterval?: Duration.Input | undefined;\n readonly shutdownTimeout?: Duration.Input | undefined;\n}\n\n/**\n * Create an Effect Layer that provides OpenTelemetry traces, logs, and metrics\n * configured for MXL's OTLP collector.\n *\n * Returns a no-op layer when `OTEL_SDK_DISABLED=true`.\n */\nexport const layer = (config: MxlConfig = {}) =>\n Layer.unwrap(\n Effect.gen(function* () {\n const resolved = yield* resolveResource({ ...config, sdkType: \"server\" });\n if (!resolved.endpoint) return Layer.empty;\n\n return Otlp.layerJson({\n baseUrl: normalizeOtlpBaseUrl(resolved.endpoint),\n headers: resolved.headers,\n resource: resolved.resource,\n maxBatchSize: config.maxBatchSize,\n loggerExportInterval: config.loggerExportInterval,\n metricsExportInterval: config.metricsExportInterval,\n tracerExportInterval: config.tracerExportInterval,\n shutdownTimeout: config.shutdownTimeout,\n }).pipe(Layer.provide(FetchHttpClient.layer));\n })\n ).pipe(Layer.updateService(Tracer.Tracer, wrapTracerWithOtelContextBridge));\n","export interface SignalState {\n disabledUntil: number;\n}\n\nexport const COOLDOWN_MS = 60_000;\n\nexport const makeSerializedFlush = <Args extends unknown[]>(\n flush: (...args: Args) => Promise<void>\n): ((...args: Args) => Promise<void>) => {\n let pending: Promise<void> = Promise.resolve();\n return (...args: Args) => {\n pending = pending.then(\n () => flush(...args),\n () => flush(...args)\n );\n return pending;\n };\n};\n\nexport const guardFlush = <Args extends unknown[]>(\n prefix: string,\n flush: (...args: Args) => Promise<void>,\n state?: SignalState\n): ((...args: Args) => Promise<void>) => {\n return async (...args: Args) => {\n if (state && Date.now() < state.disabledUntil) {\n return;\n }\n try {\n await flush(...args);\n } catch (error) {\n if (state) {\n state.disabledUntil = Date.now() + COOLDOWN_MS;\n }\n console.error(`${prefix} flush failed; cooling down 60s`, error);\n }\n };\n};\n\nexport const fetchTransport = async (input: {\n readonly body: string | Uint8Array;\n readonly headers: Record<string, string>;\n readonly keepalive?: boolean | undefined;\n readonly url: string;\n}): Promise<void> => {\n const response = await fetch(input.url, {\n body: input.body,\n headers: input.headers,\n keepalive: input.keepalive,\n method: \"POST\",\n });\n if (!response.ok) {\n throw new Error(`POST ${input.url} → ${response.status}`);\n }\n};\n","import { Context, Effect, Layer } from \"effect\";\n\nimport {\n type MxlEventsConfig,\n type MxlEventsHandle,\n layer as eventsLayer,\n makeHandle,\n} from \"../server/events.js\";\nimport { layer as otelLayer } from \"../server/layer.js\";\nimport { guardFlush, makeSerializedFlush } from \"../shared/flush-core.js\";\n\nexport interface Config {\n readonly apiKey?: string | undefined;\n readonly attributes?: Record<string, unknown> | undefined;\n readonly clientId?: string | undefined;\n readonly endpoint?: string | undefined;\n readonly environment?: string | undefined;\n readonly ingestUrl?: string | undefined;\n readonly serviceName?: string | undefined;\n readonly serviceVersion?: string | undefined;\n}\n\nexport class WorkerEnvironment extends Context.Service<\n WorkerEnvironment,\n Record<string, unknown>\n>()(\"Cloudflare.Workers.WorkerEnvironment\") {}\n\nexport interface Telemetry {\n readonly flush: (env: Record<string, unknown>) => Promise<void>;\n readonly layer: Layer.Layer<never>;\n readonly requestLayer: Layer.Layer<never, never, WorkerEnvironment>;\n}\n\nconst stringFromEnv = (\n env: Record<string, unknown>,\n key: string\n): string | undefined => {\n const value = env[key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n};\n\nconst resolveEventsConfig = (\n env: Record<string, unknown>,\n config: Config\n): MxlEventsConfig => ({\n apiKey: config.apiKey ?? stringFromEnv(env, \"MXL_API_KEY\"),\n clientId: config.clientId ?? stringFromEnv(env, \"MXL_CLIENT_ID\"),\n endpoint:\n config.ingestUrl ?? stringFromEnv(env, \"MXL_BASKET_URL\") ?? undefined,\n flushInterval: 0,\n serviceName:\n config.serviceName ?? stringFromEnv(env, \"OTEL_SERVICE_NAME\") ?? \"unknown\",\n});\n\nexport const make = (config: Config = {}): Telemetry => {\n let handle: MxlEventsHandle | undefined;\n const state = { disabledUntil: 0 };\n\n const flush = makeSerializedFlush(\n guardFlush(\n \"[MxlCloudflareSDK]\",\n async (env: Record<string, unknown>): Promise<void> => {\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n const eventsConfig = resolveEventsConfig(env, config);\n if (!eventsConfig.clientId) {\n return;\n }\n handle ??= makeHandle(eventsConfig);\n await handle.flush();\n },\n state\n )\n );\n\n const layer = otelLayer({\n attributes: Object.fromEntries(\n Object.entries(config.attributes ?? {}).map(([key, value]) => [\n key,\n String(value),\n ])\n ),\n endpoint: config.endpoint,\n environment: config.environment,\n serviceName: config.serviceName,\n serviceVersion: config.serviceVersion,\n });\n\n const requestLayer = Layer.mergeAll(\n layer,\n Layer.unwrap(\n Effect.gen(function* () {\n const env = yield* WorkerEnvironment;\n const eventsConfig = resolveEventsConfig(env, config);\n if (!eventsConfig.clientId) {\n return Layer.empty;\n }\n return eventsLayer(eventsConfig);\n })\n ),\n Layer.effectDiscard(\n Effect.gen(function* () {\n const env = yield* WorkerEnvironment;\n yield* Effect.addFinalizer(() => Effect.promise(() => flush(env)));\n })\n )\n );\n\n return {\n flush,\n layer,\n requestLayer,\n };\n};\n\nexport const MxlCloudflareSDK = { make };\n"],"mappings":";;;;;;;AAGA,MAAa,uBAAuB,CAAC,iBAAiB,aAAa;AAiCnE,MAAM,uBAAuB,SAC3B,qBAAqB,MAAM,aAAa,aAAa,IAAI;AAE3D,MAAa,oBACX,UAC2B;CAC3B,IAAI,UAAU,KAAA,GACZ,OAAO,CAAC;CAEV,MAAM,aAAqC,CAAC;CAC5C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,GAAG;EAChD,IAAI,UAAU,KAAA,GACZ;EAEF,WAAW,OAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,KAAK;CACpE;CACA,OAAO;AACT;AAEA,MAAa,oBAAoB,WAC9B,iBAAiB,OAAO,QAAQ,IAAI,KAAK,SAAS,KAAK,IAAI,CAAC,EAAA,CAAG,YAAY;AAE9E,MAAa,0BAA0B,UAKH;CAClC,MAAM,UAAU,OAAO,MAAM,SAAS,WAAW,MAAM,KAAK,KAAK,IAAI;CACrE,IAAI,QAAQ,WAAW,KAAK,oBAAoB,OAAO,GACrD;CAEF,MAAM,UAAU,MAAM,WAAW,CAAC;CAClC,OAAO;EACL,YAAY,iBAAiB,QAAQ,UAAU;EAC/C,UAAU,QAAQ,WAAW;EAC7B,MAAM,QAAQ,MAAM,GAAA,EAAwB;EAC5C,WAAW,QAAQ,YAAY;EAC/B,cAAc,MAAM;EACpB,YAAY,QAAQ,aAAa;EACjC,QAAQ,MAAM;EACd,WAAW,iBAAiB,QAAQ,SAAS;EAC7C,aAAa,QAAQ;EACrB,KAAK,QAAQ,OAAO;EACpB,SAAS,QAAQ,UAAU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AAK;AACrE;AAEA,MAAa,QAAQ,SAAiB,CAAC,MAAiB;CACtD,IAAI;CAGJ,MAAM,QAAQ,oBACZ,WACE,sBACA,OAAO,QAAgD;EACrD,MAAM,IAAI,SAAe,YAAY,WAAW,SAAS,CAAC,CAAC;EAC3D,MAAM,eAAe,oBAAoB,KAAK,MAAM;EACpD,IAAI,CAAC,aAAa,UAChB;EAEF,WAAW,WAAW,YAAY;EAClC,MAAM,OAAO,MAAM;CACrB,GACA,EAdY,eAAe,EAcvB,CACN,CACF;CAEA,MAAMK,UAAQC,MAAU;EACtB,YAAY,OAAO,YACjB,OAAO,QAAQ,OAAO,cAAc,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CAC5D,KACA,OAAO,KAAK,CACd,CAAC,CACH;EACA,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,aAAa,OAAO;EACpB,gBAAgB,OAAO;CACzB,CAAC;CAsBD,OAAO;EACL;EACA,OAAA;EACA,cAvBmB,MAAM,SACzBD,SACA,MAAM,OACJ,OAAO,IAAI,aAAa;GACtB,MAAM,MAAM,OAAO;GACnB,MAAM,eAAe,oBAAoB,KAAK,MAAM;GACpD,IAAI,CAAC,aAAa,UAChB,OAAO,MAAM;GAEf,OAAOE,QAAY,YAAY;EACjC,CAAC,CACH,GACA,MAAM,cACJ,OAAO,IAAI,aAAa;GACtB,MAAM,MAAM,OAAO;GACnB,OAAO,OAAO,mBAAmB,OAAO,cAAc,MAAM,GAAG,CAAC,CAAC;EACnE,CAAC,CACH,CAMW;CACb;AACF;AAEA,MAAa,mBAAmB,EAAE,KAAK"}
@@ -1,8 +1,9 @@
1
- import { Config, Duration, Effect, Layer, ManagedRuntime, Option } from "effect";
1
+ import { Cause, Config, Context, Duration, Effect, Layer, ManagedRuntime, Option, Schema } from "effect";
2
2
  import * as Tracer from "effect/Tracer";
3
+ import { HttpClient } from "effect/unstable/http";
3
4
  import { SpanContext } from "@opentelemetry/api";
4
5
  declare namespace layer_d_exports {
5
- export { MxlConfig, layer };
6
+ export { MxlConfig, layer$1 as layer };
6
7
  }
7
8
  interface MxlConfig {
8
9
  readonly serviceName?: string | undefined;
@@ -23,7 +24,71 @@ interface MxlConfig {
23
24
  *
24
25
  * Returns a no-op layer when `OTEL_SDK_DISABLED=true`.
25
26
  */
26
- declare const layer: (config?: MxlConfig) => Layer.Layer<never, never, never>;
27
+ declare const layer$1: (config?: MxlConfig) => Layer.Layer<never, never, never>;
28
+ //#endregion
29
+ //#region src/shared/product-event.d.ts
30
+ interface TrackProps {
31
+ readonly [key: string]: unknown;
32
+ }
33
+ interface TrackOptions {
34
+ readonly attributes?: TrackProps | undefined;
35
+ readonly groupId?: string | undefined;
36
+ readonly pagePath?: string | undefined;
37
+ readonly sessionId?: string | undefined;
38
+ readonly timestamp?: Date | number | undefined;
39
+ readonly traceparent?: string | undefined;
40
+ readonly url?: string | undefined;
41
+ readonly userId?: string | undefined;
42
+ readonly visitorId?: string | undefined;
43
+ }
44
+ declare namespace events_d_exports {
45
+ export { MxlEvents, MxlEventsApi, MxlEventsConfig, MxlEventsHandle, ProductEventsPostError, TrackOptions, layer, make$1 as make, makeHandle };
46
+ }
47
+ interface MxlEventsConfig {
48
+ readonly apiKey?: string | undefined;
49
+ readonly clientId?: string | undefined;
50
+ readonly endpoint?: string | undefined;
51
+ readonly eventsPath?: string | undefined;
52
+ readonly flushInterval?: Duration.Input | undefined;
53
+ readonly maxBatchSize?: number | undefined;
54
+ readonly serviceName?: string | undefined;
55
+ }
56
+ interface MxlEventsApi {
57
+ readonly flush: Effect.Effect<void>;
58
+ readonly track: (name: string, options?: TrackOptions) => Effect.Effect<void>;
59
+ }
60
+ declare const MxlEvents_base: Context.ServiceClass<MxlEvents, "@safaricom-mxl/effect-sdk/MxlEvents", MxlEventsApi>;
61
+ declare class MxlEvents extends MxlEvents_base {}
62
+ declare const ProductEventsPostError_base: Schema.Class<ProductEventsPostError, Schema.TaggedStruct<"@safaricom-mxl/effect-sdk/ProductEventsPostError", {
63
+ readonly cause: Schema.optionalKey<Schema.Defect>;
64
+ readonly message: Schema.String;
65
+ readonly status: Schema.optionalKey<Schema.Number>;
66
+ }>, Cause.YieldableError>;
67
+ declare class ProductEventsPostError extends ProductEventsPostError_base {}
68
+ declare const make$1: (config?: MxlEventsConfig) => Effect.Effect<{
69
+ flush: Effect.Effect<void, never, never>;
70
+ track: (name: string, options?: TrackOptions) => Effect.Effect<void>;
71
+ }, never, HttpClient.HttpClient | import("effect/Scope").Scope>;
72
+ declare const layer: (config?: MxlEventsConfig) => Layer.Layer<MxlEvents>;
73
+ interface MxlEventsHandle {
74
+ readonly dispose: () => Promise<void>;
75
+ readonly flush: () => Promise<void>;
76
+ readonly track: (name: string, options?: TrackOptions) => void;
77
+ }
78
+ declare const makeHandle: (config?: MxlEventsConfig) => MxlEventsHandle;
79
+ declare namespace flushable_d_exports {
80
+ export { FlushableTelemetry, MxlFlushableConfig, make };
81
+ }
82
+ interface MxlFlushableConfig extends MxlConfig {
83
+ readonly apiKey?: string | undefined;
84
+ readonly autoFlushInterval?: number | false | undefined;
85
+ readonly clientId?: string | undefined;
86
+ readonly ingestUrl?: string | undefined;
87
+ }
88
+ interface FlushableTelemetry extends MxlEventsHandle {
89
+ readonly layer: Layer.Layer<never, never, never>;
90
+ }
91
+ declare const make: (config?: MxlFlushableConfig) => FlushableTelemetry;
27
92
  //#endregion
28
93
  //#region src/server/platform.d.ts
29
94
  interface PlatformInputs {
@@ -190,7 +255,7 @@ interface EffectTraceEnricherOptions {
190
255
  /**
191
256
  * Enrich evlog wide events with trace/span IDs from OTel global context or W3C headers.
192
257
  *
193
- * Use in the MXL evlog enricher chain alongside `createOtelTraceEnricher`.
258
+ * Use `createEffectTraceEnricher` in the MXL evlog enricher chain.
194
259
  */
195
260
  declare function createEffectTraceEnricher(options?: EffectTraceEnricherOptions): (ctx: EffectTraceEnrichContext) => void;
196
261
  //#endregion
@@ -218,5 +283,5 @@ declare function withDependencySpan<A, E, R>(name: string, options: WithDependen
218
283
  /** Promise-based dependency span for non-Effect code paths. */
219
284
  declare function withPromiseDependencySpan<T>(name: string, attributes: Record<string, string>, operation: () => Promise<T>, kind?: DependencySpanKind): Promise<T>;
220
285
  //#endregion
221
- export { annotateLogsWithActiveSpanCorrelation as $, minimumLogLevelLayer as A, buildQueueTraceCarrier as B, SerializedLogError as C, logError as D, logDebug as E, jobWithSpanEffect as F, resolveTraceparentFromHeaders as G, finalizeHttpSpan as H, runJobWithSpan as I, withHttpServerSpan as J, spanContextFromCarrier as K, HttpSpanAttributes as L, resolveLogLevelFromEnv as M, serializeLogError as N, logInfo as O, RunJobWithSpanOptions as P, TraceLogAnnotations as Q, LogHttpResponseOptions as R, HttpStatusLogFields as S, logAtLevel as T, logHttpRequestFailure as U, buildQueueTraceCarrierEffect as V, logHttpResponse as W, withParentFromTraceparent as X, withParentFromTraceCarrier as Y, TraceCorrelation as Z, formatTraceparent as _, bufferSpanAttributes as a, normalizeOtlpBaseUrl as at, EffectLogLevel as b, kafkaProducerSpanAttributes as c, PlatformInputs as ct, withDependencySpan as d, MxlConfig as dt, getEffectTraceCorrelation as et, withPromiseDependencySpan as f, layer_d_exports as ft, buildTraceCarrierFromSpan as g, createEffectTraceEnricher as h, addSpanLinksFromTraceCarriers as i, tracerDisabledWhenLayer as it, resolveEffectLogLevelFromHttpStatus as j, logWarning as k, queueConsumerSpanAttributes as l, derivePlatformAttributes as lt, EffectTraceEnricherOptions as m, DependencySpanKind as n, traceCorrelationLogAnnotations as nt, dbClientSpanAttributes as o, parseOtelResourceAttributes as ot, EffectTraceEnrichContext as p, spanContextFromTraceparent as q, WithDependencySpanOptions as r, shouldDisableHttpTrace as rt, geoSpanAttributes as s, parseOtlpHeaders as st, DbSystem as t, parseTraceparent as tt, queueProducerSpanAttributes as u, getAutoPlatformAttributes as ut, otelGlobalContextBridgeLayer as v, buildHttpStatusLogFields as w, HttpLogOutcome as x, wrapTracerWithOtelContextBridge as y, QueueTraceContextCarrier$1 as z };
222
- //# sourceMappingURL=index-8yBtnSxJ.d.mts.map
286
+ export { annotateLogsWithActiveSpanCorrelation as $, minimumLogLevelLayer as A, buildQueueTraceCarrier as B, SerializedLogError as C, logError as D, logDebug as E, jobWithSpanEffect as F, resolveTraceparentFromHeaders as G, finalizeHttpSpan as H, runJobWithSpan as I, withHttpServerSpan as J, spanContextFromCarrier as K, HttpSpanAttributes as L, resolveLogLevelFromEnv as M, serializeLogError as N, logInfo as O, RunJobWithSpanOptions as P, TraceLogAnnotations as Q, LogHttpResponseOptions as R, HttpStatusLogFields as S, logAtLevel as T, logHttpRequestFailure as U, buildQueueTraceCarrierEffect as V, logHttpResponse as W, withParentFromTraceparent as X, withParentFromTraceCarrier as Y, TraceCorrelation as Z, formatTraceparent as _, events_d_exports as _t, bufferSpanAttributes as a, normalizeOtlpBaseUrl as at, EffectLogLevel as b, layer_d_exports as bt, kafkaProducerSpanAttributes as c, PlatformInputs as ct, withDependencySpan as d, FlushableTelemetry as dt, getEffectTraceCorrelation as et, withPromiseDependencySpan as f, MxlFlushableConfig as ft, buildTraceCarrierFromSpan as g, MxlEventsHandle as gt, createEffectTraceEnricher as h, MxlEventsConfig as ht, addSpanLinksFromTraceCarriers as i, tracerDisabledWhenLayer as it, resolveEffectLogLevelFromHttpStatus as j, logWarning as k, queueConsumerSpanAttributes as l, derivePlatformAttributes as lt, EffectTraceEnricherOptions as m, MxlEventsApi as mt, DependencySpanKind as n, traceCorrelationLogAnnotations as nt, dbClientSpanAttributes as o, parseOtelResourceAttributes as ot, EffectTraceEnrichContext as p, flushable_d_exports as pt, spanContextFromTraceparent as q, WithDependencySpanOptions as r, shouldDisableHttpTrace as rt, geoSpanAttributes as s, parseOtlpHeaders as st, DbSystem as t, parseTraceparent as tt, queueProducerSpanAttributes as u, getAutoPlatformAttributes as ut, otelGlobalContextBridgeLayer as v, TrackOptions as vt, buildHttpStatusLogFields as w, HttpLogOutcome as x, wrapTracerWithOtelContextBridge as y, MxlConfig as yt, QueueTraceContextCarrier$1 as z };
287
+ //# sourceMappingURL=index-BF4-zL-9.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-BF4-zL-9.d.mts","names":[],"sources":["../src/server/layer.ts","../src/shared/product-event.ts","../src/server/events.ts","../src/server/flushable.ts","../src/server/platform.ts","../src/server/config.ts","../src/server/otlp.ts","../src/server/http-middleware.ts","../src/server/trace-correlation.ts","../src/server/http-tracing.ts","../src/server/jobs.ts","../src/server/logging.ts","../src/server/otel-context-bridge.ts","../src/server/evlog-bridge.ts","../src/shared/dependency-spans.ts"],"mappings":";;;;;;;UAUiB;WACN;WACA;WACA;WACA;WACA,UAAU;WACV,aAAa;WACb;WACA,uBAAuB,SAAS;WAChC,wBAAwB,SAAS;WACjC,uBAAuB,SAAS;WAChC,kBAAkB,SAAS;;;;;;;;cASzB,UAAK,SAAY,cAAS,MAAA;;;UCVtB;YACL;;UAGK;WACN,aAAa;WACb;WACA;WACA;WACA,YAAY;WACZ;WACA;WACA;WACA;;;;;UCHM;WACN;WACA;WACA;WACA;WACA,gBAAgB,SAAS;WACzB;WACA;;UAGM;WACN,OAAO,OAAO;WACd,QAAQ,cAAc,UAAU,iBAAiB,OAAO;;;cAGtD,kBAAkB;;;;;;cAIlB,+BAA+B;cA2B/B,SAAI,SAAA,oBAAA,OAAA;;EAuFM,QAAA,cAAM,UAAW,iBAAoB,OAAO;UA6BjE,WAAA,oCAAA;cAEW,QAAK,SAAY,oBAAuB,MAAM,MAAM;UAGhD;WACN,eAAe;WACf,aAAa;WACb,QAAQ,cAAc,UAAU;;cAG9B,aAAU,SAAY,oBAAuB;;;;UChMzC,2BAA2B;WACjC;WACA;WACA;WACA;;UAGM,2BAA2B;WACjC,OAAO,MAAM;;cAGX,OAAI,SAAY,uBAA0B;;;UCnBtC;WACN;WACA;WACA;WACA;WACA,KAAK,SAAS;;KAGpB,QAAQ;cAoIA,2BAAwB,QAC3B,mBACP;KAoBS,qBAAqB;cAoBpB,iCAAgC;;;;;;;;;c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OAAO,OAAO,GAAG,GAAG;;iBA2BD,0BAA0B,GAC9C,cACA,YAAY,wBACZ,iBAAiB,QAAQ,IACzB,OAAM,qBACL,QAAQ"}
@@ -1,2 +1,2 @@
1
- import { $ as annotateLogsWithActiveSpanCorrelation, A as minimumLogLevelLayer, B as buildQueueTraceCarrier, C as SerializedLogError, D as logError, E as logDebug, F as jobWithSpanEffect, G as resolveTraceparentFromHeaders, H as finalizeHttpSpan, I as runJobWithSpan, J as withHttpServerSpan, K as spanContextFromCarrier, L as HttpSpanAttributes, M as resolveLogLevelFromEnv, N as serializeLogError, O as logInfo, P as RunJobWithSpanOptions, Q as TraceLogAnnotations, R as LogHttpResponseOptions, S as HttpStatusLogFields, T as logAtLevel, U as logHttpRequestFailure, V as buildQueueTraceCarrierEffect, W as logHttpResponse, X as withParentFromTraceparent, Y as withParentFromTraceCarrier, Z as TraceCorrelation, _ as formatTraceparent, a as bufferSpanAttributes, at as normalizeOtlpBaseUrl, b as EffectLogLevel, c as kafkaProducerSpanAttributes, ct as PlatformInputs, d as withDependencySpan, dt as MxlConfig, et as getEffectTraceCorrelation, f as withPromiseDependencySpan, ft as layer_d_exports, g as buildTraceCarrierFromSpan, h as createEffectTraceEnricher, i as addSpanLinksFromTraceCarriers, it as tracerDisabledWhenLayer, j as resolveEffectLogLevelFromHttpStatus, k as logWarning, l as queueConsumerSpanAttributes, lt as derivePlatformAttributes, m as EffectTraceEnricherOptions, n as DependencySpanKind, nt as traceCorrelationLogAnnotations, o as dbClientSpanAttributes, ot as parseOtelResourceAttributes, p as EffectTraceEnrichContext, q as spanContextFromTraceparent, r as WithDependencySpanOptions, rt as shouldDisableHttpTrace, s as geoSpanAttributes, st as parseOtlpHeaders, t as DbSystem, tt as parseTraceparent, u as queueProducerSpanAttributes, ut as getAutoPlatformAttributes, v as otelGlobalContextBridgeLayer, w as buildHttpStatusLogFields, x as HttpLogOutcome, y as wrapTracerWithOtelContextBridge, z as QueueTraceContextCarrier } from "./index-8yBtnSxJ.mjs";
2
- export { type DbSystem, type DependencySpanKind, type EffectLogLevel, type EffectTraceEnrichContext, type EffectTraceEnricherOptions, type HttpLogOutcome, type HttpSpanAttributes, type HttpStatusLogFields, type LogHttpResponseOptions, layer_d_exports as Mxl, type MxlConfig, type PlatformInputs, type QueueTraceContextCarrier, type RunJobWithSpanOptions, type SerializedLogError, type TraceCorrelation, type TraceLogAnnotations, type WithDependencySpanOptions, addSpanLinksFromTraceCarriers, annotateLogsWithActiveSpanCorrelation, bufferSpanAttributes, buildHttpStatusLogFields, buildQueueTraceCarrier, buildQueueTraceCarrierEffect, buildTraceCarrierFromSpan, createEffectTraceEnricher, dbClientSpanAttributes, derivePlatformAttributes, finalizeHttpSpan, formatTraceparent, geoSpanAttributes, getAutoPlatformAttributes, getEffectTraceCorrelation, jobWithSpanEffect, kafkaProducerSpanAttributes, logAtLevel, logDebug, logError, logHttpRequestFailure, logHttpResponse, logInfo, logWarning, minimumLogLevelLayer, normalizeOtlpBaseUrl, otelGlobalContextBridgeLayer, parseOtelResourceAttributes, parseOtlpHeaders, parseTraceparent, queueConsumerSpanAttributes, queueProducerSpanAttributes, resolveEffectLogLevelFromHttpStatus, resolveLogLevelFromEnv, resolveTraceparentFromHeaders, runJobWithSpan, serializeLogError, shouldDisableHttpTrace, spanContextFromCarrier, spanContextFromTraceparent, traceCorrelationLogAnnotations, tracerDisabledWhenLayer, withDependencySpan, withHttpServerSpan, withParentFromTraceCarrier, withParentFromTraceparent, withPromiseDependencySpan, wrapTracerWithOtelContextBridge };
1
+ import { $ as annotateLogsWithActiveSpanCorrelation, A as minimumLogLevelLayer, B as buildQueueTraceCarrier, C as SerializedLogError, D as logError, E as logDebug, F as jobWithSpanEffect, G as resolveTraceparentFromHeaders, H as finalizeHttpSpan, I as runJobWithSpan, J as withHttpServerSpan, K as spanContextFromCarrier, L as HttpSpanAttributes, M as resolveLogLevelFromEnv, N as serializeLogError, O as logInfo, P as RunJobWithSpanOptions, Q as TraceLogAnnotations, R as LogHttpResponseOptions, S as HttpStatusLogFields, T as logAtLevel, U as logHttpRequestFailure, V as buildQueueTraceCarrierEffect, W as logHttpResponse, X as withParentFromTraceparent, Y as withParentFromTraceCarrier, Z as TraceCorrelation, _ as formatTraceparent, _t as events_d_exports, a as bufferSpanAttributes, at as normalizeOtlpBaseUrl, b as EffectLogLevel, bt as layer_d_exports, c as kafkaProducerSpanAttributes, ct as PlatformInputs, d as withDependencySpan, dt as FlushableTelemetry, et as getEffectTraceCorrelation, f as withPromiseDependencySpan, ft as MxlFlushableConfig, g as buildTraceCarrierFromSpan, gt as MxlEventsHandle, h as createEffectTraceEnricher, ht as MxlEventsConfig, i as addSpanLinksFromTraceCarriers, it as tracerDisabledWhenLayer, j as resolveEffectLogLevelFromHttpStatus, k as logWarning, l as queueConsumerSpanAttributes, lt as derivePlatformAttributes, m as EffectTraceEnricherOptions, mt as MxlEventsApi, n as DependencySpanKind, nt as traceCorrelationLogAnnotations, o as dbClientSpanAttributes, ot as parseOtelResourceAttributes, p as EffectTraceEnrichContext, pt as flushable_d_exports, q as spanContextFromTraceparent, r as WithDependencySpanOptions, rt as shouldDisableHttpTrace, s as geoSpanAttributes, st as parseOtlpHeaders, t as DbSystem, tt as parseTraceparent, u as queueProducerSpanAttributes, ut as getAutoPlatformAttributes, v as otelGlobalContextBridgeLayer, vt as TrackOptions, w as buildHttpStatusLogFields, x as HttpLogOutcome, y as wrapTracerWithOtelContextBridge, yt as MxlConfig, z as QueueTraceContextCarrier } from "./index-BF4-zL-9.mjs";
2
+ export { type DbSystem, type DependencySpanKind, type EffectLogLevel, type EffectTraceEnrichContext, type EffectTraceEnricherOptions, type FlushableTelemetry, type HttpLogOutcome, type HttpSpanAttributes, type HttpStatusLogFields, type LogHttpResponseOptions, layer_d_exports as Mxl, type MxlConfig, events_d_exports as MxlEvents, type MxlEventsApi, type MxlEventsConfig, type MxlEventsHandle, flushable_d_exports as MxlFlush, type MxlFlushableConfig, type PlatformInputs, type QueueTraceContextCarrier, type RunJobWithSpanOptions, type SerializedLogError, type TraceCorrelation, type TraceLogAnnotations, type TrackOptions, type WithDependencySpanOptions, addSpanLinksFromTraceCarriers, annotateLogsWithActiveSpanCorrelation, bufferSpanAttributes, buildHttpStatusLogFields, buildQueueTraceCarrier, buildQueueTraceCarrierEffect, buildTraceCarrierFromSpan, createEffectTraceEnricher, dbClientSpanAttributes, derivePlatformAttributes, finalizeHttpSpan, formatTraceparent, geoSpanAttributes, getAutoPlatformAttributes, getEffectTraceCorrelation, jobWithSpanEffect, kafkaProducerSpanAttributes, logAtLevel, logDebug, logError, logHttpRequestFailure, logHttpResponse, logInfo, logWarning, minimumLogLevelLayer, normalizeOtlpBaseUrl, otelGlobalContextBridgeLayer, parseOtelResourceAttributes, parseOtlpHeaders, parseTraceparent, queueConsumerSpanAttributes, queueProducerSpanAttributes, resolveEffectLogLevelFromHttpStatus, resolveLogLevelFromEnv, resolveTraceparentFromHeaders, runJobWithSpan, serializeLogError, shouldDisableHttpTrace, spanContextFromCarrier, spanContextFromTraceparent, traceCorrelationLogAnnotations, tracerDisabledWhenLayer, withDependencySpan, withHttpServerSpan, withParentFromTraceCarrier, withParentFromTraceparent, withPromiseDependencySpan, wrapTracerWithOtelContextBridge };
@@ -1,2 +1,2 @@
1
- import { A as minimumLogLevelLayer, B as layer_exports, C as withParentFromTraceparent, D as logError, E as logDebug, F as getEffectTraceCorrelation, G as normalizeOtlpBaseUrl, H as getAutoPlatformAttributes, I as parseTraceparent, J as otelGlobalContextBridgeLayer, K as buildTraceCarrierFromSpan, L as traceCorrelationLogAnnotations, M as resolveLogLevelFromEnv, N as serializeLogError, O as logInfo, P as annotateLogsWithActiveSpanCorrelation, R as shouldDisableHttpTrace, S as withParentFromTraceCarrier, T as logAtLevel, U as parseOtelResourceAttributes, V as derivePlatformAttributes, W as parseOtlpHeaders, Y as wrapTracerWithOtelContextBridge, _ as logHttpResponse, a as kafkaProducerSpanAttributes, b as spanContextFromTraceparent, c as withDependencySpan, d as jobWithSpanEffect, f as runJobWithSpan, g as logHttpRequestFailure, h as finalizeHttpSpan, i as geoSpanAttributes, j as resolveEffectLogLevelFromHttpStatus, k as logWarning, l as withPromiseDependencySpan, m as buildQueueTraceCarrierEffect, n as bufferSpanAttributes, o as queueConsumerSpanAttributes, p as buildQueueTraceCarrier, q as formatTraceparent, r as dbClientSpanAttributes, s as queueProducerSpanAttributes, t as addSpanLinksFromTraceCarriers, u as createEffectTraceEnricher, v as resolveTraceparentFromHeaders, w as buildHttpStatusLogFields, x as withHttpServerSpan, y as spanContextFromCarrier, z as tracerDisabledWhenLayer } from "./server-Dz6g7ADZ.mjs";
2
- export { layer_exports as Mxl, addSpanLinksFromTraceCarriers, annotateLogsWithActiveSpanCorrelation, bufferSpanAttributes, buildHttpStatusLogFields, buildQueueTraceCarrier, buildQueueTraceCarrierEffect, buildTraceCarrierFromSpan, createEffectTraceEnricher, dbClientSpanAttributes, derivePlatformAttributes, finalizeHttpSpan, formatTraceparent, geoSpanAttributes, getAutoPlatformAttributes, getEffectTraceCorrelation, jobWithSpanEffect, kafkaProducerSpanAttributes, logAtLevel, logDebug, logError, logHttpRequestFailure, logHttpResponse, logInfo, logWarning, minimumLogLevelLayer, normalizeOtlpBaseUrl, otelGlobalContextBridgeLayer, parseOtelResourceAttributes, parseOtlpHeaders, parseTraceparent, queueConsumerSpanAttributes, queueProducerSpanAttributes, resolveEffectLogLevelFromHttpStatus, resolveLogLevelFromEnv, resolveTraceparentFromHeaders, runJobWithSpan, serializeLogError, shouldDisableHttpTrace, spanContextFromCarrier, spanContextFromTraceparent, traceCorrelationLogAnnotations, tracerDisabledWhenLayer, withDependencySpan, withHttpServerSpan, withParentFromTraceCarrier, withParentFromTraceparent, withPromiseDependencySpan, wrapTracerWithOtelContextBridge };
1
+ import { A as minimumLogLevelLayer, B as flushable_exports, C as withParentFromTraceparent, D as logError, E as logDebug, F as getEffectTraceCorrelation, G as parseOtelResourceAttributes, H as layer_exports, I as parseTraceparent, J as buildTraceCarrierFromSpan, K as parseOtlpHeaders, L as traceCorrelationLogAnnotations, M as resolveLogLevelFromEnv, N as serializeLogError, O as logInfo, P as annotateLogsWithActiveSpanCorrelation, R as shouldDisableHttpTrace, S as withParentFromTraceCarrier, T as logAtLevel, U as derivePlatformAttributes, V as events_exports, W as getAutoPlatformAttributes, X as otelGlobalContextBridgeLayer, Y as formatTraceparent, Z as wrapTracerWithOtelContextBridge, _ as logHttpResponse, a as kafkaProducerSpanAttributes, b as spanContextFromTraceparent, c as withDependencySpan, d as jobWithSpanEffect, f as runJobWithSpan, g as logHttpRequestFailure, h as finalizeHttpSpan, i as geoSpanAttributes, j as resolveEffectLogLevelFromHttpStatus, k as logWarning, l as withPromiseDependencySpan, m as buildQueueTraceCarrierEffect, n as bufferSpanAttributes, o as queueConsumerSpanAttributes, p as buildQueueTraceCarrier, q as normalizeOtlpBaseUrl, r as dbClientSpanAttributes, s as queueProducerSpanAttributes, t as addSpanLinksFromTraceCarriers, u as createEffectTraceEnricher, v as resolveTraceparentFromHeaders, w as buildHttpStatusLogFields, x as withHttpServerSpan, y as spanContextFromCarrier, z as tracerDisabledWhenLayer } from "./server-DU685moi.mjs";
2
+ export { layer_exports as Mxl, events_exports as MxlEvents, flushable_exports as MxlFlush, addSpanLinksFromTraceCarriers, annotateLogsWithActiveSpanCorrelation, bufferSpanAttributes, buildHttpStatusLogFields, buildQueueTraceCarrier, buildQueueTraceCarrierEffect, buildTraceCarrierFromSpan, createEffectTraceEnricher, dbClientSpanAttributes, derivePlatformAttributes, finalizeHttpSpan, formatTraceparent, geoSpanAttributes, getAutoPlatformAttributes, getEffectTraceCorrelation, jobWithSpanEffect, kafkaProducerSpanAttributes, logAtLevel, logDebug, logError, logHttpRequestFailure, logHttpResponse, logInfo, logWarning, minimumLogLevelLayer, normalizeOtlpBaseUrl, otelGlobalContextBridgeLayer, parseOtelResourceAttributes, parseOtlpHeaders, parseTraceparent, queueConsumerSpanAttributes, queueProducerSpanAttributes, resolveEffectLogLevelFromHttpStatus, resolveLogLevelFromEnv, resolveTraceparentFromHeaders, runJobWithSpan, serializeLogError, shouldDisableHttpTrace, spanContextFromCarrier, spanContextFromTraceparent, traceCorrelationLogAnnotations, tracerDisabledWhenLayer, withDependencySpan, withHttpServerSpan, withParentFromTraceCarrier, withParentFromTraceparent, withPromiseDependencySpan, wrapTracerWithOtelContextBridge };
@@ -1,2 +1,2 @@
1
- import { $ as annotateLogsWithActiveSpanCorrelation, A as minimumLogLevelLayer, B as buildQueueTraceCarrier, C as SerializedLogError, D as logError, E as logDebug, F as jobWithSpanEffect, G as resolveTraceparentFromHeaders, H as finalizeHttpSpan, I as runJobWithSpan, J as withHttpServerSpan, K as spanContextFromCarrier, L as HttpSpanAttributes, M as resolveLogLevelFromEnv, N as serializeLogError, O as logInfo, P as RunJobWithSpanOptions, Q as TraceLogAnnotations, R as LogHttpResponseOptions, S as HttpStatusLogFields, T as logAtLevel, U as logHttpRequestFailure, V as buildQueueTraceCarrierEffect, W as logHttpResponse, X as withParentFromTraceparent, Y as withParentFromTraceCarrier, Z as TraceCorrelation, _ as formatTraceparent, a as bufferSpanAttributes, at as normalizeOtlpBaseUrl, b as EffectLogLevel, c as kafkaProducerSpanAttributes, ct as PlatformInputs, d as withDependencySpan, dt as MxlConfig, et as getEffectTraceCorrelation, f as withPromiseDependencySpan, ft as layer_d_exports, g as buildTraceCarrierFromSpan, h as createEffectTraceEnricher, i as addSpanLinksFromTraceCarriers, it as tracerDisabledWhenLayer, j as resolveEffectLogLevelFromHttpStatus, k as logWarning, l as queueConsumerSpanAttributes, lt as derivePlatformAttributes, m as EffectTraceEnricherOptions, n as DependencySpanKind, nt as traceCorrelationLogAnnotations, o as dbClientSpanAttributes, ot as parseOtelResourceAttributes, p as EffectTraceEnrichContext, q as spanContextFromTraceparent, r as WithDependencySpanOptions, rt as shouldDisableHttpTrace, s as geoSpanAttributes, st as parseOtlpHeaders, t as DbSystem, tt as parseTraceparent, u as queueProducerSpanAttributes, ut as getAutoPlatformAttributes, v as otelGlobalContextBridgeLayer, w as buildHttpStatusLogFields, x as HttpLogOutcome, y as wrapTracerWithOtelContextBridge, z as QueueTraceContextCarrier } from "../index-8yBtnSxJ.mjs";
2
- export { type DbSystem, type DependencySpanKind, type EffectLogLevel, type EffectTraceEnrichContext, type EffectTraceEnricherOptions, type HttpLogOutcome, type HttpSpanAttributes, type HttpStatusLogFields, type LogHttpResponseOptions, layer_d_exports as Mxl, type MxlConfig, type PlatformInputs, type QueueTraceContextCarrier, type RunJobWithSpanOptions, type SerializedLogError, type TraceCorrelation, type TraceLogAnnotations, type WithDependencySpanOptions, addSpanLinksFromTraceCarriers, annotateLogsWithActiveSpanCorrelation, bufferSpanAttributes, buildHttpStatusLogFields, buildQueueTraceCarrier, buildQueueTraceCarrierEffect, buildTraceCarrierFromSpan, createEffectTraceEnricher, dbClientSpanAttributes, derivePlatformAttributes, finalizeHttpSpan, formatTraceparent, geoSpanAttributes, getAutoPlatformAttributes, getEffectTraceCorrelation, jobWithSpanEffect, kafkaProducerSpanAttributes, logAtLevel, logDebug, logError, logHttpRequestFailure, logHttpResponse, logInfo, logWarning, minimumLogLevelLayer, normalizeOtlpBaseUrl, otelGlobalContextBridgeLayer, parseOtelResourceAttributes, parseOtlpHeaders, parseTraceparent, queueConsumerSpanAttributes, queueProducerSpanAttributes, resolveEffectLogLevelFromHttpStatus, resolveLogLevelFromEnv, resolveTraceparentFromHeaders, runJobWithSpan, serializeLogError, shouldDisableHttpTrace, spanContextFromCarrier, spanContextFromTraceparent, traceCorrelationLogAnnotations, tracerDisabledWhenLayer, withDependencySpan, withHttpServerSpan, withParentFromTraceCarrier, withParentFromTraceparent, withPromiseDependencySpan, wrapTracerWithOtelContextBridge };
1
+ import { $ as annotateLogsWithActiveSpanCorrelation, A as minimumLogLevelLayer, B as buildQueueTraceCarrier, C as SerializedLogError, D as logError, E as logDebug, F as jobWithSpanEffect, G as resolveTraceparentFromHeaders, H as finalizeHttpSpan, I as runJobWithSpan, J as withHttpServerSpan, K as spanContextFromCarrier, L as HttpSpanAttributes, M as resolveLogLevelFromEnv, N as serializeLogError, O as logInfo, P as RunJobWithSpanOptions, Q as TraceLogAnnotations, R as LogHttpResponseOptions, S as HttpStatusLogFields, T as logAtLevel, U as logHttpRequestFailure, V as buildQueueTraceCarrierEffect, W as logHttpResponse, X as withParentFromTraceparent, Y as withParentFromTraceCarrier, Z as TraceCorrelation, _ as formatTraceparent, _t as events_d_exports, a as bufferSpanAttributes, at as normalizeOtlpBaseUrl, b as EffectLogLevel, bt as layer_d_exports, c as kafkaProducerSpanAttributes, ct as PlatformInputs, d as withDependencySpan, dt as FlushableTelemetry, et as getEffectTraceCorrelation, f as withPromiseDependencySpan, ft as MxlFlushableConfig, g as buildTraceCarrierFromSpan, gt as MxlEventsHandle, h as createEffectTraceEnricher, ht as MxlEventsConfig, i as addSpanLinksFromTraceCarriers, it as tracerDisabledWhenLayer, j as resolveEffectLogLevelFromHttpStatus, k as logWarning, l as queueConsumerSpanAttributes, lt as derivePlatformAttributes, m as EffectTraceEnricherOptions, mt as MxlEventsApi, n as DependencySpanKind, nt as traceCorrelationLogAnnotations, o as dbClientSpanAttributes, ot as parseOtelResourceAttributes, p as EffectTraceEnrichContext, pt as flushable_d_exports, q as spanContextFromTraceparent, r as WithDependencySpanOptions, rt as shouldDisableHttpTrace, s as geoSpanAttributes, st as parseOtlpHeaders, t as DbSystem, tt as parseTraceparent, u as queueProducerSpanAttributes, ut as getAutoPlatformAttributes, v as otelGlobalContextBridgeLayer, vt as TrackOptions, w as buildHttpStatusLogFields, x as HttpLogOutcome, y as wrapTracerWithOtelContextBridge, yt as MxlConfig, z as QueueTraceContextCarrier } from "../index-BF4-zL-9.mjs";
2
+ export { type DbSystem, type DependencySpanKind, type EffectLogLevel, type EffectTraceEnrichContext, type EffectTraceEnricherOptions, type FlushableTelemetry, type HttpLogOutcome, type HttpSpanAttributes, type HttpStatusLogFields, type LogHttpResponseOptions, layer_d_exports as Mxl, type MxlConfig, events_d_exports as MxlEvents, type MxlEventsApi, type MxlEventsConfig, type MxlEventsHandle, flushable_d_exports as MxlFlush, type MxlFlushableConfig, type PlatformInputs, type QueueTraceContextCarrier, type RunJobWithSpanOptions, type SerializedLogError, type TraceCorrelation, type TraceLogAnnotations, type TrackOptions, type WithDependencySpanOptions, addSpanLinksFromTraceCarriers, annotateLogsWithActiveSpanCorrelation, bufferSpanAttributes, buildHttpStatusLogFields, buildQueueTraceCarrier, buildQueueTraceCarrierEffect, buildTraceCarrierFromSpan, createEffectTraceEnricher, dbClientSpanAttributes, derivePlatformAttributes, finalizeHttpSpan, formatTraceparent, geoSpanAttributes, getAutoPlatformAttributes, getEffectTraceCorrelation, jobWithSpanEffect, kafkaProducerSpanAttributes, logAtLevel, logDebug, logError, logHttpRequestFailure, logHttpResponse, logInfo, logWarning, minimumLogLevelLayer, normalizeOtlpBaseUrl, otelGlobalContextBridgeLayer, parseOtelResourceAttributes, parseOtlpHeaders, parseTraceparent, queueConsumerSpanAttributes, queueProducerSpanAttributes, resolveEffectLogLevelFromHttpStatus, resolveLogLevelFromEnv, resolveTraceparentFromHeaders, runJobWithSpan, serializeLogError, shouldDisableHttpTrace, spanContextFromCarrier, spanContextFromTraceparent, traceCorrelationLogAnnotations, tracerDisabledWhenLayer, withDependencySpan, withHttpServerSpan, withParentFromTraceCarrier, withParentFromTraceparent, withPromiseDependencySpan, wrapTracerWithOtelContextBridge };
@@ -1,2 +1,2 @@
1
- import { A as minimumLogLevelLayer, B as layer_exports, C as withParentFromTraceparent, D as logError, E as logDebug, F as getEffectTraceCorrelation, G as normalizeOtlpBaseUrl, H as getAutoPlatformAttributes, I as parseTraceparent, J as otelGlobalContextBridgeLayer, K as buildTraceCarrierFromSpan, L as traceCorrelationLogAnnotations, M as resolveLogLevelFromEnv, N as serializeLogError, O as logInfo, P as annotateLogsWithActiveSpanCorrelation, R as shouldDisableHttpTrace, S as withParentFromTraceCarrier, T as logAtLevel, U as parseOtelResourceAttributes, V as derivePlatformAttributes, W as parseOtlpHeaders, Y as wrapTracerWithOtelContextBridge, _ as logHttpResponse, a as kafkaProducerSpanAttributes, b as spanContextFromTraceparent, c as withDependencySpan, d as jobWithSpanEffect, f as runJobWithSpan, g as logHttpRequestFailure, h as finalizeHttpSpan, i as geoSpanAttributes, j as resolveEffectLogLevelFromHttpStatus, k as logWarning, l as withPromiseDependencySpan, m as buildQueueTraceCarrierEffect, n as bufferSpanAttributes, o as queueConsumerSpanAttributes, p as buildQueueTraceCarrier, q as formatTraceparent, r as dbClientSpanAttributes, s as queueProducerSpanAttributes, t as addSpanLinksFromTraceCarriers, u as createEffectTraceEnricher, v as resolveTraceparentFromHeaders, w as buildHttpStatusLogFields, x as withHttpServerSpan, y as spanContextFromCarrier, z as tracerDisabledWhenLayer } from "../server-Dz6g7ADZ.mjs";
2
- export { layer_exports as Mxl, addSpanLinksFromTraceCarriers, annotateLogsWithActiveSpanCorrelation, bufferSpanAttributes, buildHttpStatusLogFields, buildQueueTraceCarrier, buildQueueTraceCarrierEffect, buildTraceCarrierFromSpan, createEffectTraceEnricher, dbClientSpanAttributes, derivePlatformAttributes, finalizeHttpSpan, formatTraceparent, geoSpanAttributes, getAutoPlatformAttributes, getEffectTraceCorrelation, jobWithSpanEffect, kafkaProducerSpanAttributes, logAtLevel, logDebug, logError, logHttpRequestFailure, logHttpResponse, logInfo, logWarning, minimumLogLevelLayer, normalizeOtlpBaseUrl, otelGlobalContextBridgeLayer, parseOtelResourceAttributes, parseOtlpHeaders, parseTraceparent, queueConsumerSpanAttributes, queueProducerSpanAttributes, resolveEffectLogLevelFromHttpStatus, resolveLogLevelFromEnv, resolveTraceparentFromHeaders, runJobWithSpan, serializeLogError, shouldDisableHttpTrace, spanContextFromCarrier, spanContextFromTraceparent, traceCorrelationLogAnnotations, tracerDisabledWhenLayer, withDependencySpan, withHttpServerSpan, withParentFromTraceCarrier, withParentFromTraceparent, withPromiseDependencySpan, wrapTracerWithOtelContextBridge };
1
+ import { A as minimumLogLevelLayer, B as flushable_exports, C as withParentFromTraceparent, D as logError, E as logDebug, F as getEffectTraceCorrelation, G as parseOtelResourceAttributes, H as layer_exports, I as parseTraceparent, J as buildTraceCarrierFromSpan, K as parseOtlpHeaders, L as traceCorrelationLogAnnotations, M as resolveLogLevelFromEnv, N as serializeLogError, O as logInfo, P as annotateLogsWithActiveSpanCorrelation, R as shouldDisableHttpTrace, S as withParentFromTraceCarrier, T as logAtLevel, U as derivePlatformAttributes, V as events_exports, W as getAutoPlatformAttributes, X as otelGlobalContextBridgeLayer, Y as formatTraceparent, Z as wrapTracerWithOtelContextBridge, _ as logHttpResponse, a as kafkaProducerSpanAttributes, b as spanContextFromTraceparent, c as withDependencySpan, d as jobWithSpanEffect, f as runJobWithSpan, g as logHttpRequestFailure, h as finalizeHttpSpan, i as geoSpanAttributes, j as resolveEffectLogLevelFromHttpStatus, k as logWarning, l as withPromiseDependencySpan, m as buildQueueTraceCarrierEffect, n as bufferSpanAttributes, o as queueConsumerSpanAttributes, p as buildQueueTraceCarrier, q as normalizeOtlpBaseUrl, r as dbClientSpanAttributes, s as queueProducerSpanAttributes, t as addSpanLinksFromTraceCarriers, u as createEffectTraceEnricher, v as resolveTraceparentFromHeaders, w as buildHttpStatusLogFields, x as withHttpServerSpan, y as spanContextFromCarrier, z as tracerDisabledWhenLayer } from "../server-DU685moi.mjs";
2
+ export { layer_exports as Mxl, events_exports as MxlEvents, flushable_exports as MxlFlush, addSpanLinksFromTraceCarriers, annotateLogsWithActiveSpanCorrelation, bufferSpanAttributes, buildHttpStatusLogFields, buildQueueTraceCarrier, buildQueueTraceCarrierEffect, buildTraceCarrierFromSpan, createEffectTraceEnricher, dbClientSpanAttributes, derivePlatformAttributes, finalizeHttpSpan, formatTraceparent, geoSpanAttributes, getAutoPlatformAttributes, getEffectTraceCorrelation, jobWithSpanEffect, kafkaProducerSpanAttributes, logAtLevel, logDebug, logError, logHttpRequestFailure, logHttpResponse, logInfo, logWarning, minimumLogLevelLayer, normalizeOtlpBaseUrl, otelGlobalContextBridgeLayer, parseOtelResourceAttributes, parseOtlpHeaders, parseTraceparent, queueConsumerSpanAttributes, queueProducerSpanAttributes, resolveEffectLogLevelFromHttpStatus, resolveLogLevelFromEnv, resolveTraceparentFromHeaders, runJobWithSpan, serializeLogError, shouldDisableHttpTrace, spanContextFromCarrier, spanContextFromTraceparent, traceCorrelationLogAnnotations, tracerDisabledWhenLayer, withDependencySpan, withHttpServerSpan, withParentFromTraceCarrier, withParentFromTraceparent, withPromiseDependencySpan, wrapTracerWithOtelContextBridge };
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { Config, Effect, Layer, Match, Option, References } from "effect";
2
+ import { Cause, Config, Context, Duration, Effect, Layer, ManagedRuntime, Match, Option, References, Schedule, Schema, Semaphore } from "effect";
3
3
  import * as Tracer from "effect/Tracer";
4
- import { FetchHttpClient, HttpMiddleware } from "effect/unstable/http";
4
+ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpMiddleware } from "effect/unstable/http";
5
5
  import { Otlp } from "effect/unstable/observability";
6
6
  import * as Otel from "@opentelemetry/api";
7
7
  import { SpanKind, SpanStatusCode, TraceFlags, context, propagation, trace } from "@opentelemetry/api";
@@ -258,10 +258,10 @@ const getAutoPlatformAttributes = () => {
258
258
  };
259
259
  //#endregion
260
260
  //#region src/server/resource.ts
261
- const stringOrUndefined = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
262
- const DEFAULT_VCS_REPOSITORY_URL = "https://gitlab.safaricom.co.ke/mxl/apm/mxl-node-sdk";
261
+ const stringOrUndefined$1 = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
262
+ const DEFAULT_VCS_REPOSITORY_URL = "https://gitlab.safaricom.co.ke/mxl/apm/mxl-effect-sdk";
263
263
  function resolveCommitRevision() {
264
- return stringOrUndefined(process.env.COMMIT_SHA) ?? stringOrUndefined(process.env.VERCEL_GIT_COMMIT_SHA) ?? stringOrUndefined(process.env.GITHUB_SHA) ?? stringOrUndefined(process.env.RAILWAY_GIT_COMMIT_SHA) ?? stringOrUndefined(process.env.CF_PAGES_COMMIT_SHA) ?? stringOrUndefined(process.env.RENDER_GIT_COMMIT);
264
+ return stringOrUndefined$1(process.env.COMMIT_SHA) ?? stringOrUndefined$1(process.env.VERCEL_GIT_COMMIT_SHA) ?? stringOrUndefined$1(process.env.GITHUB_SHA) ?? stringOrUndefined$1(process.env.RAILWAY_GIT_COMMIT_SHA) ?? stringOrUndefined$1(process.env.CF_PAGES_COMMIT_SHA) ?? stringOrUndefined$1(process.env.RENDER_GIT_COMMIT);
265
265
  }
266
266
  let serviceInstanceId;
267
267
  const getServiceInstanceId = () => serviceInstanceId ??= v7();
@@ -301,7 +301,7 @@ const resolveResource = (config) => Effect.gen(function* () {
301
301
  attributes["deployment.commit_sha"] = commitRevision;
302
302
  attributes["vcs.ref.head.revision"] = commitRevision;
303
303
  }
304
- attributes["vcs.repository.url.full"] = stringOrUndefined(process.env.MXL_VCS_REPOSITORY_URL) ?? DEFAULT_VCS_REPOSITORY_URL;
304
+ attributes["vcs.repository.url.full"] = stringOrUndefined$1(process.env.MXL_VCS_REPOSITORY_URL) ?? DEFAULT_VCS_REPOSITORY_URL;
305
305
  Object.assign(attributes, envResourceAttributes);
306
306
  if (config.attributes) Object.assign(attributes, config.attributes);
307
307
  return {
@@ -317,14 +317,14 @@ const resolveResource = (config) => Effect.gen(function* () {
317
317
  }).pipe(Effect.orDie);
318
318
  //#endregion
319
319
  //#region src/server/layer.ts
320
- var layer_exports = /* @__PURE__ */ __exportAll({ layer: () => layer });
320
+ var layer_exports = /* @__PURE__ */ __exportAll({ layer: () => layer$1 });
321
321
  /**
322
322
  * Create an Effect Layer that provides OpenTelemetry traces, logs, and metrics
323
323
  * configured for MXL's OTLP collector.
324
324
  *
325
325
  * Returns a no-op layer when `OTEL_SDK_DISABLED=true`.
326
326
  */
327
- const layer = (config = {}) => Layer.unwrap(Effect.gen(function* () {
327
+ const layer$1 = (config = {}) => Layer.unwrap(Effect.gen(function* () {
328
328
  const resolved = yield* resolveResource({
329
329
  ...config,
330
330
  sdkType: "server"
@@ -341,6 +341,186 @@ const layer = (config = {}) => Layer.unwrap(Effect.gen(function* () {
341
341
  shutdownTimeout: config.shutdownTimeout
342
342
  }).pipe(Layer.provide(FetchHttpClient.layer));
343
343
  })).pipe(Layer.updateService(Tracer.Tracer, wrapTracerWithOtelContextBridge));
344
+ const RESERVED_EVENT_NAMES = ["session_start", "session_end"];
345
+ const isReservedEventName = (name) => RESERVED_EVENT_NAMES.some((reserved) => reserved === name);
346
+ const coerceTrackProps = (props) => {
347
+ if (props === void 0) return {};
348
+ const attributes = {};
349
+ for (const [key, value] of Object.entries(props)) {
350
+ if (value === void 0) continue;
351
+ attributes[key] = typeof value === "string" ? value : String(value);
352
+ }
353
+ return attributes;
354
+ };
355
+ const toEventTimestamp = (value) => (value instanceof Date ? value : new Date(value ?? Date.now())).toISOString();
356
+ const encodeProductEventLine = (input) => {
357
+ const trimmed = typeof input.name === "string" ? input.name.trim() : "";
358
+ if (trimmed.length === 0 || isReservedEventName(trimmed)) return;
359
+ const options = input.options ?? {};
360
+ return {
361
+ attributes: coerceTrackProps(options.attributes),
362
+ group_id: options.groupId ?? "",
363
+ name: trimmed.slice(0, 80),
364
+ page_path: options.pagePath ?? "",
365
+ service_name: input.serviceName,
366
+ session_id: options.sessionId ?? "",
367
+ source: input.source,
368
+ timestamp: toEventTimestamp(options.timestamp),
369
+ traceparent: options.traceparent,
370
+ url: options.url ?? "",
371
+ user_id: options.userId ?? "",
372
+ visitor_id: options.visitorId ?? ""
373
+ };
374
+ };
375
+ const encodeNdjson = (lines) => `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`;
376
+ //#endregion
377
+ //#region src/version.ts
378
+ const SDK_NAME = "mxl-effect-sdk";
379
+ const SDK_VERSION = "0.0.15";
380
+ //#endregion
381
+ //#region src/server/events.ts
382
+ var events_exports = /* @__PURE__ */ __exportAll({
383
+ MxlEvents: () => MxlEvents,
384
+ ProductEventsPostError: () => ProductEventsPostError,
385
+ layer: () => layer,
386
+ make: () => make$1,
387
+ makeHandle: () => makeHandle
388
+ });
389
+ const DEFAULT_FLUSH_INTERVAL = Duration.seconds(5);
390
+ const DEFAULT_MAX_BATCH_SIZE = 100;
391
+ const MAX_BUFFERED_EVENTS = 1e3;
392
+ const WARN_INTERVAL_MS = 3e4;
393
+ const DEFAULT_BASKET_URL = "http://127.0.0.1:8000";
394
+ var MxlEvents = class extends Context.Service()("@safaricom-mxl/effect-sdk/MxlEvents") {};
395
+ var ProductEventsPostError = class extends Schema.TaggedError()("@safaricom-mxl/effect-sdk/ProductEventsPostError", {
396
+ cause: Schema.optionalKey(Schema.Defect()),
397
+ message: Schema.String,
398
+ status: Schema.optionalKey(Schema.Number)
399
+ }) {};
400
+ const stringOrUndefined = (value) => value && value.length > 0 ? value : void 0;
401
+ const resolveEventsConfig = (config) => {
402
+ const endpoint = (config.endpoint ?? process.env.MXL_BASKET_URL ?? DEFAULT_BASKET_URL).replace(/\/$/, "");
403
+ return {
404
+ apiKey: stringOrUndefined(config.apiKey ?? process.env.MXL_API_KEY),
405
+ clientId: stringOrUndefined(config.clientId ?? process.env.MXL_CLIENT_ID),
406
+ serviceName: config.serviceName ?? process.env.OTEL_SERVICE_NAME ?? "unknown",
407
+ url: `${endpoint}${config.eventsPath ?? "/events"}`
408
+ };
409
+ };
410
+ const make$1 = Effect.fn("MxlEvents.make")(function* (config = {}) {
411
+ const resolved = resolveEventsConfig(config);
412
+ const maxBatchSize = Math.max(1, config.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE);
413
+ const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
414
+ const flushing = yield* Semaphore.make(1);
415
+ let buffer = [];
416
+ let warnedAboutName = false;
417
+ let warnedAboutClient = false;
418
+ let lastPostWarnAt = 0;
419
+ const warnPost = (error) => {
420
+ const now = Date.now();
421
+ if (now - lastPostWarnAt < WARN_INTERVAL_MS) return;
422
+ lastPostWarnAt = now;
423
+ console.warn(`[MxlEvents] ${error.message} (dropping batch)`, error.cause ?? "");
424
+ };
425
+ const warnMissingClient = () => {
426
+ if (warnedAboutClient) return;
427
+ warnedAboutClient = true;
428
+ console.warn("[MxlEvents] no client id — set MXL_CLIENT_ID or pass `clientId`; dropping events");
429
+ };
430
+ const warnEmptyName = () => {
431
+ if (warnedAboutName) return;
432
+ warnedAboutName = true;
433
+ console.warn("[MxlEvents] track() needs a non-empty event name; the call was ignored.");
434
+ };
435
+ const post = (lines) => {
436
+ const headers = {
437
+ "mxl-client-id": resolved.clientId ?? "",
438
+ "mxl-sdk-name": SDK_NAME,
439
+ "mxl-sdk-version": SDK_VERSION,
440
+ "user-agent": `${SDK_NAME}-server/${SDK_VERSION}`
441
+ };
442
+ if (resolved.apiKey) headers["mxl-api-key"] = resolved.apiKey;
443
+ return HttpClientRequest.post(resolved.url).pipe(HttpClientRequest.setHeaders(headers), HttpClientRequest.bodyText(encodeNdjson(lines), "application/x-ndjson"), client.execute, Effect.asVoid, Effect.mapError((error) => error.response !== void 0 ? new ProductEventsPostError({
444
+ message: `POST ${resolved.url} → ${error.response.status}`,
445
+ status: error.response.status
446
+ }) : new ProductEventsPostError({
447
+ cause: error,
448
+ message: `POST ${resolved.url} failed: ${error.message}`
449
+ })));
450
+ };
451
+ const flush = flushing.withPermits(1)(Effect.suspend(() => {
452
+ if (buffer.length === 0) return Effect.void;
453
+ const batch = buffer;
454
+ buffer = [];
455
+ if (resolved.clientId === void 0) {
456
+ warnMissingClient();
457
+ return Effect.void;
458
+ }
459
+ return post(batch).pipe(Effect.catchCause((cause) => Effect.sync(() => {
460
+ warnPost(Option.getOrElse(Cause.findErrorOption(cause), () => new ProductEventsPostError({
461
+ cause: Cause.squash(cause),
462
+ message: `POST ${resolved.url} failed`
463
+ })));
464
+ })));
465
+ }));
466
+ const track = (name, options = {}) => Effect.sync(() => {
467
+ const line = encodeProductEventLine({
468
+ name,
469
+ options,
470
+ serviceName: resolved.serviceName,
471
+ source: "server"
472
+ });
473
+ if (line === void 0) {
474
+ warnEmptyName();
475
+ return false;
476
+ }
477
+ buffer.push(line);
478
+ if (buffer.length > MAX_BUFFERED_EVENTS) buffer.splice(0, buffer.length - MAX_BUFFERED_EVENTS);
479
+ return buffer.length >= maxBatchSize;
480
+ }).pipe(Effect.flatMap((full) => full ? Effect.forkDetach(flush) : Effect.void), Effect.asVoid);
481
+ const interval = config.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
482
+ if (Duration.toMillis(interval) > 0) yield* Effect.forkScoped(flush.pipe(Effect.schedule(Schedule.spaced(interval))));
483
+ yield* Effect.addFinalizer(() => flush);
484
+ return {
485
+ flush,
486
+ track
487
+ };
488
+ });
489
+ const layer = (config = {}) => Layer.effect(MxlEvents, make$1(config)).pipe(Layer.provide(FetchHttpClient.layer));
490
+ const makeHandle = (config = {}) => {
491
+ const runtime = ManagedRuntime.make(layer(config));
492
+ const swallow = (promise) => promise.then(() => void 0, () => void 0);
493
+ return {
494
+ dispose: () => swallow(runtime.dispose()),
495
+ flush: () => swallow(runtime.runPromise(Effect.gen(function* () {
496
+ yield* (yield* MxlEvents).flush;
497
+ }))),
498
+ track: (name, options) => {
499
+ swallow(runtime.runPromise(Effect.gen(function* () {
500
+ yield* (yield* MxlEvents).track(name, options);
501
+ })));
502
+ }
503
+ };
504
+ };
505
+ //#endregion
506
+ //#region src/server/flushable.ts
507
+ var flushable_exports = /* @__PURE__ */ __exportAll({ make: () => make });
508
+ const make = (config = {}) => {
509
+ const eventsConfig = {
510
+ apiKey: config.apiKey,
511
+ clientId: config.clientId,
512
+ endpoint: config.ingestUrl,
513
+ flushInterval: config.autoFlushInterval === false ? 0 : config.autoFlushInterval,
514
+ serviceName: config.serviceName
515
+ };
516
+ const handle = makeHandle(eventsConfig);
517
+ return {
518
+ dispose: handle.dispose,
519
+ flush: handle.flush,
520
+ layer: Layer.mergeAll(layer$1(config), layer(eventsConfig)),
521
+ track: handle.track
522
+ };
523
+ };
344
524
  //#endregion
345
525
  //#region src/server/http-middleware.ts
346
526
  function shouldDisableHttpTrace(request) {
@@ -704,7 +884,7 @@ function assignTraceFields(event, traceId, spanId, overwrite) {
704
884
  /**
705
885
  * Enrich evlog wide events with trace/span IDs from OTel global context or W3C headers.
706
886
  *
707
- * Use in the MXL evlog enricher chain alongside `createOtelTraceEnricher`.
887
+ * Use `createEffectTraceEnricher` in the MXL evlog enricher chain.
708
888
  */
709
889
  function createEffectTraceEnricher(options = {}) {
710
890
  const overwrite = options.overwrite ?? false;
@@ -825,6 +1005,6 @@ async function withPromiseDependencySpan(name, attributes, operation, kind = "cl
825
1005
  });
826
1006
  }
827
1007
  //#endregion
828
- export { minimumLogLevelLayer as A, layer_exports as B, withParentFromTraceparent as C, logError as D, logDebug as E, getEffectTraceCorrelation as F, normalizeOtlpBaseUrl as G, getAutoPlatformAttributes as H, parseTraceparent as I, otelGlobalContextBridgeLayer as J, buildTraceCarrierFromSpan as K, traceCorrelationLogAnnotations as L, resolveLogLevelFromEnv as M, serializeLogError as N, logInfo as O, annotateLogsWithActiveSpanCorrelation as P, shouldDisableHttpTrace as R, withParentFromTraceCarrier as S, logAtLevel as T, parseOtelResourceAttributes as U, derivePlatformAttributes as V, parseOtlpHeaders as W, wrapTracerWithOtelContextBridge as Y, logHttpResponse as _, kafkaProducerSpanAttributes as a, spanContextFromTraceparent as b, withDependencySpan as c, jobWithSpanEffect as d, runJobWithSpan as f, logHttpRequestFailure as g, finalizeHttpSpan as h, geoSpanAttributes as i, resolveEffectLogLevelFromHttpStatus as j, logWarning as k, withPromiseDependencySpan as l, buildQueueTraceCarrierEffect as m, bufferSpanAttributes as n, queueConsumerSpanAttributes as o, buildQueueTraceCarrier as p, formatTraceparent as q, dbClientSpanAttributes as r, queueProducerSpanAttributes as s, addSpanLinksFromTraceCarriers as t, createEffectTraceEnricher as u, resolveTraceparentFromHeaders as v, buildHttpStatusLogFields as w, withHttpServerSpan as x, spanContextFromCarrier as y, tracerDisabledWhenLayer as z };
1008
+ export { minimumLogLevelLayer as A, flushable_exports as B, withParentFromTraceparent as C, logError as D, logDebug as E, getEffectTraceCorrelation as F, parseOtelResourceAttributes as G, layer_exports as H, parseTraceparent as I, buildTraceCarrierFromSpan as J, parseOtlpHeaders as K, traceCorrelationLogAnnotations as L, resolveLogLevelFromEnv as M, serializeLogError as N, logInfo as O, annotateLogsWithActiveSpanCorrelation as P, shouldDisableHttpTrace as R, withParentFromTraceCarrier as S, logAtLevel as T, derivePlatformAttributes as U, events_exports as V, getAutoPlatformAttributes as W, otelGlobalContextBridgeLayer as X, formatTraceparent as Y, wrapTracerWithOtelContextBridge as Z, logHttpResponse as _, kafkaProducerSpanAttributes as a, spanContextFromTraceparent as b, withDependencySpan as c, jobWithSpanEffect as d, runJobWithSpan as f, logHttpRequestFailure as g, finalizeHttpSpan as h, geoSpanAttributes as i, resolveEffectLogLevelFromHttpStatus as j, logWarning as k, withPromiseDependencySpan as l, buildQueueTraceCarrierEffect as m, bufferSpanAttributes as n, queueConsumerSpanAttributes as o, buildQueueTraceCarrier as p, normalizeOtlpBaseUrl as q, dbClientSpanAttributes as r, queueProducerSpanAttributes as s, addSpanLinksFromTraceCarriers as t, createEffectTraceEnricher as u, resolveTraceparentFromHeaders as v, buildHttpStatusLogFields as w, withHttpServerSpan as x, spanContextFromCarrier as y, tracerDisabledWhenLayer as z };
829
1009
 
830
- //# sourceMappingURL=server-Dz6g7ADZ.mjs.map
1010
+ //# sourceMappingURL=server-DU685moi.mjs.map