diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..ae64359 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +//registry.npmjs.org/:_authToken=${NPM_TOKEN} diff --git a/README.md b/README.md index b703116..55c9c41 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,23 @@ duck.warn('Slow query', { ms: 1200 }); Before process exit, await `duck.flush()` so queued HTTP work finishes (for example at the end of an `async main()`). +### Reserved `_duck` on log payloads + +The second argument to `log` / `debug` / `warn` / `error` / `fatal` may be a plain object with a reserved **`_duck`** field for technical metadata. **`_duck` is not sent inside `context`** on the wire. + +- **`_duck.dTags`** — sets top-level `dTags` on the ingest event (same as in a raw JSON body). +- **`_duck.scope`** — one-shot `Partial` merged into **this** log only (after global `setScope`, before fixed fields). Use e.g. `platform: "ios"` to override the default `"node"`. Optional **`_duck.scope.context`** is used as the event `context` only when there are no other keys besides `_duck`. + +Any other keys on the object become **`context`**, which matches typical ingest JSON (`dTags` at the root, domain fields under `context`). + +```typescript +duck.warn("DUCKBUG_DTAGS_SMOKE_TEST", { + source: "initDuckBugDeviceContext", + platform: "ios", + _duck: { dTags: ["smoke-test", "dtags"] }, +}); +``` + ## Full usage example End-to-end pattern for a Node/Bun service: DSN from env, scope (release, user, fingerprint), privacy pipeline, `beforeSend`, batched transport with retries, transport errors, console forwarding, global error handlers, structured logs, manual errors, and clean shutdown. diff --git a/package.json b/package.json index 5b77764..1e4a8bb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@duckbug/js", - "version": "0.1.3", + "version": "1.0.0", "type": "module", "main": "./dist/cjs/index.cjs", "module": "./dist/esm/index.js", diff --git a/src/SDK/DuckSDK.ts b/src/SDK/DuckSDK.ts index 67d72dd..9c946a9 100644 --- a/src/SDK/DuckSDK.ts +++ b/src/SDK/DuckSDK.ts @@ -1,7 +1,6 @@ import type { DuckBugErrorEvent, DuckBugLogEvent, - IngestJsonValue, IngestSharedMetadata, } from "../contract"; import type { @@ -12,6 +11,7 @@ import { processError } from "../DuckBug/DuckBugHelper"; import { finalizeIngestEvent } from "../DuckBug/finalizeIngestEvent"; import type { StrippableIngestSection } from "../DuckBug/stripIngestSections"; import { SDK_IDENTITY } from "../sdkIdentity"; +import { type DuckLogPayload, parseDuckLogPayload } from "./duckLogPayload"; import type { LogLevel } from "./LogLevel"; import { logLevel } from "./LogLevel"; import { LogProvider } from "./LogProvider"; @@ -72,23 +72,23 @@ export class DuckSDK { ).then(() => undefined); } - log(tag: string, payload?: object) { + log(tag: string, payload?: DuckLogPayload) { this.emitLog(logLevel.DEBUG, tag, payload); } - error(tag: string, payload?: object) { + error(tag: string, payload?: DuckLogPayload) { this.emitLog(logLevel.ERROR, tag, payload); } - debug(tag: string, payload?: object) { + debug(tag: string, payload?: DuckLogPayload) { this.emitLog(logLevel.DEBUG, tag, payload); } - warn(tag: string, payload?: object) { + warn(tag: string, payload?: DuckLogPayload) { this.emitLog(logLevel.WARN, tag, payload); } - fatal(tag: string, payload?: object) { + fatal(tag: string, payload?: DuckLogPayload) { this.emitLog(logLevel.FATAL, tag, payload); } @@ -155,15 +155,26 @@ export class DuckSDK { return out as DuckBugErrorEvent; } - private emitLog(level: LogLevel, message: string, payload?: object) { + private emitLog(level: LogLevel, message: string, payload?: DuckLogPayload) { + const { scopePatch, context, dTags } = parseDuckLogPayload(payload); + const platform = + scopePatch.platform !== undefined && + typeof scopePatch.platform === "string" + ? scopePatch.platform + : "node"; + const scopeForSpread = { ...scopePatch } as Record; + delete scopeForSpread.platform; + const event: DuckBugLogEvent = this.mergeScope({ + ...scopeForSpread, time: Date.now(), level, message, - platform: "node", + platform, sdk: { ...SDK_IDENTITY }, - ...(payload !== undefined ? { context: payload as IngestJsonValue } : {}), - }); + ...(dTags !== undefined ? { dTags } : {}), + ...(context !== undefined ? { context } : {}), + } as DuckBugLogEvent); const finalized = finalizeIngestEvent(event, { extraSensitiveKeys: this.extraSensitiveKeys, stripSections: this.stripSections, diff --git a/src/SDK/duckLogPayload.ts b/src/SDK/duckLogPayload.ts new file mode 100644 index 0000000..092e058 --- /dev/null +++ b/src/SDK/duckLogPayload.ts @@ -0,0 +1,101 @@ +import type { IngestJsonValue, IngestSharedMetadata } from "../contract"; + +/** + * Reserved key on the second argument to `Duck` / `DuckSDK` log methods. + * Not sent inside `context` on the wire. + */ +export type DuckReservedMeta = { + dTags?: string[]; + /** One-shot metadata merged into this log only (after global `setScope`, before fixed fields). */ + scope?: Partial; +}; + +export type DuckLogPayload = Record & { + _duck?: DuckReservedMeta; +}; + +/** Log event fields applied by emitLog; strip if passed via `_duck.scope`. */ +const EMIT_OWNED = ["time", "level", "message", "sdk"] as const; + +/** + * Splits the optional second argument into scope-like fields, `dTags`, and `context`. + * - Plain object: strips `_duck`, remaining keys become `context` if non-empty. + * - Non-plain-object payload: entire value becomes `context` (legacy). + */ +export function parseDuckLogPayload(payload: object | undefined): { + scopePatch: Partial; + context: IngestJsonValue | undefined; + dTags: string[] | undefined; +} { + if (payload === undefined) { + return { scopePatch: {}, context: undefined, dTags: undefined }; + } + // `typeof null === "object"` — treat null like other non-object contexts. + if ( + payload === null || + Array.isArray(payload) || + typeof payload !== "object" + ) { + return { + scopePatch: {}, + context: payload as IngestJsonValue, + dTags: undefined, + }; + } + + const rec = { ...(payload as Record) }; + const rawDuck = rec._duck; + delete rec._duck; + + let reserved: DuckReservedMeta | undefined; + if ( + rawDuck !== null && + typeof rawDuck === "object" && + !Array.isArray(rawDuck) + ) { + reserved = rawDuck as DuckReservedMeta; + } + + const hasRest = Object.keys(rec).length > 0; + const restContext = hasRest ? (rec as IngestJsonValue) : undefined; + + let scopeContext: IngestJsonValue | undefined; + let scopePatch: Partial = {}; + const inner = reserved?.scope; + if ( + inner !== undefined && + typeof inner === "object" && + !Array.isArray(inner) + ) { + const s = inner as IngestSharedMetadata & { context?: IngestJsonValue }; + scopeContext = s.context; + const { context: _c, ...restScope } = s; + scopePatch = { ...restScope }; + } + + for (const k of EMIT_OWNED) { + delete (scopePatch as Record)[k]; + } + + let context: IngestJsonValue | undefined; + if (hasRest) { + context = restContext; + } else if (scopeContext !== undefined) { + context = scopeContext; + } + + let dTags: string[] | undefined; + if (reserved?.dTags !== undefined) { + dTags = reserved.dTags; + } else if (scopePatch.dTags !== undefined) { + dTags = scopePatch.dTags; + } + + const { dTags: _scopeDtags, ...scopePatchNoDtags } = scopePatch; + + return { + scopePatch: scopePatchNoDtags, + context, + dTags, + }; +} diff --git a/src/SDK/index.ts b/src/SDK/index.ts index ff6cb56..7aabc88 100644 --- a/src/SDK/index.ts +++ b/src/SDK/index.ts @@ -1,6 +1,10 @@ export type { Provider, SendEventMeta } from "../SDK/Provider"; export type { DuckSDKOptions } from "./DuckSDK"; export { Duck, DuckSDK } from "./DuckSDK"; +export type { + DuckLogPayload, + DuckReservedMeta, +} from "./duckLogPayload"; export type { LogLevel } from "./LogLevel"; export { logLevel } from "./LogLevel"; export { LogProvider } from "./LogProvider"; diff --git a/tests/SDK/DuckSDK.test.ts b/tests/SDK/DuckSDK.test.ts index d10cba3..7226a07 100644 --- a/tests/SDK/DuckSDK.test.ts +++ b/tests/SDK/DuckSDK.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, mock } from "bun:test"; +import { beforeEach, describe, expect, it, mock, spyOn } from "bun:test"; import type { LogProviderConfig, Provider } from "../../src/SDK"; import { Duck, DuckSDK } from "../../src/SDK/DuckSDK"; import { logLevel } from "../../src/SDK/LogLevel"; @@ -250,6 +250,127 @@ describe("DuckSDK", () => { }); }); + describe("_duck log payload", () => { + beforeEach(() => { + sdk = new DuckSDK(providers); + }); + + it("maps dTags to top level and domain fields to context (ingest curl shape)", () => { + const spy = spyOn(Date, "now").mockReturnValue(1_704_067_200_000); + + sdk.warn("DUCKBUG_DTAGS_SMOKE_TEST", { + source: "initDuckBugDeviceContext", + platform: "ios", + _duck: { dTags: ["smoke-test", "dtags"] }, + }); + + expect(mockProvider1.sendLog).toHaveBeenCalledWith( + expect.objectContaining({ + time: 1_704_067_200_000, + level: logLevel.WARN, + message: "DUCKBUG_DTAGS_SMOKE_TEST", + dTags: ["smoke-test", "dtags"], + context: { + source: "initDuckBugDeviceContext", + platform: "ios", + }, + }), + SDK_SKIP_PIPELINE, + ); + const body = (mockProvider1.sendLog as ReturnType).mock + .calls[0][0] as { context?: Record }; + expect(body.context?._duck).toBeUndefined(); + spy.mockRestore(); + }); + + it("uses _duck.scope.context when payload has no other keys", () => { + sdk.warn("ONLY_SCOPE_CTX", { + _duck: { + scope: { + context: { a: 1 }, + release: "1.0.0", + }, + }, + }); + expect(mockProvider1.sendLog).toHaveBeenCalledWith( + expect.objectContaining({ + message: "ONLY_SCOPE_CTX", + context: { a: 1 }, + release: "1.0.0", + }), + SDK_SKIP_PIPELINE, + ); + }); + + it("prefers root payload over _duck.scope.context for context", () => { + sdk.warn("ROOT_WINS", { + b: 2, + _duck: { + scope: { + context: { a: 1 }, + }, + }, + }); + expect(mockProvider1.sendLog).toHaveBeenCalledWith( + expect.objectContaining({ + context: { b: 2 }, + }), + SDK_SKIP_PIPELINE, + ); + }); + + it("applies _duck.scope.platform over default node", () => { + sdk.warn("PLATFORM", { + _duck: { scope: { platform: "ios" } }, + }); + expect(mockProvider1.sendLog).toHaveBeenCalledWith( + expect.objectContaining({ + platform: "ios", + }), + SDK_SKIP_PIPELINE, + ); + }); + + it("uses dTags from _duck.scope when _duck.dTags omitted", () => { + sdk.warn("TAG", { + _duck: { scope: { dTags: ["from-scope"] } }, + }); + expect(mockProvider1.sendLog).toHaveBeenCalledWith( + expect.objectContaining({ + dTags: ["from-scope"], + }), + SDK_SKIP_PIPELINE, + ); + }); + + it("_duck.dTags overrides scope.dTags", () => { + sdk.warn("TAG", { + _duck: { + dTags: ["reserved"], + scope: { dTags: ["ignored"] }, + }, + }); + expect(mockProvider1.sendLog).toHaveBeenCalledWith( + expect.objectContaining({ + dTags: ["reserved"], + }), + SDK_SKIP_PIPELINE, + ); + }); + + it("treats null payload as context null (typeof null is object)", () => { + // @ts-expect-error intentional loose call + sdk.log("NULL_CTX", null); + expect(mockProvider1.sendLog).toHaveBeenCalledWith( + expect.objectContaining({ + message: "NULL_CTX", + context: null, + }), + SDK_SKIP_PIPELINE, + ); + }); + }); + describe("quack", () => { beforeEach(() => { sdk = new DuckSDK(providers);